-
Notifications
You must be signed in to change notification settings - Fork 66
/
manul.py
1571 lines (1236 loc) · 65.6 KB
/
manul.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
# Manul - main module
# -------------------------------------
# Maksim Shudrak <[email protected]> <[email protected]>
#
# Copyright 2019 Salesforce.com, inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from os import listdir
from os.path import isfile, join
import shutil
from ctypes import *
import multiprocessing
import argparse
from timeit import default_timer as timer
import ntpath
from printing import *
from manul_utils import *
from manul_win_utils import *
import manul_network
import random
import afl_fuzz
import zlib
import importlib
import dbi_mode
import radamsa
PY3 = sys.version_info[0] == 3
if PY3:
string_types = str,
xrange = range
else:
string_types = basestring,
xrange = xrange
import subprocess, threading
import signal
net_process_is_up = None
net_sleep_between_cases = 0
INIT_WAIT_TIME = 0
class ForkServer(object):
def __init__(self, timeout):
self.control = os.pipe()
self.status = os.pipe()
self.r_fd = None
self.timeout = timeout
def init_forkserver(self, cmd):
processid = os.fork()
if processid:
# This is the parent process
time.sleep(INIT_WAIT_TIME)
self.r_fd = os.fdopen(self.status[0], 'rb')
res = self.r_fd.read(4)
if len(res) != 4:
ERROR("Failed to init forkserver")
INFO(0, bcolors.OKGREEN, None, "Forkserver init completed successfully")
else:
# This is the child process
os.dup2(self.control[0], 198)
os.dup2(self.status[1], 199)
null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)]
# put /dev/null fds on 1 and 2
os.dup2(null_fds[0], 1)
os.dup2(null_fds[1], 2)
cmd = cmd.split()
# TODO: we need to close some fds before we actually start execv
# more details: https://lcamtuf.blogspot.com/2014/10/fuzzing-binaries-without-execve.html
os.execv(cmd[0], cmd[0:])
ERROR("Failed to start the target using forkserver")
sys.exit(0) # this shouldn't be happen
def run_via_forkserver(self):
# TODO: timeouts for read/write otherwise we can wait infinitely
res = os.write(self.control[1], b"go_!") # ask forkserver to fork
if res != 4:
ERROR("Failed to communicate with forkserver (run_via_forkserver, write). Unable to send go command")
fork_pid = self.r_fd.read(4)
if len(fork_pid) != 4:
ERROR("Failed to communicate with forkserver (run_via_forkserver, read). Unable to confirm fork")
status = self.r_fd.read(4) # TODO: we need timeout here because our target can go idle
if len(status) != 4:
ERROR("Failed to communicate with forkserver (run_via_forkserver, read). Unable to retrieve child status")
return bytes_to_int(status)
class Command(object):
def __init__(self, target_ip, target_port, target_protocol, timeout, fokserver_on, dbi_persistence_handler,
dbi_persistence_mode):
self.process = None
self.forkserver_on = fokserver_on
self.forkserver_is_up = False
self.forkserver = None
self.returncode = 0
if self.forkserver_on:
self.forkserver = ForkServer(timeout)
self.out = None
self.err = None
self.timeout = timeout
if target_ip:
self.target_ip = target_ip
self.target_port = int(target_port)
self.target_protocol = target_protocol
self.net_class = None
self.dbi_persistence_on = dbi_persistence_handler
self.dbi_persistence_mode = dbi_persistence_mode
self.dbi_restart_target = True
def init_target_server(self, cmd):
global net_process_is_up
INFO(1, bcolors.BOLD, None, "Launching %s" % cmd)
if sys.platform == "win32":
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=os.setsid)
if not is_alive(self.process.pid):
ERROR("Failed to start target server error code = %d, output = %s" % (self.process.returncode, self.process.stdout))
net_process_is_up = True
time.sleep(INIT_WAIT_TIME)
def net_send_data_to_target(self, data, net_cmd):
global net_process_is_up
if not net_process_is_up:
INFO(1, None, None, "Target network server is down, starting")
self.init_target_server(net_cmd)
self.net_class = manul_network.Network(self.target_ip, self.target_port, self.target_protocol)
if not net_process_is_up: # is it the first run ?
ERROR("The target network application is not started, aborting")
self.net_class.send_test_case(data)
time.sleep(net_sleep_between_cases)
if not is_alive(self.process.pid):
INFO(1, None, None, "Target is dead")
if sys.platform == "win32":
returncode = EXCEPTION_FIRST_CRITICAL_CODE # just take the first critical
else:
returncode = 11
net_process_is_up = False
self.net_class = None
return returncode, "[Manul message] Target is dead"
return 0, ""
def exec_command_forkserver(self, cmd):
if not self.forkserver_is_up:
self.forkserver.init_forkserver(cmd)
self.forkserver_is_up = True
status = self.forkserver.run_via_forkserver()
return status
def handle_dbi_pre(self):
res = self.dbi_persistence_on.recv_command()
if res == 'P':
# our target successfully reached the target function and is waiting for the next command
INFO(1, None, None, "Target successfully reached the target function (pre_handler)")
send_res = self.dbi_persistence_on.send_command('F') # notify the target that we received command
elif res == 'K' and self.dbi_persistence_mode == 2:
INFO(1, None, None, "Target successfully reached the target function (pre_loop_handler) for the first time")
send_res = self.dbi_persistence_on.send_command('P') # notify the target that we received command
elif res == 'Q':
INFO(1, None, None, "Target notified about exit (after post_handler in target)")
self.dbi_restart_target = True
return True
elif res == 'T': # TODO can it happen when we are sending command ?
self.dbi_restart_target = True
return True
else:
ERROR("Received wrong command from the instrumentation library (pre_handler): %s" % res)
return False
def handle_dbi_post(self):
res = self.dbi_persistence_on.recv_command()
if res == 'K':
INFO(1, None, None, "Target successfully exited from the target function (post_handler)")
elif res == 'T':
WARNING(None, "The target failed to answer within given timeframe, restarting")
self.dbi_restart_target = True
return 0
elif res == "":
WARNING(None, "No answer from the target, restarting.")
# the target should be restarted after this (it can be a crash)
self.dbi_restart_target = True
return 1
elif res == "C": # target sent crash signal, handling and restarting
self.dbi_restart_target = True
return 2
else:
ERROR("Received wrong command from the instrumentation library (post_handler)")
return 0
def exec_command_dbi_persistence(self, cmd):
if self.dbi_restart_target:
if self.process != None and is_alive(self.process.pid):
INFO(1, None, None, "Killing the target")
kill_all(self.process.pid)
self.dbi_persistence_on.close_ipc_object() # close if it is not a first run
self.dbi_persistence_on.setup_ipc_object()
if sys.platform == "win32":
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if not is_alive(self.process.pid):
ERROR("Failed to start the target error code = %d, output = %s" %
(self.process.returncode, self.process.stdout))
self.dbi_persistence_on.connect_pipe_win()
else:
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=os.setsid)
if not is_alive(self.process.pid):
ERROR("Failed to start the target error code = %d, output = %s" %
(self.process.returncode, self.process.stdout))
INFO(1, None, None, "Target successfully started, waiting for result")
self.dbi_restart_target = False
if self.handle_dbi_pre():
# It means that the target issued quit command or we failed to send command, we should handle it properly
return 0, ""
if self.dbi_persistence_mode == 1:
res = self.handle_dbi_post()
if res == 1:
self.handle_return(1) # we use custom timeout of 5 seconds here to check if our target is still alive
return self.process.returncode, self.err
elif res == 2: # TODO: it is only for windows, make it consistent
return EXCEPTION_FIRST_CRITICAL_CODE, "Segmentation fault"
else:
ERROR("Persistence mode not yet supported")
return 0, ""
def handle_return(self, default_timeout):
INFO(1, None, None, "Requesting target state")
if PY3:
try:
self.out, self.err = self.process.communicate(timeout=default_timeout)
except subprocess.TimeoutExpired:
INFO(1, None, None, "Timeout occured")
kill_all(self.process.pid)
return False
else:
self.out, self.err = self.process.communicate() # watchdog will handle timeout if needed in PY2
INFO(1, None, None, "State %s %s" % (self.out, self.err))
return True
def exec_command(self, cmd):
if self.forkserver_on:
self.returncode = self.exec_command_forkserver(cmd)
self.err = ""
return
if self.dbi_persistence_on:
INFO(1, None, None, "Persistence mode")
self.returncode, self.err = self.exec_command_dbi_persistence(cmd)
return
if sys.platform == "win32":
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
else:
self.process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
preexec_fn=os.setsid)
INFO(1, None, None, "Target successfully started, waiting for result")
self.handle_return(self.timeout)
def run(self, cmd):
self.exec_command(cmd)
if isinstance(self.err, (bytes, bytearray)):
self.err = self.err.decode("utf-8", 'replace')
if self.forkserver_on or self.dbi_persistence_on:
return self.returncode, self.err
return self.process.returncode, self.err
class Fuzzer:
def __init__(self, list_of_files, fuzzer_id, virgin_bits_global, args, stats_array, restore_session, crash_bits,
dbi_setup, radamsa_path):
# local fuzzer config
INFO(1, None, None, "Performing intialization of fuzzer %d" % fuzzer_id)
global SHM_SIZE, net_sleep_between_cases
self.SHM_SIZE = SHM_SIZE
self.CALIBRATIONS_COUNT = 7
self.SHM_ENV_VAR = "__AFL_SHM_ID"
self.deterministic = args.deterministic_seed
if self.deterministic:
random.seed(a=self.fuzzer_id)
self.dbi = args.dbi
self.afl_fuzzer = dict()
self.radamsa_path = radamsa_path
if "linux" in sys.platform and "radamsa:0" not in args.mutator_weights:
self.radamsa_fuzzer = radamsa.RadamsaFuzzer(RAND(MAX_SEED))
self.radamsa_fuzzer.load_library(self.radamsa_path)
else:
self.radamsa_fuzzer = None
self.token_dict = list()
self.timeout = args.timeout
self.disable_volatile_bytes = args.disable_volatile_bytes
net_sleep_between_cases = float(args.net_sleep_between_cases)
self.user_mutators = dict()
self.mutator_weights = OrderedDict()
total_weights = 0
try:
weights = args.mutator_weights.split(",")
for weight in weights:
name, weight = weight.split(":")
total_weights += int(weight)
self.mutator_weights[name] = total_weights
except:
ERROR("Invalid format for mutator_weights string, check manul.config file")
if total_weights != 10:
ERROR("Weights in mutator_weights should have 10 in sum, check manul.config file")
try:
if args.dict:
fd = open(args.dict, 'r')
content = fd.readlines()
fd.close()
for line in content:
line = line.replace("\n", "")
if line.startswith("#") or line == "":
continue
line = bytearray(line, "utf-8")
self.token_dict.append(line)
except:
WARNING(None, "Failed to parse dictionary file, dictionary is in invalid format or not accessible")
self.current_file_name = None
self.prev_hashes = dict() # used to store hash of coverage bitmap for each file
for file_name in list_of_files:
self.prev_hashes[file_name] = None
self.cmd_fuzzing = args.cmd_fuzzing
if args.user_signals:
self.user_defined_signals = args.user_signals.split(",")
else:
self.user_defined_signals = None
self.dbi_pipe_handler = None
if dbi_setup:
self.dbi_engine_path = dbi_setup[0]
self.dbi_tool_path = dbi_setup[1]
self.dbi_tool_params = dbi_setup[2]
if args.dbi_persistence_mode >= 1:
INFO(1, None, None, "Getting PIPE name for fuzzer %d" % fuzzer_id)
self.dbi_pipe_handler = dbi_mode.IPCObjectHandler(self.timeout)
obj_name = self.dbi_pipe_handler.get_ipc_obj_name()
INFO(1, None, None, "IPC object name in %s" % (obj_name))
self.dbi_tool_params += "-ipc_obj_name %s" % (obj_name)
self.target_ip = None
self.target_port = None
self.target_protocol = None
if args.target_ip_port:
self.target_ip = args.target_ip_port.split(':')[0]
self.target_port = args.target_ip_port.split(':')[1]
self.target_protocol = args.target_protocol
self.list_of_files = list_of_files
self.fuzzer_id = fuzzer_id
self.virgin_bits = list()
self.virgin_bits = [0xFF] * SHM_SIZE
self.global_map = virgin_bits_global
self.crash_bits = crash_bits # happens not too often
self.bitmap_size = 0
self.avg_bitmap_size = 0
self.avg_exec_per_sec = 0
self.stats_array = stats_array
self.restore = restore_session
# creating output dir structure
self.output_path = args.output + "/%d" % fuzzer_id
self.queue_path = self.output_path + "/queue"
if not args.custom_path:
self.mutate_file_path = self.output_path + "/mutations"
else:
self.mutate_file_path = args.custom_path
self.crashes_path = self.output_path + "/crashes"
self.unique_crashes_path = self.crashes_path + "/unique"
self.enable_logging = args.logging_enable
self.log_file = None
self.user_sync_freq = args.sync_freq
self.sync_bitmap_freq = -1
if not self.restore:
try:
os.mkdir(self.output_path)
except:
ERROR("Failed to create required output dir structure (unique dir)")
try:
os.mkdir(self.queue_path)
except:
ERROR("Failed to create required output dir structure (queue)")
try:
os.mkdir(self.crashes_path)
except:
ERROR("Failed to create required output dir structure (crashes)")
try:
os.mkdir(self.unique_crashes_path)
except:
ERROR("Failed to create required output dir structure (unique crashes)")
if not args.custom_path:
try:
os.mkdir(self.mutate_file_path)
except:
ERROR("Failed to create output directory for mutated files")
self.is_dumb_mode = args.simple_mode
self.input_path = args.input
self.target_binary_path = args.target_binary # and its arguments
self.fuzzer_stats = FuzzerStats()
self.stats_file = None
self.disable_save_stats = args.no_stats
if not self.is_dumb_mode:
self.trace_bits = self.setup_shm()
for i in range(0, self.SHM_SIZE):
if self.virgin_bits[i] != 0xFF:
self.global_map[i] = self.virgin_bits[i]
elif self.global_map[i] != 0xFF and self.virgin_bits[i] == 0xFF:
self.virgin_bits[i] = self.global_map[i]
if self.restore:
if not isfile(self.output_path + "/fuzzer_stats"):
ERROR("Fuzzer stats file doesn't exist. Make sure your output is actual working dir of manul")
self.stats_file = open(self.output_path + "/fuzzer_stats", 'r')
content = self.stats_file.readlines()
line = None
for line in content: # getting last line from file to restore session
pass
if line is None:
ERROR("Failed to restore fuzzer %d from stats. Invalid fuzzer_stats format" % self.fuzzer_id)
last = line[:-2] # skipping last symbol space and \n
INFO(0, None, None, "Restoring last stats %s" % last)
self.stats_file.close()
bitmap = None
if not self.is_dumb_mode:
self.bitmap_file = open(self.output_path + "/fuzzer_bitmap", "rb")
bitmap = self.bitmap_file.read()
self.bitmap_file.close()
self.restore_session(last, bitmap)
if not self.disable_save_stats:
self.stats_file = open(self.output_path + "/fuzzer_stats", 'a+')
self.bitmap_file = open(self.output_path + "/fuzzer_bitmap", 'wb')
if self.enable_logging:
self.log_file = open(self.output_path + "/fuzzer_log", 'a')
self.init_mutators()
self.net_cmd = False
if self.target_ip:
self.net_cmd = self.prepare_cmd_to_run(None, True)
self.forkserver_on = args.forkserver_on
INFO(1, None, None, "Initalization is done for %d" % fuzzer_id)
self.command = Command(self.target_ip, self.target_port, self.target_protocol, self.timeout, args.forkserver_on,
self.dbi_pipe_handler, args.dbi_persistence_mode)
def sync_bitmap(self):
self.sync_bitmap_freq += 1
if (self.sync_bitmap_freq % self.user_sync_freq) != 0:
return
if self.is_dumb_mode:
return
for i in range(0, self.SHM_SIZE):
if self.virgin_bits[i] != 0xFF:
self.global_map[i] = self.virgin_bits[i]
elif self.global_map[i] != 0xFF and self.virgin_bits[i] == 0xFF:
self.virgin_bits[i] = self.global_map[i]
def restore_session(self, last, bitmap):
# parse previously saved stats line
last = last.split(" ")[1:] # cut timestamp
for index, stat in enumerate(last):
stat = float(stat.split(":")[1]) # taking actual value
if PY3:
stat_name = list(self.fuzzer_stats.stats.items())[index][0]
else:
stat_name = self.fuzzer_stats.stats.items()[index][0]
self.fuzzer_stats.stats[stat_name] = stat
if bitmap:
# restoring and synchronizing bitmap
'''for i in range(0, SHM_SIZE):
self.virgin_bits[i] = bitmap[i]
self.sync_bitmap_freq = self.user_sync_freq # little trick to enable synchronization
self.sync_bitmap()
self.sync_bitmap_freq = 0'''
# restoring queue
final_list_of_files = list()
new_files = [f for f in os.listdir(self.queue_path) if os.path.isfile(os.path.join(self.queue_path, f))]
for file_name in new_files:
final_list_of_files.append((1, file_name)) # this is how we add new files
self.list_of_files = self.list_of_files + final_list_of_files
if self.deterministic: # skip already seen seeds
for i in range(0, self.fuzzer_stats.stats['executions']):
random.seed(seed=self.fuzzer_id)
def save_stats(self):
if self.stats_file is None:
return
self.stats_file.write(str(time.time()) + " ")
for index, (k,v) in enumerate(self.fuzzer_stats.stats.items()):
self.stats_file.write("%d:%.2f " % (index, v))
self.stats_file.write("\n")
self.stats_file.flush()
# saving AFL state
for file_name in self.list_of_files:
if not isinstance(file_name, string_types) : file_name = file_name[1]
self.afl_fuzzer[file_name].save_state(self.output_path)
def prepare_cmd_to_run(self, target_file_path, is_net):
if self.dbi:
dbi_tool_opt = "-c"
if self.dbi == "pin":
dbi_tool_opt = "-t"
binary_path = "".join(self.target_binary_path)
if self.cmd_fuzzing:
target_file_path = extract_content(target_file_path) # now it is the file content
if not is_net:
binary_path = binary_path.replace("@@", target_file_path)
final_string = "%s %s %s %s -- %s" % (self.dbi_engine_path, dbi_tool_opt, self.dbi_tool_path,
self.dbi_tool_params, binary_path)
else:
final_string = "".join(self.target_binary_path)
if self.cmd_fuzzing:
target_file_path = extract_content(target_file_path) # now it is the file content
target_file_path = target_file_path.decode("utf-8", "replace")
target_file_path = target_file_path.replace('\x00', '')
max_length = os.sysconf('SC_ARG_MAX') - len(final_string) - 3 # the last 2 is @@
target_file_path = target_file_path[:max_length]
if not is_net:
final_string = final_string.replace("@@", target_file_path)
return final_string
def setup_shm_win(self):
from ctypes.wintypes import DWORD, HANDLE, LPCWSTR, LPVOID
FILE_MAP_ALL_ACCESS = 0xF001F
PAGE_READWRITE = 0x04
sh_name = "%s_%s" % (str(int(round(time.time()))), self.fuzzer_id)
szName = c_wchar_p(sh_name)
kernel32_dll = windll.kernel32
create_file_mapping_func = kernel32_dll.CreateFileMappingW
create_file_mapping_func.argtypes = (HANDLE, LPVOID, DWORD, DWORD, DWORD, LPCWSTR)
create_file_mapping_func.restype = HANDLE
map_view_of_file_func = kernel32_dll.MapViewOfFile
map_view_of_file_func.restype = LPVOID
hMapObject = create_file_mapping_func(-1, None,
PAGE_READWRITE, 0, self.SHM_SIZE,
szName)
if not hMapObject or hMapObject == 0:
ERROR("Could not open file mapping object, GetLastError = %d" % GetLastError())
pBuf = map_view_of_file_func(hMapObject, FILE_MAP_ALL_ACCESS, 0, 0,
self.SHM_SIZE)
if not pBuf or pBuf == 0:
ERROR("Could not map view of file, GetLastError = %d" % GetLastError())
INFO(0, None, self.log_file, "Setting up shared mem %s for fuzzer:%d" % (sh_name,
self.fuzzer_id))
os.environ[self.SHM_ENV_VAR] = sh_name
return pBuf
def setup_shm(self):
if sys.platform == "win32":
return self.setup_shm_win()
IPC_PRIVATE = 0
try:
rt = CDLL('librt.so')
except:
rt = CDLL('librt.so.1')
shmget = rt.shmget
shmget.argtypes = [c_int, c_size_t, c_int]
shmget.restype = c_int
shmat = rt.shmat
shmat.argtypes = [c_int, POINTER(c_void_p), c_int]
shmat.restype = c_void_p#POINTER(c_byte * self.SHM_SIZE)
shmid = shmget(IPC_PRIVATE, self.SHM_SIZE, 0o666)
if shmid < 0:
ERROR("shmget() failed")
addr = shmat(shmid, None, 0)
INFO(0, None, self.log_file, "Setting up shared mem %d for fuzzer:%d" % (shmid, self.fuzzer_id))
os.environ[self.SHM_ENV_VAR] = str(shmid)
return addr
def init_mutators(self):
INFO(0, bcolors.BOLD + bcolors.HEADER, self.log_file, "Initializing mutators")
for module_name in self.mutator_weights:
if "afl" == module_name or "radamsa" == module_name:
continue
try:
self.user_mutators[module_name] = importlib.import_module(module_name)
except ImportError as exc:
ERROR("Unable to load user provided mutator %s. %s" % (module_name, exc.message))
self.user_mutators[module_name].init()
# init AFL fuzzer state
for file_name in self.list_of_files:
if not isinstance(file_name, string_types): file_name = file_name[1]
self.afl_fuzzer[file_name] = afl_fuzz.AFLFuzzer(self.token_dict, self.queue_path, file_name) #assign AFL for each file
if self.restore:
self.afl_fuzzer[file_name].restore_state(self.output_path)
def dry_run(self):
INFO(0, bcolors.BOLD + bcolors.HEADER, self.log_file, "Performing dry run")
useless = 0
for file_name in self.list_of_files:
# if we have tuple and not string here it means that this file was found during execution and located in queue
self.current_file_name = file_name
if not isinstance(file_name, string_types):
file_name = file_name[1]
full_input_file_path = self.queue_path + "/" + file_name
else:
full_input_file_path = self.input_path + "/" + file_name
shutil.copy(full_input_file_path, self.mutate_file_path + "/.cur_input")
full_input_file_path = self.mutate_file_path + "/.cur_input"
memset(self.trace_bits, 0x0, SHM_SIZE)
if self.target_ip:
err_code, err_output = self.command.net_send_data_to_target(extract_content(full_input_file_path), self.net_cmd)
else:
cmd = self.prepare_cmd_to_run(full_input_file_path, False)
INFO(1, bcolors.BOLD, self.log_file, "Launching %s" % cmd)
err_code, err_output = self.command.run(cmd)
if err_code and err_code != 0:
INFO(1, None, self.log_file, "Initial input file: %s triggers an exception in the target" % file_name)
if self.is_critical(err_output, err_code):
WARNING(self.log_file, "Initial input %s leads target to crash (did you disable leak sanitizer?). "
"Enable --debug to check actual output" % file_name)
INFO(1, None, self.log_file, err_output)
elif self.is_problem_with_config(err_code, err_output):
WARNING(self.log_file, "Problematic file %s" % file_name)
trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE)
# count non-zero bytes just to check that instrumentation actually works
non_zeros = [x for x in trace_bits_as_str if x != 0x0]
if len(non_zeros) == 0:
INFO(1, None, self.log_file, "Output from target %s" % err_output)
if "is for the wrong architecture" in err_output:
ERROR("You should run 32-bit drrun for 32-bit targets and 64-bit drrun for 64-bit targets")
ERROR("%s doesn't cover any path in the target, Make sure the binary is actually instrumented" % file_name)
ret = self.has_new_bits(trace_bits_as_str, True, list(), self.virgin_bits, False, full_input_file_path)
if ret == 0:
useless += 1
WARNING(self.log_file, "Test %s might be useless because it doesn't cover new paths in the target, consider removing it" % file_name)
else:
self.sync_bitmap()
if useless != 0:
WARNING(self.log_file, "%d out of %d initial files are useless" % (useless, len(self.list_of_files)))
INFO(0, bcolors.BOLD + bcolors.OKBLUE, self.log_file, "Dry run finished")
self.fuzzer_stats.stats['executions'] += 1.0
self.update_stats()
def has_new_bits(self, trace_bits_as_str, update_virgin_bits, volatile_bytes, bitmap_to_compare, calibration, full_input_file_path):
ret = 0
#print_bitmaps(bitmap_to_compare, trace_bits_as_str, full_input_file_path)
if not calibration:
hash_current = zlib.crc32(trace_bits_as_str) & 0xFFFFFFFF
if not isinstance(self.current_file_name, string_types):
self.current_file_name = self.current_file_name[1]
prev_hash = self.prev_hashes.get(self.current_file_name, None)
if prev_hash and hash_current == prev_hash:
return 0
self.prev_hashes[self.current_file_name] = hash_current
for j in range(0, SHM_SIZE):
if j in volatile_bytes:
continue # ignoring volatile bytes
if PY3:
trace_byte = trace_bits_as_str[j] # optimize it and compare by 4-8 bytes or even use xmm0?
else:
trace_byte = ord(trace_bits_as_str[j]) # self.trace_bits.contents[j])#
if not trace_byte:
continue
virgin_byte = bitmap_to_compare[j]
if trace_byte and (trace_byte & virgin_byte):
if ret < 2:
if virgin_byte == 0xff:
ret = 2 # new path discovered
if update_virgin_bits:
self.bitmap_size += 1
else:
ret = 1 # new hit of existent paths
virgin_byte = virgin_byte & ~trace_byte
if update_virgin_bits:
bitmap_to_compare[j] = virgin_byte # python will handle potential synchronization issues
return ret
def calibrate_test_case(self, full_file_path):
volatile_bytes = list()
trace_bits_as_str = string_at(self.trace_bits, self.SHM_SIZE) # this is how we read memory in Python
bitmap_to_compare = list("\x00" * self.SHM_SIZE)
for i in range(0, self.SHM_SIZE):
if PY3:
bitmap_to_compare[i] = trace_bits_as_str[i]
else:
bitmap_to_compare[i] = ord(trace_bits_as_str[i])
cmd, data = None, None
if self.target_ip: # in net mode we only need data
data = extract_content(full_file_path)
else:
cmd = self.prepare_cmd_to_run(full_file_path, False)
for i in range(0, self.CALIBRATIONS_COUNT):
INFO(1, None, self.log_file, "Calibrating %s %d" % (full_file_path, i))
memset(self.trace_bits, 0x0, SHM_SIZE)
if self.target_ip: # in net mode we only need data
err_code, err_output = self.command.net_send_data_to_target(data, self.net_cmd)
else:
INFO(1, None, self.log_file, cmd)
if self.cmd_fuzzing:
try:
err_code, err_output = self.command.run(cmd)
except OSError as e:
if e.errno == 7:
WARNING(self.log_file, "Failed to send this input over command line into the target, input too long")
continue
else:
ERROR("Failed to execute command, error:", e)
else:
err_code, err_output = self.command.run(cmd)
if err_code and err_code > 0:
INFO(1, None, self.log_file, "Target raised exception during calibration for %s" % full_file_path)
trace_bits_as_str = string_at(self.trace_bits, SHM_SIZE) # this is how we read memory in Python
if not self.disable_volatile_bytes:
for j in range(0, SHM_SIZE):
if PY3:
trace_byte = trace_bits_as_str[j]
else:
trace_byte = ord(trace_bits_as_str[j])
if trace_byte != bitmap_to_compare[j]:
if j not in volatile_bytes:
volatile_bytes.append(j) # mark offset of this byte as volatile
INFO(1, None, self.log_file, "We have %d volatile bytes for this new finding" % len(volatile_bytes))
# let's try to check for new coverage ignoring volatile bytes
self.fuzzer_stats.stats['blacklisted_paths'] = len(volatile_bytes)
return self.has_new_bits(trace_bits_as_str, True, volatile_bytes, self.virgin_bits, True, full_file_path)
def update_stats(self):
for i, (k,v) in enumerate(self.fuzzer_stats.stats.items()):
self.stats_array[i] = v
def is_problem_with_config(self, exc_code, err_output):
if (exc_code == 127 or exc_code == 126) and not self.cmd_fuzzing: # command not found or permissions
ERROR("Thread %d unable to execute target. Bash return %s" % (self.fuzzer_id, err_output))
elif exc_code == 124: # timeout
WARNING(self.log_file, "Target failed to finish execution within given timeout, try to increase default timeout")
return True
return False
def generate_new_name(self, file_name):
iteration = int(round(self.fuzzer_stats.stats['executions']))
if file_name.startswith("manul"): # manul-DateTime-FuzzerId-iteration_original.name
base_name = file_name[file_name.find("_")+1:]
file_name = base_name
now = int(round(time.time()))
return "manul-%d-%d-%d_%s" % (now, self.fuzzer_id, iteration, file_name)
def is_critical_win(self, exception_code):
if exception_code == STATUS_CONTROL_C_EXIT:
return False
if exception_code >= EXCEPTION_FIRST_CRITICAL_CODE and exception_code < EXCEPTION_LAST_CRITICAL_CODE:
return True
return False
def is_critical_mac(self, exception_code):
if exception_code in critical_signals_nix:
return True
return False
def is_critifcal_linux(self, exception_code):
if exception_code in critical_signals_nix:
return True
if self.forkserver_on and os.WIFSIGNALED(exception_code):
return True
return False
def is_critical(self, err_str, err_code):
if err_str and "Sanitizer" in err_str or "SIGSEGV" in err_str or "Segmentation fault" in err_str or \
"core dumped" in err_str or "floating point exception" in err_str:
return True
if self.user_defined_signals and err_code in self.user_defined_signals:
return True
if sys.platform == "win32":
return self.is_critical_win(err_code)
elif sys.platform == "darwin":
return self.is_critical_mac(err_code)
else: # looks like Linux
return self.is_critifcal_linux(err_code)
def mutate_radamsa(self, full_input_file_path, full_output_file_path):
if "linux" in sys.platform: # on Linux we just use a shared library to speed up test cases generation
data = extract_content(full_input_file_path)
data_new = self.radamsa_fuzzer.radamsa_generate_output(bytes(data))
save_content(data_new, full_output_file_path)
return 0
new_seed_str = ""
if self.deterministic:
new_seed = random.randint(0, sys.maxsize)
new_seed_str = "--seed %d " % new_seed
cmd = "%s %s%s > %s" % (self.radamsa_path, new_seed_str, full_input_file_path, full_output_file_path)
INFO(1, None, self.log_file, "Running %s" % cmd)
try:
subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True) # generate new input
except subprocess.CalledProcessError as exc:
WARNING(self.log_file,
"Fuzzer %d failed to generate new input from %s due to some problem with radamsa. Error code %d. Return msg %s" %
(self.fuzzer_id, full_input_file_path, exc.returncode, exc.output))
return 1
return 0
def mutate_afl(self, file_name, full_input_file_path, full_output_file_path):
data = extract_content(full_input_file_path)
res = self.afl_fuzzer[file_name].mutate(data, self.list_of_files,
self.fuzzer_stats.stats['exec_per_sec'],
self.avg_exec_per_sec, self.bitmap_size,
self.avg_bitmap_size, 0) # TODO: handicap
if not res:
WARNING(self.log_file, "Unable to mutate data provided using afl")
return 1
if len(data) <= 0:
WARNING(self.log_file, "AFL produced empty file for %s", full_input_file_path)
save_content(data, full_output_file_path)
return 0
def mutate_input(self, file_name, full_input_file_path, full_output_file_path):
execution = self.fuzzer_stats.stats['executions'] % 10
for name in self.mutator_weights:
weight = self.mutator_weights[name]
if execution < weight and name == "afl":
return self.mutate_afl(file_name, full_input_file_path, full_output_file_path)
elif execution < weight and name == "radamsa":
return self.mutate_radamsa(full_input_file_path, full_output_file_path)
elif execution < weight:
mutator = self.user_mutators.get(name, None)
if not mutator:
ERROR("Unable to load user provided mutator %s at mutate_input stage" % name)
data = extract_content(full_input_file_path)
data = mutator.mutate(data)
if not data:
ERROR("No data returned from user provided mutator. Exciting.")
save_content(data, full_output_file_path)
return 0
else:
continue
def run(self):
if not self.is_dumb_mode:
self.dry_run()
last_stats_saved_time = 0