-
Notifications
You must be signed in to change notification settings - Fork 346
/
sessions.py
1871 lines (1558 loc) · 75.3 KB
/
sessions.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
import datetime
import errno
import itertools
import logging
import os
import pickle
import socket
import threading
import time
import traceback
import warnings
import zlib
from builtins import input
from io import open
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.wsgi import WSGIContainer
from boofuzz import (
blocks,
constants,
event_hook,
exception,
fuzz_logger,
fuzz_logger_curses,
fuzz_logger_db,
fuzz_logger_text,
helpers,
pgraph,
primitives,
)
from boofuzz.monitors import CallbackMonitor
from boofuzz.mutation_context import MutationContext
from boofuzz.protocol_session import ProtocolSession
from boofuzz.web.app import app
from .exception import BoofuzzFailure
class Target:
"""Target descriptor container.
Takes an ITargetConnection and wraps send/recv with appropriate
FuzzDataLogger calls.
Encapsulates pedrpc connection logic.
Contains a logger which is configured by Session.add_target().
Example:
tcp_target = Target(SocketConnection(host='127.0.0.1', port=17971))
Args:
connection (itarget_connection.ITargetConnection): Connection to system under test.
monitors (List[Union[IMonitor, pedrpc.Client]]): List of Monitors for this Target.
monitor_alive: List of Functions that are called when a Monitor is alive. It is passed
the monitor instance that became alive. Use it to e.g. set options
on restart.
repeater (repeater.Repeater): Repeater to use for sending. Default None.
procmon: Deprecated interface for adding a process monitor.
procmon_options: Deprecated interface for adding a process monitor.
"""
def __init__(
self,
connection,
monitors=None,
monitor_alive=None,
max_recv_bytes=10000,
repeater=None,
procmon=None,
procmon_options=None,
**kwargs
):
self._fuzz_data_logger = None
self._target_connection = connection
self.max_recv_bytes = max_recv_bytes
self.repeater = repeater
self.monitors = monitors if monitors is not None else []
if procmon is not None:
if procmon_options is not None:
procmon.set_options(**procmon_options)
self.monitors.append(procmon)
self.monitor_alive = monitor_alive if monitor_alive is not None else []
if "procmon" in kwargs.keys() and kwargs["procmon"] is not None:
warnings.warn(
"Target(procmon=...) is deprecated. Please change your code"
" and add it to the monitors argument. For now, we do this "
"for you, but this will be removed in the future.",
FutureWarning,
)
self.monitors.append(kwargs["procmon"])
if "netmon" in kwargs.keys() and kwargs["netmon"] is not None:
warnings.warn(
"Target(netmon=...) is deprecated. Please change your code"
" and add it to the monitors argument. For now, we do this "
"for you, but this will be removed in the future.",
FutureWarning,
)
self.monitors.append(kwargs["netmon"])
# set these manually once target is instantiated.
self.vmcontrol = None
self.vmcontrol_options = {}
@property
def netmon_options(self):
raise NotImplementedError(
"This property is not supported; grab netmon from monitors and use set_options(**dict)"
)
@property
def procmon_options(self):
raise NotImplementedError(
"This property is not supported; grab procmon from monitors and use set_options(**dict)"
)
def close(self):
"""
Close connection to the target.
:return: None
"""
self._fuzz_data_logger.log_info("Closing target connection...")
self._target_connection.close()
self._fuzz_data_logger.log_info("Connection closed.")
def open(self):
"""
Opens connection to the target. Make sure to call close!
:return: None
"""
self._fuzz_data_logger.log_info("Opening target connection ({0})...".format(self._target_connection.info))
self._target_connection.open()
self._fuzz_data_logger.log_info("Connection opened.")
def pedrpc_connect(self):
warnings.warn(
"pedrpc_connect has been renamed to monitors_alive. "
"This alias will stop working in a future version of boofuzz.",
FutureWarning,
)
return self.monitors_alive()
def monitors_alive(self):
"""
Wait for the monitors to become alive / establish connection to the RPC server.
This method is called on every restart of the target and when it's added to a session.
After successful probing, a callback is called, passing the monitor.
:return: None
"""
for monitor in self.monitors:
while True:
if monitor.alive():
break
time.sleep(1)
if self.monitor_alive:
for cb in self.monitor_alive:
cb(monitor)
def recv(self, max_bytes=None):
"""
Receive up to max_bytes data from the target.
Args:
max_bytes (int): Maximum number of bytes to receive.
Returns:
Received data.
"""
if max_bytes is None:
max_bytes = self.max_recv_bytes
if self._fuzz_data_logger is not None:
self._fuzz_data_logger.log_info("Receiving...")
data = self._target_connection.recv(max_bytes=max_bytes)
if self._fuzz_data_logger is not None:
self._fuzz_data_logger.log_recv(data)
return data
def send(self, data):
"""
Send data to the target. Only valid after calling open!
Args:
data: Data to send.
Returns:
None
"""
num_sent = 0
if self._fuzz_data_logger is not None:
repeat = ""
if self.repeater is not None:
repeat = ", " + self.repeater.log_message()
self._fuzz_data_logger.log_info("Sending {0} bytes{1}...".format(len(data), repeat))
if self.repeater is not None:
self.repeater.start()
while self.repeater.repeat():
num_sent = self._target_connection.send(data=data)
self.repeater.reset()
else:
num_sent = self._target_connection.send(data=data)
if self._fuzz_data_logger is not None:
self._fuzz_data_logger.log_send(data[:num_sent])
def set_fuzz_data_logger(self, fuzz_data_logger):
"""
Set this object's fuzz data logger -- for sent and received fuzz data.
:param fuzz_data_logger: New logger.
:type fuzz_data_logger: ifuzz_logger.IFuzzLogger
:return: None
"""
self._fuzz_data_logger = fuzz_data_logger
class Connection(pgraph.Edge):
def __init__(self, src, dst, callback=None):
"""
Extends pgraph.edge with a callback option. This allows us to register a function to call between node
transmissions to implement functionality such as challenge response systems. The callback method must follow
this prototype::
def callback(target, fuzz_data_logger, session, node, edge, *args, **kwargs)
Where node is the node about to be sent, edge is the last edge along the current fuzz path to "node", session
is a pointer to the session instance which is useful for snagging data such as sesson.last_recv which contains
the data returned from the last socket transmission and sock is the live socket. A callback is also useful in
situations where, for example, the size of the next packet is specified in the first packet.
Args:
src (int): Edge source ID
dst (int): Edge destination ID
callback (function): Optional. Callback function to pass received data to between node xmits
"""
super(Connection, self).__init__(src, dst)
self.callback = callback
class SessionInfo:
def __init__(self, db_filename):
self._db_reader = fuzz_logger_db.FuzzLoggerDbReader(db_filename=db_filename)
@property
def monitor_results(self):
return self._db_reader.failure_map
@property
def monitor_data(self):
return {-1, "Monitor Data is not currently saved in the database"}
@property
def procmon_results(self):
warnings.warn(
"procmon_results has been renamed to monitor_results."
"This alias will stop working in a future version of boofuzz",
FutureWarning,
)
return self.monitor_results
@property
def netmon_results(self):
warnings.warn(
"netmon_results is now part of monitor_data" "This alias will stop working in a future version of boofuzz",
FutureWarning,
)
return self.monitor_data
@property
def fuzz_node(self):
return None
@property
def total_num_mutations(self):
return None
@property
def total_mutant_index(self):
x = next(self._db_reader.query("SELECT COUNT(*) FROM cases"))[0]
return x
@property
def mutant_index(self):
return None
def test_case_data(self, index):
"""Return test case data object (for use by web server)
Args:
index (int): Test case index
Returns:
Test case data object
"""
return self._db_reader.get_test_case_data(index=index)
@property
def is_paused(self):
return False
@property
def state(self):
return "finished"
@property
def exec_speed(self):
return 0
@property
def runtime(self):
return 0
@property
def current_test_case_name(self):
return ""
class WebApp:
"""Serve fuzz data over HTTP.
Args:
session_info (SessionInfo): Object providing information on session
web_port (int): Port for monitoring fuzzing campaign via a web browser. Default 26000.
web_address (string): Address binded to port for monitoring fuzzing campaign via a web browser.
Default 'localhost'.
"""
def __init__(
self, session_info, web_port=constants.DEFAULT_WEB_UI_PORT, web_address=constants.DEFAULT_WEB_UI_ADDRESS
):
self._session_info = session_info
self._web_interface_thread = self._build_webapp_thread(port=web_port, address=web_address)
pass
def _build_webapp_thread(self, port, address):
app.session = self._session_info
http_server = HTTPServer(WSGIContainer(app))
http_server.listen(port, address=address)
flask_thread = threading.Thread(target=IOLoop.instance().start)
flask_thread.daemon = True
return flask_thread
def server_init(self):
"""Called by fuzz() to initialize variables, web interface, etc."""
if not self._web_interface_thread.is_alive():
# spawn the web interface.
self._web_interface_thread.start()
def open_test_run(db_filename, port=constants.DEFAULT_WEB_UI_PORT, address=constants.DEFAULT_WEB_UI_ADDRESS):
s = SessionInfo(db_filename=db_filename)
w = WebApp(session_info=s, web_port=port, web_address=address)
w.server_init()
class Session(pgraph.Graph):
"""
Extends pgraph.graph and provides a container for architecting protocol dialogs.
Args:
session_filename (str): Filename to serialize persistent data to. Default None.
index_start (int); First test case index to run
index_end (int); Last test case index to run
sleep_time (float): Time in seconds to sleep in between tests. Default 0.
restart_interval (int): Restart the target after n test cases, disable by setting to 0 (default).
console_gui (bool): Use curses to generate a static console screen similar to the webinterface. Has not been
tested under Windows. Default False.
crash_threshold_request (int): Maximum number of crashes allowed before a request is exhausted. Default 12.
crash_threshold_element (int): Maximum number of crashes allowed before an element is exhausted. Default 3.
restart_sleep_time (int): Time in seconds to sleep when target can't be restarted. Default 5.
restart_callbacks (list of method): The registered method will be called after a failed post_test_case_callback
Default None.
restart_threshold (int): Maximum number of retries on lost target connection. Default None (indefinitely).
restart_timeout (float): Time in seconds for that a connection attempt should be retried. Default None
(indefinitely).
pre_send_callbacks (list of method): The registered method will be called prior to each fuzz request.
Default None.
post_test_case_callbacks (list of method): The registered method will be called after each fuzz test case.
Default None.
post_start_target_callbacks (list of method): Method(s) will be called after the target is started or restarted,
say, by a process monitor.
web_port (int or None): Port for monitoring fuzzing campaign via a web browser. Set to None to disable the web
app. Default 26000.
keep_web_open (bool): Keep the webinterface open after session completion. Default True.
fuzz_loggers (list of ifuzz_logger.IFuzzLogger): For saving test data and results.. Default Log to STDOUT.
fuzz_db_keep_only_n_pass_cases (int): Minimize disk usage by only saving passing test cases
if they are in the n test cases preceding a failure or error.
Set to 0 to save after every test case (high disk I/O!). Default 0.
receive_data_after_each_request (bool): If True, Session will attempt to receive a reply after transmitting
each non-fuzzed node. Default True.
check_data_received_each_request (bool): If True, Session will verify that some data has
been received after transmitting each non-fuzzed node, and if not,
register a failure. If False, this check will not be performed. Default
False. A receive attempt is still made unless
receive_data_after_each_request is False.
receive_data_after_fuzz (bool): If True, Session will attempt to receive a reply after transmitting
a fuzzed message. Default False.
ignore_connection_reset (bool): Log ECONNRESET errors ("Target connection reset") as "info" instead of
failures.
ignore_connection_aborted (bool): Log ECONNABORTED errors as "info" instead of failures.
ignore_connection_issues_when_sending_fuzz_data (bool): Ignore fuzz data transmission failures. Default True.
This is usually a helpful setting to enable, as targets may drop connections once a
message is clearly invalid.
ignore_connection_ssl_errors (bool): Log SSL related errors as "info" instead of failures. Default False.
reuse_target_connection (bool): If True, only use one target connection instead of reconnecting each test case.
Default False.
target (Target): Target for fuzz session. Target must be fully initialized. Default None.
db_filename (str): Filename to store sqlite db for test results and case information.
Defaults to ./boofuzz-results/{uniq_timestamp}.db
web_address: Address where's Boofuzz logger exposed. Default 'localhost'
"""
def __init__(
self,
session_filename=None,
index_start=1,
index_end=None,
sleep_time=0.0,
restart_interval=0,
web_port=constants.DEFAULT_WEB_UI_PORT,
keep_web_open=True,
console_gui=False,
crash_threshold_request=12,
crash_threshold_element=3,
restart_sleep_time=5,
restart_callbacks=None,
restart_threshold=None,
restart_timeout=None,
pre_send_callbacks=None,
post_test_case_callbacks=None,
post_start_target_callbacks=None,
fuzz_loggers=None,
fuzz_db_keep_only_n_pass_cases=0,
receive_data_after_each_request=True,
check_data_received_each_request=False,
receive_data_after_fuzz=False,
ignore_connection_reset=False,
ignore_connection_aborted=False,
ignore_connection_issues_when_sending_fuzz_data=True,
ignore_connection_ssl_errors=False,
reuse_target_connection=False,
target=None,
web_address=constants.DEFAULT_WEB_UI_ADDRESS,
db_filename=None,
):
self._ignore_connection_reset = ignore_connection_reset
self._ignore_connection_aborted = ignore_connection_aborted
self._ignore_connection_issues_when_sending_fuzz_data = ignore_connection_issues_when_sending_fuzz_data
self._reuse_target_connection = reuse_target_connection
self._ignore_connection_ssl_errors = ignore_connection_ssl_errors
super(Session, self).__init__()
self.session_filename = session_filename
self._index_start = max(index_start, 1)
self._index_end = index_end
self.sleep_time = sleep_time
self.restart_interval = restart_interval
self.web_port = web_port
self._keep_web_open = keep_web_open
self.console_gui = console_gui
self._crash_threshold_node = crash_threshold_request
self._crash_threshold_element = crash_threshold_element
self.restart_sleep_time = restart_sleep_time
self.restart_threshold = restart_threshold
self.restart_timeout = restart_timeout
self.web_address = web_address
if fuzz_loggers is None:
fuzz_loggers = []
if self.console_gui and os.name != "nt":
fuzz_loggers.append(
fuzz_logger_curses.FuzzLoggerCurses(web_port=self.web_port, web_address=self.web_address)
)
self._keep_web_open = False
else:
fuzz_loggers = [fuzz_logger_text.FuzzLoggerText()]
self._run_id = datetime.datetime.utcnow().replace(microsecond=0).isoformat().replace(":", "-")
if db_filename is not None:
helpers.mkdir_safe(db_filename, file_included=True)
self._db_filename = db_filename
else:
helpers.mkdir_safe(os.path.join(constants.RESULTS_DIR))
self._db_filename = os.path.join(constants.RESULTS_DIR, "run-{0}.db".format(self._run_id))
self._db_logger = fuzz_logger_db.FuzzLoggerDb(
db_filename=self._db_filename, num_log_cases=fuzz_db_keep_only_n_pass_cases
)
self._crash_filename = "boofuzz-crash-bin-{0}".format(self._run_id)
self._fuzz_data_logger = fuzz_logger.FuzzLogger(fuzz_loggers=[self._db_logger] + fuzz_loggers)
self._check_data_received_each_request = check_data_received_each_request
self._receive_data_after_each_request = receive_data_after_each_request
self._receive_data_after_fuzz = receive_data_after_fuzz
self._skip_current_node_after_current_test_case = False
self._skip_current_element_after_current_test_case = False
self.start_time = time.time()
self.end_time = None
self.cumulative_pause_time = 0
if self.web_port is not None:
self.web_interface_thread = self.build_webapp_thread(port=self.web_port, address=self.web_address)
if pre_send_callbacks is None:
pre_send_methods = []
else:
pre_send_methods = pre_send_callbacks
if post_test_case_callbacks is None:
post_test_case_methods = []
else:
post_test_case_methods = post_test_case_callbacks
if post_start_target_callbacks is None:
post_start_target_methods = []
else:
post_start_target_methods = post_start_target_callbacks
if restart_callbacks is None:
restart_methods = []
else:
restart_methods = restart_callbacks
self._callback_monitor = CallbackMonitor(
on_pre_send=pre_send_methods,
on_post_send=post_test_case_methods,
on_restart_target=restart_methods,
on_post_start_target=post_start_target_methods,
)
self.total_num_mutations = 0 # total available protocol mutations (before combining multiple mutations)
self.total_mutant_index = 0 # index within all mutations iterated through, including skipped mutations
self.mutant_index = 0 # index within currently mutating element
self.num_cases_actually_fuzzed = 0
self.fuzz_node = None # Request object currently being fuzzed
self.current_test_case_name = ""
self.targets = []
self.monitor_results = {} # map of test case indices to list of crash synopsis strings (failed cases only)
# map of test case indices to list of supplement captured data (all cases where data was captured)
self.monitor_data = {}
self.is_paused = False
self.crashing_primitives = {}
self.on_failure = event_hook.EventHook()
# import settings if they exist.
self.import_file()
# create a root node. we do this because we need to start fuzzing from a single point and the user may want
# to specify a number of initial requests.
self.root = pgraph.Node()
self.root.label = "__ROOT_NODE__"
self.root.name = self.root.label
self.last_recv = None
self.last_send = None
self.add_node(self.root)
if target is not None:
def apply_options(monitor):
monitor.set_options(crash_filename=self._crash_filename)
return
target.monitor_alive.append(apply_options)
try:
self.add_target(target)
except exception.BoofuzzRpcError as e:
self._fuzz_data_logger.log_error(str(e))
raise
@property
def netmon_results(self):
raise NotImplementedError(
"netmon_results is now part of monitor_results and thus can't be accessed directly."
" Please update your code."
)
def add_node(self, node):
"""
Add a pgraph node to the graph. We overload this routine to automatically generate and assign an ID whenever a
node is added.
Args:
node (pgraph.Node): Node to add to session graph
"""
node.number = len(self.nodes)
node.id = len(self.nodes)
if node.id not in self.nodes:
self.nodes[node.id] = node
return self
def add_target(self, target):
"""
Add a target to the session. Multiple targets can be added for parallel fuzzing.
Args:
target (Target): Target to add to session
"""
# pass specified target parameters to the PED-RPC server.
target.monitors_alive()
target.set_fuzz_data_logger(fuzz_data_logger=self._fuzz_data_logger)
if self._callback_monitor not in target.monitors:
target.monitors.append(self._callback_monitor)
# add target to internal list.
self.targets.append(target)
def connect(self, src, dst=None, callback=None):
"""
Create a connection between the two requests (nodes) and register an optional callback to process in between
transmissions of the source and destination request. The session class maintains a top level node that all
initial requests must be connected to. Example::
sess = sessions.session()
sess.connect(sess.root, s_get("HTTP"))
If given only a single parameter, sess.connect() will default to attaching the supplied node to the root node.
This is a convenient alias. The following line is identical to the second line from the above example::
sess.connect(s_get("HTTP"))
Leverage callback methods to handle situations such as challenge response systems.
A callback method must follow the message signature of :meth:`Session.example_test_case_callback`.
Remember to include \\*\\*kwargs for forward-compatibility.
Args:
src (str or Request (pgrah.Node)): Source request name or request node
dst (str or Request (pgrah.Node), optional): Destination request name or request node
callback (def, optional): Callback function to pass received data to between node xmits. Default None.
Returns:
pgraph.Edge: The edge between the src and dst.
"""
# if only a source was provided, then make it the destination and set the source to the root node.
if dst is None:
dst = src
src = self.root
# if source or destination is a name, resolve the actual node.
if isinstance(src, str):
src = self.find_node("name", src)
if isinstance(dst, str):
dst = self.find_node("name", dst)
# if source or destination is not in the graph, add it.
if src != self.root and self.find_node("name", src.name) is None:
self.add_node(src)
if self.find_node("name", dst.name) is None:
self.add_node(dst)
# create an edge between the two nodes and add it to the graph.
edge = Connection(src.id, dst.id, callback)
self.add_edge(edge)
return edge
@property
def exec_speed(self):
return self.num_cases_actually_fuzzed / self.runtime
@property
def runtime(self):
if self.end_time is not None:
t = self.end_time
else:
t = time.time()
return t - self.start_time - self.cumulative_pause_time
def export_file(self):
"""
Dump various object values to disk.
:see: import_file()
"""
if not self.session_filename:
return
data = {
"session_filename": self.session_filename,
"index_start": self.total_mutant_index,
"sleep_time": self.sleep_time,
"restart_sleep_time": self.restart_sleep_time,
"restart_interval": self.restart_interval,
"web_port": self.web_port,
"web_address": self.web_address,
"crash_threshold": self._crash_threshold_node,
"total_num_mutations": self.total_num_mutations,
"total_mutant_index": self.total_mutant_index,
"monitor_results": self.monitor_results,
"is_paused": self.is_paused,
}
fh = open(self.session_filename, "wb+")
fh.write(zlib.compress(pickle.dumps(data, protocol=2)))
fh.close()
def _start_target(self, target):
started = False
for monitor in target.monitors:
if monitor.start_target():
started = True
break
if started:
for monitor in target.monitors:
monitor.post_start_target(target=target, fuzz_data_logger=self._fuzz_data_logger, session=self)
def import_file(self):
"""
Load various object values from disk.
:see: export_file()
"""
if self.session_filename is None:
return
try:
with open(self.session_filename, "rb") as f:
data = pickle.loads(zlib.decompress(f.read()))
except (IOError, zlib.error, pickle.UnpicklingError):
return
# update the skip variable to pick up fuzzing from last test case.
self._index_start = data["total_mutant_index"]
self.session_filename = data["session_filename"]
self.sleep_time = data["sleep_time"]
self.restart_sleep_time = data["restart_sleep_time"]
self.restart_interval = data["restart_interval"]
self.web_port = data["web_port"]
self.web_address = data["web_address"]
self._crash_threshold_node = data["crash_threshold"]
self.total_num_mutations = data["total_num_mutations"]
self.total_mutant_index = data["total_mutant_index"]
self.monitor_results = data["monitor_results"]
self.is_paused = data["is_paused"]
def num_mutations(self, max_depth=None):
"""
Number of total mutations in the graph. The logic of this routine is identical to that of fuzz(). See fuzz()
for inline comments. The member variable self.total_num_mutations is updated appropriately by this routine.
Args:
max_depth (int): Maximum combinatorial depth used for fuzzing. num_mutations returns None if this value is
None or greater than 1, as the number of mutations is typically very large when using combinatorial fuzzing.
Returns:
int: Total number of mutations in this session.
"""
if max_depth is None or max_depth > 1:
self.total_num_mutations = None
return self.total_num_mutations
return self._num_mutations_recursive()
def _num_mutations_recursive(self, this_node=None, path=None):
"""Helper for num_mutations.
Args:
this_node (request (node)): Current node that is being fuzzed. Default None.
path (list): Nodes along the path to the current one being fuzzed. Default [].
Returns:
int: Total number of mutations in this session.
"""
if this_node is None:
this_node = self.root
self.total_num_mutations = 0
if path is None:
path = []
for edge in self.edges_from(this_node.id):
next_node = self.nodes[edge.dst]
self.total_num_mutations += next_node.get_num_mutations()
if edge.src != self.root.id:
path.append(edge)
self._num_mutations_recursive(next_node, path)
# finished with the last node on the path, pop it off the path stack.
if path:
path.pop()
return self.total_num_mutations
def _pause_if_pause_flag_is_set(self):
"""
If that pause flag is raised, enter an endless loop until it is lowered.
"""
if self.is_paused:
pause_start = time.time()
while 1:
if self.is_paused:
time.sleep(1)
else:
break
self.cumulative_pause_time += time.time() - pause_start
def _check_for_passively_detected_failures(self, target, failure_already_detected=False):
"""Check for and log passively detected failures. Return True if any found.
Args:
target (Target): Target to be checked for failures.
failure_already_detected (bool): If a failure was already detected.
Returns:
bool: True if failures were found. False otherwise.
"""
has_crashed = False
if len(target.monitors) > 0:
self._fuzz_data_logger.open_test_step("Contact target monitors")
# So, we need to run through the array two times. First, we check
# if any of the monitors reported a failure and if so, we need to
# gather a crash synopsis from them. We don't know whether
# a monitor can provide a crash synopsis, but in any case, we'll
# check. In the second run, we try to get crash synopsis from the
# monitors that did not detect a crash as supplemental information.
finished_monitors = []
for monitor in target.monitors:
if not monitor.post_send(target=target, fuzz_data_logger=self._fuzz_data_logger, session=self):
has_crashed = True
self._fuzz_data_logger.log_fail(
"{0} detected crash on test case #{1}: {2}".format(
str(monitor), self.total_mutant_index, monitor.get_crash_synopsis()
)
)
finished_monitors.append(monitor)
if not has_crashed and not failure_already_detected:
self._fuzz_data_logger.log_pass("No crash detected.")
else:
for monitor in set(target.monitors) - set(finished_monitors):
synopsis = monitor.get_crash_synopsis()
if len(synopsis) > 0:
self._fuzz_data_logger.log_fail(
"{0} provided additional information for crash on #{1}: {2}".format(
str(monitor), self.total_mutant_index, monitor.get_crash_synopsis()
)
)
return has_crashed
def _get_monitor_data(self, target):
"""Query monitors for any data they may want to add to this test case.
Args:
target (Target): Monitor to query data from.
"""
for monitor in target.monitors:
data = monitor.retrieve_data()
if data is not None and len(data) > 0:
self._fuzz_data_logger.log_info(
"{0} captured {1} bytes of additional data for test case #{2}".format(
str(monitor), len(data), self.total_mutant_index
)
)
if self.total_mutant_index not in self.monitor_data:
self.monitor_data[self.total_mutant_index] = []
self.monitor_data[self.total_mutant_index] += [data]
def _process_failures(self, target):
"""Process any failures in self.crash_synopses.
If self.crash_synopses contains any entries, perform these failure-related actions:
- log failure summary if needed
- save failures to self.monitor_results (for website)
- exhaust node if crash threshold is reached
- target restart
Should be called after each fuzz test case.
Args:
target (Target): Target to restart if failure occurred.
Returns:
bool: True if any failures were found; False otherwise.
"""
crash_synopses = self._fuzz_data_logger.failed_test_cases.get(self._fuzz_data_logger.most_recent_test_id, [])
if len(crash_synopses) > 0:
self._fuzz_data_logger.open_test_step("Failure summary")
# retrieve the primitive that caused the crash and increment it's individual crash count.
self.crashing_primitives[self.fuzz_node.mutant] = self.crashing_primitives.get(self.fuzz_node.mutant, 0) + 1
self.crashing_primitives[self.fuzz_node] = self.crashing_primitives.get(self.fuzz_node, 0) + 1
# print crash synopsis
if len(crash_synopses) > 1:
# Prepend a header if > 1 failure report, so that they are visible from the main web page
synopsis = "({0} reports) {1}".format(len(crash_synopses), "\n".join(crash_synopses))
else:
synopsis = "\n".join(crash_synopses)
self.monitor_results[self.total_mutant_index] = crash_synopses
self._fuzz_data_logger.log_info(synopsis)
if (
self.fuzz_node.mutant is not None
and self.crashing_primitives[self.fuzz_node] >= self._crash_threshold_node
):
skipped = max(0, self.fuzz_node.get_num_mutations() - self.mutant_index)
self._skip_current_node_after_current_test_case = True
self._fuzz_data_logger.open_test_step(
"Crash threshold reached for this request, exhausting {0} mutants.".format(skipped)
)
self.total_mutant_index += skipped
self.mutant_index += skipped
elif (
self.fuzz_node.mutant is not None
and self.crashing_primitives[self.fuzz_node.mutant] >= self._crash_threshold_element
):
if not isinstance(self.fuzz_node.mutant, primitives.Group) and not isinstance(
self.fuzz_node.mutant, blocks.Repeat
):
skipped = max(0, self.fuzz_node.mutant.get_num_mutations() - self.mutant_index)
self._skip_current_element_after_current_test_case = True
self._fuzz_data_logger.open_test_step(
"Crash threshold reached for this element, exhausting {0} mutants.".format(skipped)
)
self.total_mutant_index += skipped
self.mutant_index += skipped
self._restart_target(target)
return True
else:
return False
def register_post_test_case_callback(self, method):
"""Register a post- test case method.
The registered method will be called after each fuzz test case.
Potential uses:
* Closing down a connection.
* Checking for expected responses.
The order of callback events is as follows::
pre_send() - req - callback ... req - callback - post-test-case-callback
Args:
method (function): A method with the same parameters as :func:`~Session.post_send`
"""
self._callback_monitor.on_post_send.append(method)
# noinspection PyUnusedLocal
def example_test_case_callback(self, target, fuzz_data_logger, session, test_case_context, *args, **kwargs):
"""
Example call signature for methods given to :func:`~Session.connect` or
:func:`~Session.register_post_test_case_callback`
Args:
target (Target): Target with sock-like interface.
fuzz_data_logger (ifuzz_logger.IFuzzLogger): Allows logging of test checks and passes/failures.
Provided with a test case and test step already opened.
session (Session): Session object calling post_send.
Useful properties include last_send and last_recv.
test_case_context (ProtocolSession): Context for test case-scoped data.
:py:class:`ProtocolSession` :py:attr:`session_variables <ProtocolSession.session_variables>`
values are generally set within a callback and referenced in elements via default values of type
:py:class:`ProtocolSessionReference`.
args: Implementations should include \\*args and \\**kwargs for forward-compatibility.
kwargs: Implementations should include \\*args and \\**kwargs for forward-compatibility.
"""
# default to doing nothing.
self._fuzz_data_logger.log_info("No post_send callback registered.")
# noinspection PyMethodMayBeStatic
def _pre_send(self, target):
"""