forked from louisalflame/WebTraceCollector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crawler.py
587 lines (518 loc) · 25.8 KB
/
crawler.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Module docstring
"""
import os, sys, json, posixpath, time, datetime, codecs, logging, random, copy, string
from abc import ABCMeta, abstractmethod
from automata import Automata, State, Edge
from visualizer import Visualizer
from dom_analyzer import DomAnalyzer
from configuration import MutationMethod
from mutation import Mutation
from bs4 import BeautifulSoup
if sys.version_info.major >= 3:
from urllib.parse import urlparse
else:
from urlparse import urlparse
class Crawler:
__metaclass__ = ABCMeta
@abstractmethod
def run(self):
pass
#==============================================================================================================================
# Selenium Web Driver
#==============================================================================================================================
class SeleniumCrawler(Crawler):
def __init__(self, configuration, executor, automata, databank, algorithm):
self.configuration = configuration
self.executor = executor
self.automata = automata
self.databank = databank
#ALGO
self.algorithm = algorithm
self.algorithm.set_utility(self, configuration, executor, automata)
#list of event:(state, clickable, inputs, selects, iframe_list)
self.event_history = []
def run(self):
#start time
self.time_start = time.time()
self.executor.start()
self.executor.goto_url()
initial_state = self.get_initail_state()
self.run_script_before_crawl(initial_state)
self.crawl(1)
return self.automata
#the core
def run_algorithm(self):
# repeat for trace_amount times
for i in range( self.configuration.get_trace_amount() ):
print ('=initial state')
self.initial()
print ('=get into loop')
j=0
while self.action_events and self.configuration.get_max_depth() != 0:
print('==start an action event')
#string = ''.join([ str(action['action']['clickable'].get_id())+str(action['depth'])+str(action['state'].get_id()) for action in self.action_events ])
string = ''.join([ str(action['depth'])+str(action['state'].get_id()) for action in self.action_events ])
logging.info(' action_events : '+string )
#print(' action_events : '+string)
print('==get next action')
state, action, depth = self.get_next_action()
print('==change state')
self.change_state(state, action, depth)
print('==change edge')
edge = self.trigger_action(state, action, depth)
print('==update state')
new_state,new_depth =self.update_states(state, edge, action, depth)
print('==end an action event')
print ("new depth:", new_depth)
print ("max depth:", self.configuration.get_max_depth())
print ("new state:", new_state.get_id(),j)
print ("max state:", self.configuration.get_max_states())
#check depth
if new_depth > self.configuration.get_max_depth():
print("reach max depth")
#check state
if int(new_state.get_id()) >= self.configuration.get_max_states():
print("reach max state")
break
#check time
if (time.time() - self.time_start) > self.configuration.get_max_time():
logging.info("|||| TIMO OUT |||| end crawl ")
break
j=j+1
print('=end a for_loop')
self.close()
return self.automata
def initial(self):
self.action_events = []
#start time
self.time_start = time.time()
print('==prepare algorithm')
self.algorithm.prepare()
print('==get current state && add new events')
current_state = self.automata.get_current_state()
self.add_new_events(current_state, None, 0)
def close(self):
self.algorithm.end()
self.executor.close()
print("close browser")
def get_next_action(self):
event = self.algorithm.get_next_action( self.action_events )
return event['state'], event['action'], event['depth']
def change_state(self, state, action, depth):
current_state = self.automata.get_current_state()
if current_state != state:
self.algorithm.change_state(state, action, depth)
logging.info(' now depth(%s) - max_depth(%s); current state: %s', depth, self.configuration.get_max_depth(), state.get_id() )
def trigger_action(self, state, action, depth):
inputs = state.get_copy_inputs( action['iframe_key'] )
selects = state.get_copy_selects(action['iframe_key'])
checkboxes = state.get_copy_checkboxes(action['iframe_key'])
radios = state.get_copy_radios(action['iframe_key'])
new_edge = Edge(state.get_id(), None, action['clickable'], inputs, selects, checkboxes, radios, action['iframe_key'] )
self.algorithm.trigger_action( state, new_edge, action, depth )
return new_edge
#have to run two automata in p2b2?
def update_states(self, current_state, new_edge, action, depth):
dom_list, url, is_same = self.is_same_state_dom(current_state)
if is_same:
self.algorithm.update_with_same_state(current_state, new_edge, action, depth, dom_list, url)
return current_state,depth
if self.is_same_domain(url):
logging.info(' |depth:%s state:%s| change dom to: %s', depth, current_state.get_id(), self.executor.get_url())
# check if this is a new state
temp_state = State(dom_list, url)
new_state, is_newly_added = self.automata.add_state(temp_state)
self.automata.add_edge(new_edge, new_state.get_id())
# save this click edge
current_state.add_clickable(action['clickable'], action['iframe_key'])
self.automata.change_state(new_state)
# depth GO ON
depth += 1
self.event_history.append(new_edge)
if is_newly_added:
self.algorithm.update_with_new_state(current_state, new_state, new_edge, action, depth, dom_list, url)
return new_state,depth
else:
self.algorithm.update_with_old_state(current_state, new_state, new_edge, action, depth, dom_list, url)
return new_state,depth
else:
self.algorithm.update_with_out_of_domain(current_state, new_edge, action, depth, dom_list, url)
return current_state,depth
def add_new_events(self, state, prev_state, depth):
self.algorithm.add_new_events(state, prev_state, depth)
#=========================================================================================
# BASIC CRAWL
#=========================================================================================
def get_initail_state(self):
logging.info(' get initial state')
dom_list, url = self.executor.get_dom_list(self.configuration)
initial_state = State( dom_list, url )
is_new, state = self.automata.set_initial_state(initial_state)
if is_new:
logging.info(' is new, save state')
self.automata.save_state( initial_state, 0)
self.automata.save_state_shot(self.executor, initial_state)
log_list = self.automata.save_log(self.executor,initial_state)
coor_list = self.automata.save_coor(self.executor,initial_state)
else:
self.automata.change_state(state)
time.sleep(self.configuration.get_sleep_time())
print('return state')
return state
def run_script_before_crawl(self, prev_state):
for edge in self.configuration.get_before_script():
#self.click_event_by_edge(edge)
self.executor.click_event_by_edge(edge)
self.event_history.append(edge)
dom_list, url, is_same = self.is_same_state_dom(prev_state)
if is_same:
continue
logging.info(' change dom to: ', self.executor.get_url())
# check if this is a new state
temp_state = State(dom_list, url)
new_state, is_newly_added = self.automata.add_state(temp_state)
self.automata.add_edge(edge, new_state.get_id())
# save this click edge
prev_state.add_clickable(edge.get_clickable(), edge.get_iframe_list())
if is_newly_added:
logging.info(' add new state %s of: %s', new_state.get_id(), url)
self.automata.save_state(new_state, 0)
self.automata.save_state_shot(self.executor, new_state)
self.automata.change_state(new_state)
prev_state = new_state
#=============================================================================================
# BACKTRACK
#=============================================================================================
def backtrack(self, state):
# check if depth over max depth , time over max time
if (time.time() - self.time_start) > self.configuration.get_max_time():
logging.info("|||| TIMO OUT |||| end backtrack ")
return
#if url are same, guess they are just javascipt edges
if self.executor.get_url() == state.get_url():
#first, just refresh for javascript button
logging.info('==<BACKTRACK> : try refresh')
self.executor.refresh()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't , try go back form history
logging.info('==<BACKTRACK> : try back_history ')
self.executor.back_history()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't , try do last edge of state history
if self.event_history:
logging.info('==<BACKTRACK> : try last edge of state history')
self.executor.forward_history()
#self.click_event_by_edge( self.event_history[-1] )
self.executor.click_event_by_edge( self.event_history[-1] )
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't, try go through all edge
logging.info('==<BACKTRACK> : start form base ur')
self.executor.goto_url()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
edges = self.automata.get_shortest_path(state)
for edge in edges:
self.executor.click_event_by_edge( edge )
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't, restart and try go again
logging.info('==<BACKTRACK> : retart driver')
edges = self.automata.get_shortest_path(state)
self.executor.restart_app()
self.executor.goto_url()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
for edge in edges:
self.executor.click_event_by_edge(edge)
#check again if executor really turn back. if not, sth error, stop
state_to = self.automata.get_state_by_id( edge.get_state_to() )
dom_list, url, is_same = self.is_same_state_dom(state_to)
if not is_same:
try:
err = State(dom_list, url)
with open('debug/debug_origin_'+state_to.get_id()+'.txt', 'w') as f:
f.write(state_to.get_all_dom(self.configuration))
with open('debug/debug_restart_'+state_to.get_id()+'.txt', 'w') as f:
f.write(err.get_all_dom(self.configuration))
with open('debug/debug_origin_nor_'+state_to.get_id()+'.txt', 'w') as f:
f.write( state_to.get_all_normalize_dom(self.configuration) )
with open('debug/debug_restart_nor_'+state_to.get_id()+'.txt', 'w') as f:
f.write( err.get_all_normalize_dom(self.configuration) )
logging.error('==<BACKTRACK> cannot traceback to %s \t\t__from crawler.py backtrack()', state_to.get_id() )
except Exception as e:
logging.info('==<BACKTRACK> save diff dom : %s', str(e))
dom_list, url, is_same = self.is_same_state_dom(state)
return is_same
def both_executors_backtrack(self, state, other_executor=None):
# check if depth over max depth , time over max time
logging.info("both exe backtrack")
print("both exe backtrack")
if (time.time() - self.time_start) > self.configuration.get_max_time():
logging.info("|||| TIMO OUT |||| end backtrack ")
return
#if url are same, guess they are just javascipt edges
if self.executor.get_url() == state.get_url() and other_executor.get_url() == state.get_url():
#first, just refresh for javascript button
logging.info('==<BACKTRACK> : try refresh')
self.executor.refresh()
other_executor.refresh()
#!!!!!!!!CBT
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't , try go back form history
logging.info('==<BACKTRACK> : both exe try back_history ')
before_url = self.executor.get_url()
self.executor.back_history()
print('exe back')
dom_list, after_url, is_same = self.is_same_state_dom(state)
if before_url == other_executor.get_url():
other_executor.back_history()
print('other exe back')
if is_same:
return True
#if can't , try do last edge of state history
if self.event_history:
logging.info('==<BACKTRACK> : try last edge of state history')
self.executor.forward_history()
other_executor.forward_history()
self.executor.click_event_by_edge( self.event_history[-1] )
other_executor.click_event_by_edge( self.event_history[-1] )
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't, try go through all edge
logging.info('==<BACKTRACK> : start form base ur')
self.executor.goto_url()
other_executor.goto_url()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
edges = self.automata.get_shortest_path(state)
for edge in edges:
self.executor.click_event_by_edge( edge )
other_executor.click_event_by_edge( edge )
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
#if can't, restart and try go again
logging.info('==<BACKTRACK> : restart driver')
edges = self.automata.get_shortest_path(state)
self.executor.restart_app()
self.executor.goto_url()
other_executor.restart_app()
other_executor.goto_url()
dom_list, url, is_same = self.is_same_state_dom(state)
if is_same:
return True
for edge in edges:
self.executor.click_event_by_edge(edge)
other_executor.click_event_by_edge(edge)
#check again if executor really turn back. if not, sth error, stop
state_to = self.automata.get_state_by_id( edge.get_state_to() )
dom_list, url, is_same = self.is_same_state_dom(state_to)
if not is_same:
try:
err = State(dom_list, url)
with open('debug/debug_origin_'+state_to.get_id()+'.txt', 'w') as f:
f.write(state_to.get_all_dom(self.configuration))
with open('debug/debug_restart_'+state_to.get_id()+'.txt', 'w') as f:
f.write(err.get_all_dom(self.configuration))
with open('debug/debug_origin_nor_'+state_to.get_id()+'.txt', 'w') as f:
f.write( state_to.get_all_normalize_dom(self.configuration) )
with open('debug/debug_restart_nor_'+state_to.get_id()+'.txt', 'w') as f:
f.write( err.get_all_normalize_dom(self.configuration) )
logging.error('==<BACKTRACK> cannot traceback to %s \t\t__from crawler.py backtrack()', state_to.get_id() )
except Exception as e:
logging.info('==<BACKTRACK> save diff dom : %s', str(e))
dom_list, url, is_same = self.is_same_state_dom(state)
return is_same
#=========================================================================================
# EVENT
#=========================================================================================
def make_value(self, edge):
rand = random.randint(0,1000)
for input_field in edge.get_inputs():
data_set = input_field.get_data_set(self.databank)
#check data set
value = data_set[ rand % len(data_set) ] if data_set \
else ''.join( [random.choice(string.lowercase) for i in xrange(8)] )
input_field.set_value(value)
logging.info(" set input:%s value:%s "%(input_field.get_id(), value))
for select_field in edge.get_selects():
data_set = select_field.get_data_set(self.databank)
#check data set
selected = data_set[ rand % len(data_set) ] if data_set \
else random.randint(0, len(select_field.get_value()))
select_field.set_selected(selected)
logging.info(" set select:%s value:%s "%(select_field.get_id(), selected))
for checkbox_field in edge.get_checkboxes():
data_set = checkbox_field.get_data_set(self.databank)
#check data set
selected_list = data_set[ rand % len(data_set) ].split('/') if data_set \
else random.sample( xrange(len(checkbox_field.get_checkbox_list())),
random.randint(0, len(checkbox_field.get_checkbox_list())) )
checkbox_field.set_selected_list(selected_list)
logging.info(" set checkbox:%s value:%s "%(checkbox_field.get_checkbox_name(), str(selected_list)))
for radio_field in edge.get_radios():
data_set = radio_field.get_data_set(self.databank)
#check data set
selected = data_set[ rand % len(data_set) ] if data_set \
else random.randint(0, len(radio_field.get_radio_list()))
radio_field.set_selected(selected)
logging.info(" set radio:%s value:%s "%(radio_field.get_radio_name(), selected))
#=========================================================================================
# DECISION
#=========================================================================================
def is_same_domain(self, url):
base_url = urlparse( self.configuration.get_url() )
new_url = urlparse( url )
if base_url.netloc == new_url.netloc:
return True
else:
for d in self.configuration.get_domains():
d_url = urlparse(d)
if d_url.netloc == new_url.netloc:
return True
return False
def is_same_state_dom(self, cs):
#cs is other executor's state,or previous state
dom_list, url = self.executor.get_dom_list(self.configuration)
cs_dom_list = cs.get_dom_list(self.configuration)
if url != cs.get_url():
return dom_list, url, False
elif len( cs_dom_list ) != len( dom_list ):
return dom_list, url, False
else:
for dom, cs_dom in zip(dom_list, cs_dom_list):
if not dom == cs_dom:
return dom_list, url, False
print ('same dom to: ', cs.get_id())
return dom_list, url, True
def cbt_is_same_state_dom(self, cs):
#cs is other executor
dom_list, url = self.executor.get_dom_list(self.configuration)
cs_dom_list = cs.get_dom_list(self.configuration)
if url != cs.get_url():
str=("urls are different:%s v.s %s",url,cs.get_url())
return str
else:
for dom, cs_dom in zip(dom_list, cs_dom_list):
if not dom == cs_dom:
str=("dom are different")
return str
str = 'same dom to: ', cs.get_id()
return str
#=========================================================================================
# TODO FOR MUTATION
#=========================================================================================
def run_mutant(self):
self.mutation_history = []
self.mutation_cluster = {}
self.mutation = Mutation(self.configuration.get_mutation_trace(), self.databank)
self.mutation_traces = self.make_mutation_traces()
# run a default trace for compare
logging.info(" start run default trace")
self.executor.start()
self.executor.goto_url()
initial_state = self.get_initail_state()
self.run_mutant_script(initial_state)
self.close()
# run all mutation traces
logging.info(' total %d mutation traces ', len(self.mutation_traces))
for n in xrange(len(self.mutation_traces)):
logging.info(" start run number %d mutant trace", n)
self.executor.start()
self.executor.goto_url()
initial_state = self.get_initail_state()
self.run_mutant_script(initial_state, self.mutation_traces[n])
self.close()
self.save_mutation_history()
def make_mutation_traces(self):
self.mutation.set_method(self.configuration.get_mutation_method())
self.mutation.set_modes(self.configuration.get_mutation_modes())
self.mutation.make_data_set()
self.mutation.make_mutation_traces()
# use a int to select sample of mutation traces
mutation_traces = self.mutation.get_mutation_traces()
#mutation_traces = random.sample( mutation_traces,
#min( self.configuration.get_max_mutation_traces(), len(mutation_traces) ) )
return mutation_traces
def run_mutant_script(self, prev_state, mutation_trace=None):
depth = 0
edge_trace = []
state_trace = [prev_state]
# use -1 to mark
cluster_value = prev_state.get_id() if mutation_trace else "-1"+prev_state.get_id()
for edge in self.configuration.get_mutation_trace():
new_edge = edge.get_copy()
new_edge.set_state_from( prev_state.get_id() )
if mutation_trace:
self.make_mutant_value(new_edge, mutation_trace[depth])
self.executor.click_event_by_edge(new_edge)
self.event_history.append(new_edge)
dom_list, url, is_same = self.is_same_state_dom(prev_state)
if not is_same:
logging.info(' change dom to: %s', url)
# check if this is a new state
temp_state = State(dom_list, url)
new_state, is_newly_added = self.automata.add_state(temp_state)
self.automata.add_edge(new_edge, new_state.get_id())
# save this click edge
prev_state.add_clickable(edge.get_clickable(), new_edge.get_iframe_list())
if is_newly_added:
logging.info(' add new state %s of: %s', new_state.get_id(), url)
self.automata.save_state(new_state, depth+1)
self.automata.save_state_shot(self.executor, new_state)
self.automata.change_state(new_state)
# save the state, edge
state_trace.append( new_state )
edge_trace.append( new_edge )
cluster_value += new_state.get_id()
# prepare for next edge
prev_state = new_state
depth += 1
self.mutation_history.append( (edge_trace, state_trace, cluster_value ) )
logging.warning( [ c for e,s,c in self.mutation_history ] )
def cluster_mutation_trace(self):
#then cluster other mutation traces
for edge_trace, state_trace, cluster_value in self.mutation_history:
if cluster_value in self.mutation_cluster:
self.mutation_cluster[cluster_value].append( (edge_trace, state_trace) )
else:
self.mutation_cluster[cluster_value] = [ (edge_trace, state_trace) ]
def save_mutation_history(self):
self.cluster_mutation_trace()
traces_data = {
'method': self.configuration.get_mutation_method(),
'traces': []
}
for cluster_key, mutation_traces in self.mutation_cluster.items():
for edge_trace, state_trace in mutation_traces:
trace_data = {
'edges':[],
'states':[],
'cluster_value': cluster_key
}
for edge in edge_trace:
trace_data['edges'].append(edge.get_edge_json())
for state in state_trace:
trace_data['states'].append(state.get_simple_state_json(self.configuration))
if cluster_key.startswith('-1'):
traces_data['traces'].insert(0, trace_data)
else:
traces_data['traces'].append(trace_data)
with codecs.open(os.path.join(self.configuration.get_abs_path('root'), 'mutation_traces.json'), 'w', encoding='utf-8' ) as f:
json.dump(traces_data, f, indent=2, sort_keys=True, ensure_ascii=False)