-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmisc.py
2140 lines (1755 loc) · 63.5 KB
/
misc.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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# litefuzz project
#
# misc.py
#
#
import os
import sys
import re
import glob
import hashlib
import psutil
from psutil import NoSuchProcess
import shutil
import signal
import socket
import string
import subprocess
import shlex
import random
import time
from datetime import datetime, timedelta
from builtins import input
from tqdm import tqdm
import threading
# only import gui stuff if we're on linux /w X running or Windows
if((str(sys.platform).startswith('linux')) and os.environ.get('DISPLAY')):
import pyautogui
if(str(sys.platform).startswith('darwin')):
import pyautogui
if(str(sys.platform).startswith('win32')):
import pyautogui
from _winreg import *
try:
BrokenPipeError # py3
except NameError:
BrokenPipeError = socket.error # py2
import core
import debug
import run
import mutator
import triage
import config
import settings
from settings import SUCCESS, FAILURE
from settings import SIGTRAP, SIGABRT, SIGILL, SIGFPE, SIGSEGV, SIGGO
#
# check for duplicate crashes
#
def checkDup(pc):
if(pc in config.pc_list):
if(config.debug):
print("\n[INFO] found duplicate crash: pc=%s\n" % pc)
return True
else:
if(settings.CHECK_DUPS_PREV_RUN):
for filename in os.listdir(settings.CRASH_DIR):
if(pc in filename):
if(config.debug):
print("\n[INFO] found duplicate crash from previous run: pc=%s\n" % pc)
return True
return False
#
# check for allowed chars
#
def checkAllowed(data):
allowed = set(string.ascii_letters + \
string.digits + \
string.whitespace + \
'.' + '-' + ':' + '_' + '(' + ')' + '\\' + '/')
return set(data) <= allowed
#
# checks paths and PATH to see if binary is installed
#
# source: https://stackoverflow.com/a/28909933
#
def checkForExe(name):
if(config.debug):
print("entering checkForExe() with name=%s\n" % name)
if(isWin32()):
name = addExtExe(name)
if(os.path.isfile(name)):
return True
else:
return any(
(
os.access(os.path.join(path, name), os.X_OK) and
os.path.isfile(os.path.join(path, name))
)
for path in os.environ["PATH"].split(os.pathsep)
)
#
# returns the full path for a given relative name of an executable
#
def getExePath(name):
if(config.debug):
print("entering getExecPath() with name=%s\n" % name)
if(isWin32()):
name = addExtExe(name)
for path in os.environ["PATH"].split(os.pathsep):
if(os.access(os.path.join(path, name), os.X_OK) and
os.path.isfile(os.path.join(path, name))):
full = os.path.join(path, name)
break
return full
#
# when fuzzing stuff where we aren't directly monitoring it in a
# debugger for crashes, use ReportCrash to check for crashes (mac)
#
def checkReportCrash():
if(config.debug):
print("entering checkReportCrash()\n")
time.sleep(2) # give ReportCrash plenty of time to generate the crash artifacts
try:
files = glob.glob(settings.REPORT_CRASH_DIR + '/*')
except Exception as error:
print("\n[ERROR] misc.checkReportCrash() @ dir glob: %s\n" % error)
return FAILURE
if(os.sep in config.target):
targets = config.target.split('/')
target = targets[(len(targets) - 1)]
else:
target = config.target
for file in files:
if(str(os.path.basename(file)).startswith(target)):
for report in config.report_list: # check for reports that were already there
if(report == os.path.basename(file)):
return False
if(config.debug):
print("found new crash report '%s'\n" % os.path.basename(file))
return True
if(config.debug):
print("no ReportCrash crash files found for %s\n" % target)
return False
#
# get a list of files before fuzzing so we know what was already there
#
def checkReportCrashFiles():
try:
files = glob.glob(settings.REPORT_CRASH_DIR + '/*')
except Exception as error:
print("\n[ERROR] misc.checkReportCrashFiles() @ dir glob: %s\n" % error)
return FAILURE
for file in files:
config.report_list.append(os.path.basename(file))
return SUCCESS
#
# check if ReportCrash is running (mac)
#
def checkReportCrashRunning():
if(config.debug):
print("entering checkReportCrashRunning()\n")
if(processExists('ReportCrash')):
return True
else:
if(config.debug):
print("[INFO] ReportCrash isn't running, trying to enable it...")
try:
subprocess.Popen(settings.REPORT_CRASH_LOAD, shell=True)
except Exception as error:
if(config.debug):
print("\n[ERROR] misc.checkReportCrashRunning() @ run cmd: %s\n" % error)
return False
if(processExists('ReportCrash')):
return True
return False
#
# make sure directory is clean for new target runs
#
def checkReportCrashDirectory():
if(config.debug):
print("entering checkReportCrashDirectory()\n")
try:
os.makedirs(settings.REPORT_CRASH_DIR_OLD)
except Exception as error:
if(config.debug):
print("\n[INFO] mkdir failed for ReportCrash old directory '%s': %s\n" % (settings.REPORT_CRASH_DIR_OLD, error)) # may already exist
try:
crash_files = glob.glob(settings.REPORT_CRASH_DIR + '/*')
except Exception as error:
print("\n[ERROR] misc.checkReportCrashDirectory() @ dir glob: %s\n" % error)
return FAILURE
for file in crash_files:
if(os.path.basename(file).startswith(config.target)):
if(config.debug):
print("moving %s to reportcrash old directory\n" % os.path.basename(file))
try:
shutil.move(file, settings.REPORT_CRASH_DIR_OLD)
except Exception as error:
print("\n[ERROR] misc.checkReportCrashDirectory() @ dir glob: %s\n" % error)
return FAILURE
return SUCCESS
#
# check for input limits
#
def checkInput(file, files):
if(os.path.getsize(file) == 0):
if(len(files) == 1):
print("\n[ERROR] input '%s' is an empty file" % os.path.basename(file))
else:
if(config.debug):
print("\n[INFO] input '%s' is an empty file" % os.path.basename(file))
return FAILURE
#
# disable more memory intensive mutators when fuzzing with big files
#
if(os.path.getsize(file) >= settings.BIG_INPUT_SIZE):
if(config.debug):
print("[INFO] found file %s is a big file (%d bytes), disabling memory intensive mutators\n")
settings.INSERT_MUTATOR_ENABLE = False
settings.REMOVE_MUTATOR_ENABLE = False
settings.CARVE_MUTATOR_ENABLE = False
settings.OVERWRITE_MUTATOR_ENABLE = False
if(os.path.getsize(file) > settings.MAX_INPUT_SIZE):
if(len(files) == 1):
print("\n[ERROR] only (%d) input found and it's too big: %s (%d bytes > %d bytes limit)\n" % (len(files),
os.path.basename(file),
os.path.getsize(file),
settings.MAX_INPUT_SIZE))
sys.exit(FAILURE)
else:
if(config.debug):
print("\n[INFO] input '%s' is too big (%d bytes limit)\n" % (os.path.basename(file),
settings.MAX_INPUT_SIZE))
return FAILURE
return SUCCESS
#
# quick check to make sure input directory in valid
#
def checkInputDir(inputs):
try:
if(len(os.listdir(inputs)) == 0):
print("[ERROR] input dir '%s' is empty\n" % inputs)
return FAILURE
except:
print("[ERROR] input dir '%s' doesn't exist\n" % inputs)
return FAILURE
return SUCCESS
#
# check if target is up (tcp only)
#
def checkPort(prot, host, port):
if(prot == 'tcp'):
try:
if(isWin32()):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
return (sock.connect_ex((host, port)) == 0)
else:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
return (sock.connect_ex((host, port)) == 0)
except Exception as error:
if(config.debug):
print("[INFO] misc.checkPort() failed @ connect_ex(): %s\n" % error)
return False
else:
if(config.debug):
print("[INFO] misc.checkPort() only supports TCP ports")
return False
#
# check if hostname resolves
#
def checkHostname(host):
try:
socket.gethostbyname(host)
except socket.error:
return False
return True
#
# check if IP address is valid
#
def checkIPAddress(ip):
try:
socket.inet_aton(ip)
except socket.error:
return False
return True
#
# check return code for crashes
#
def checkForCrash(cmdline):
if(config.debug):
print("entering checkForCrash()\n")
if(config.report_crash):
if(checkReportCrash()):
if(triage.reportCrash()):
return triage.saveRepro(settings.FUZZ_FILE)
if(config.process != None):
if(config.debug):
if(config.process.returncode):
print("returncode=%d\n" % config.process.returncode)
if(os.path.isfile(settings.FUZZ_OUTPUT)):
checkForCrashSSP()
if(config.process.returncode == SIGABRT or
config.process.returncode == SIGFPE or
config.process.returncode == SIGSEGV):
return triage.unix(cmdline)
if(config.golang):
if(config.process.returncode == SIGGO):
return triage.unix(cmdline)
return SUCCESS
#
# check for stack smashing or buffer overflow detected
# and if so, formally wait for the process return code
#
def checkForCrashSSP():
output = None
try:
with open(settings.FUZZ_OUTPUT, 'r') as file:
output = file.read()
except UnicodeDecodeError:
return FAILURE
except Exception as error:
print("\n[ERROR] misc.checkForCrashSSP() @ read(output): %s\n" % error)
return FAILURE
if('detected ***' in output):
if(config.debug):
print("%s" % output)
config.process.wait()
return SUCCESS
#
# check crash dir for crashes to reuse for fuzzing
#
def checkReuse(inputs):
if(len(os.listdir(settings.CRASH_DIR)) == 0):
print("\n[INFO] crash dir is empty, no crashes to reuse")
return False
extList = []
files = []
inputs = os.path.abspath(inputs)
if(os.path.isdir(inputs)):
try:
files = glob.glob(inputs + '/*')
except Exception as error:
print("\n[ERROR] misc.checkReuse() @ inputs glob: %s\n" % error)
return FAILURE
else:
files.append(inputs)
for file in files:
ext = getExt(file)
if(ext == ''):
extList.append('zz')
else:
extList.append(getExt(file))
if(config.debug):
print("%s" % extList)
config.reusedir = inputs + '-' + 'reuse' + '-' + getRandomString(4)
try:
os.makedirs(config.reusedir)
except Exception as error:
print("\n[ERROR] can't mkdir reuse directory %s: %s" % (config.reusedir, error))
return False
#
# 3) if no file extension, copy anything that's not *.out *.diff *.txt
#
try:
files = glob.glob(settings.CRASH_DIR + '/*')
except Exception as error:
print("\n[ERROR] misc.checkReuse() @ CRASH_DIR glob: %s\n" % error)
return FAILURE
for file in files:
for ext in extList:
if(file.endswith(ext)):
try:
shutil.copy(file, config.reusedir + os.sep + os.path.basename(file))
except Exception as error:
print("\n[ERROR] misc.checkReuse() @ copy '%s' for reuse: %s\n" % (file, error))
return FAILURE
return True
#
# removes the latest crashing files (eg. for test crash runs during minimization)
#
def cleanupMin():
for file in os.listdir(settings.CRASH_DIR):
if(os.path.basename(config.crash_file) in file):
try:
os.remove(settings.CRASH_DIR + os.sep + file)
except Exception as error:
if(config.debug):
print("\n[ERROR] couldn't remove '%s' test run file: %s\n" % (file, error))
return FAILURE
return SUCCESS
#
# removes the temp files and run directory (per-run dir, not the entire temp itself)
#
def cleanupTmp():
try:
shutil.rmtree(settings.RUN_DIR)
except Exception as error:
if(config.debug):
print("\n[ERROR] couldn't remove run temp directory: %s\n" % error)
return FAILURE
if(config.static_fuzz_file != None):
try:
os.remove(config.static_fuzz_file)
except Exception as error:
if(config.debug):
print("\n[ERROR] couldn't remove static fuzz file: %s\n" % error)
return FAILURE
return SUCCESS
#
# set target as crashed and get repro for remote client/server crashes
#
# note: previous fuzz file may be the only crasher available to save if next connect
# fails immediately (new fuzz file hasn't made it through the process to be created yet)
#
def clientServerCrash():
newCrash()
if(config.multibin):
repro = None # we use config.session
else:
if(config.down):
if(config.debug):
print("[INFO] misc.clientServerCrash() is using %s (FUZZ_FILE_PREV) as repro\n" % settings.FUZZ_FILE_PREV)
if(settings.FUZZ_FILE_PREV == None): # handle case where connection fails on first iteration (so no previous fuzz file)
repro = settings.FUZZ_FILE
else:
repro = settings.FUZZ_FILE_PREV # fallback in case initial connect fails (so its previous iteration data)
else:
if(config.debug):
print("[INFO] misc.clientServerCrash() is using %s (FUZZ_FILE) as repro\n" % settings.FUZZ_FILE)
repro = settings.FUZZ_FILE
return triage.saveRepro(repro)
#
# get the extension from a filename
#
def getExt(name):
if('.' in name):
ext = name.split('.')
ext = ext[len(ext) - 1]
else:
ext = ''
return ext
#
# windows is fun
#
def addExtExe(name):
if('.exe' not in name):
return name + '.exe'
else:
return name
#
# copy output to global output for visibility / debugging purposes
#
# copy .out file to /tmp/litefuzz/out for local apps and clients
# copy .txt file to /tmp/litefuzz/outs for local servers and insulated apps (running in a debugger)
#
def copyDebugOutput():
if(isWin32()): # no stdout support on windows
return SUCCESS
if((config.mode != settings.CLIENT) and (config.mode != settings.SERVER)):
try:
# if any([(config.mode == settings.LOCAL) or (config.mode == settings.LOCAL_CLIENT)]):
if ((config.mode == settings.LOCAL) or (config.mode == settings.LOCAL_CLIENT)):
if(config.insulate == False):
if(config.debug):
print("\ncopying %s to %s\n" % (settings.FUZZ_OUTPUT, settings.FUZZ_OUTPUT_DEBUG))
shutil.copy(settings.FUZZ_OUTPUT, settings.FUZZ_OUTPUT_DEBUG)
else:
if(config.debug):
print("\ncopying %s to %s\n" % (settings.FUZZ_INFO_STATIC, settings.FUZZ_OUTPUTS_DEBUG))
shutil.copy(settings.FUZZ_INFO_STATIC, settings.FUZZ_OUTPUTS_DEBUG)
except Exception as error:
print("\n[ERROR] misc.copyDebugOutput() failed: %s\n" % error)
return FAILURE
return SUCCESS
#
# run timeout for insulate mode
#
def doInsulate():
print("[+] waiting %d seconds for manual target setup before continuing...\n" % settings.INSULATE_TIMEOUT)
time.sleep(settings.INSULATE_TIMEOUT)
#
# main page heap
#
def pageHeap(target):
if(settings.DEBUG_ENV_PAGEHEAP_ENABLE):
return doPageHeap(target, True)
if(settings.DEBUG_ENV_PAGEHEAP_DISABLE):
return doPageHeap(target, False)
# else:
# if(checkPageHeap(target)):
# doPageHeap(target, False)
# else:
# print("\n[INFO] PageHeap is off (pass -z to turn it on)\n")
#
# check if pageheap is enabled
#
def checkPageHeap(target):
key = settings.PAGEHEAP_REG_KEY + os.path.basename(target)
gf_val = None
ph_val = None
try:
registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(registry, key)
gf_val = QueryValueEx(k, 'GlobalFlag')
ph_val = QueryValueEx(k, 'PageHeapFlags')
CloseKey(k)
except:
return False
if((gf_val[0] == settings.DEBUG_ENV_GFLAG_MAGIC) and
(ph_val[0] == settings.DEBUG_ENV_PAGEHEAP_MAGIC)):
return True
else:
return False
#
# check if pageheap is enabled
#
def checkMemoryDump(target):
target = addExtExe(target)
key = settings.MEMORY_DUMP_REG_KEY + os.path.basename(target)
val = None
try:
registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(registry, key)
CloseKey(k)
except:
return False
return True
#
# enable memory dumps on win32
#
def doMemoryDump(target, enable):
target = addExtExe(target)
key = settings.MEMORY_DUMP_REG_KEY + os.path.basename(target)
if(config.debug):
print("\ndump key: %s" % key)
if(enable and checkMemoryDump(target)):
return SUCCESS
elif(enable and (checkMemoryDump(target) == False)):
try:
CreateKey(HKEY_LOCAL_MACHINE, key)
k = OpenKey(HKEY_LOCAL_MACHINE, key, 0, KEY_WRITE)
SetValueEx(k, 'DumpFolder', 0, REG_SZ, settings.TMP_DIR) # place in the litefuzz tmp dir, later cp to crash dir
CloseKey(k)
except Exception as error:
print("\n[ERROR] writing to registry failed: %s\n" % error)
print("(try running elevated or use sudo.. really ;)\n") # gsudo for win32
sys.exit(FAILURE)
if(config.debug):
print("\n[INFO] turned Memory Dumps on")
else: # disable
if(checkMemoryDump(target) == False):
return SUCCESS
if(config.debug):
print("disabling Memory Dumps\n")
try:
registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(registry, key)
info = QueryInfoKey(k)
for x in range(0, info[0]):
sk = EnumKey(k, 0)
DeleteKey(k, sk)
DeleteKey(k, '')
CloseKey(k)
except Exception as error:
print("\n[ERROR] failed to delete Memory Dump reg keys: %s\n" % error)
print("(try running elevated or use sudo.. really ;)\n") # gsudo for win32
sys.exit(FAILURE)
return SUCCESS
#
# call checkPageHeap() and turn it on if requested
#
def doPageHeap(target, enable):
if(isWin32()):
target = addExtExe(target)
key = settings.PAGEHEAP_REG_KEY + os.path.basename(target)
if(config.debug):
print("\ngflags key: %s" % key)
if(settings.DEBUG_ENV_PAGEHEAP_ENABLE):
if(enable and checkPageHeap(target)):
return SUCCESS
if(enable and (checkPageHeap(target) == False)):
try:
CreateKey(HKEY_LOCAL_MACHINE, key)
k = OpenKey(HKEY_LOCAL_MACHINE, key, 0, KEY_WRITE)
SetValueEx(k, 'GlobalFlag', 0, REG_SZ, settings.DEBUG_ENV_GFLAG_MAGIC)
SetValueEx(k, 'PageHeapFlags', 0, REG_SZ, settings.DEBUG_ENV_PAGEHEAP_MAGIC)
CloseKey(k)
except Exception as error:
print("\n[ERROR] writing to registry failed: %s\n" % error)
print("(try running elevated or use sudo.. really ;)\n") # gsudo for win32
sys.exit(FAILURE)
if(config.debug):
print("\n[INFO] turned PageHeap on")
else: # disable
if(checkPageHeap(target) == False):
return SUCCESS
if(config.debug):
print("disabling PageHeap\n")
try:
registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(registry, key)
info = QueryInfoKey(k)
for x in range(0, info[0]):
sk = EnumKey(k, 0)
DeleteKey(k, sk)
DeleteKey(k, '')
CloseKey(k)
except Exception as error:
# print("\n[ERROR] failed to delete PageHeap reg keys: %s\n" % error)
# print("(try running elevated or use sudo.. really ;)\n") # gsudo for win32
# sys.exit(FAILURE)
pass
# else:
# if(checkPageHeap(target)):
# if(config.debug):
# print("[INFO] PageHeap is still on (pass -z to make this explicit or -zz to turn off)\n")
return SUCCESS
#
# flashy counter
#
def displayCount(pb, iterations, fuzz):
#
# only select the first n times
#
if(len(config.exec_times) == 0):
config.exec_avg = (config.maxtime * 3)
else:
if(len(config.exec_times) <= settings.MAX_AVG_EXEC):
if(config.mode == settings.LOCAL):
config.exec_avg = (sum(config.exec_times) / len(config.exec_times)) * 4 # more accurate
else:
config.exec_avg = sum(config.exec_times) / len(config.exec_times)
#
# total iterations
#
if(iterations != 0): # minimization
config.iterations = iterations
remaining = str(timedelta(seconds=(config.iterations - config.count) * config.exec_avg)).split('.')[0]
if(fuzz):
pb.set_description_str("@ %d/%d (%d crashes, %d duplicates, ~%s remaining)" % (config.count,
config.iterations,
config.crashes,
config.dups,
remaining))
else:
if(config.repro):
pb.set_description_str("@ %d/%d (%d crashes, %d duplicates, %d -> %d bytes, ~%s remaining)" % (config.count,
config.iterations,
config.crashes,
config.dups,
config.min_original,
config.min_current,
remaining))
else:
pb.set_description_str("@ %d/%d (%d new crashes, %d -> %d bytes, ~%s remaining)" % ((config.count + 1),
config.iterations,
config.crashes,
config.min_original,
config.min_current,
remaining))
pb.update(config.count)
#
# results
#
def displayResults():
if((config.mode == settings.CLIENT) and config.down):
print("\n[*] remote client stopped connecting, saving artifacts and exiting")
if((config.mode == settings.SERVER) and config.down):
print("\n[*] remote server stopped responding, saving artifacts and exiting")
print("\n[RESULTS]")
#
# repro / min results
#
if(config.repro or config.min):
if(config.min):
config.count += 1
if(config.crashes > 0):
if(config.repro):
if((config.mode == settings.CLIENT) or (config.mode == settings.SERVER)):
print("completed (%d) iterations with (%d) crash\n" % (config.count,
config.crashes))
else:
print("completed (%d) iterations with crash @ pc=%s\n" % (config.count,
config.current_pc))
else:
print("completed (%d) iterations with %d new crashes found\n" % (config.count,
config.crashes))
elif((config.crashes > 0) and (config.dups > 0)):
print("completed (%d) iterations with %d new crashes found\n" % (config.count, config.crashes))
elif(config.dups > 0):
print("completed (%d) iterations with no new crashes found (%d dups)\n" % (config.count, config.dups))
else:
if(config.repro):
print("completed (%d) iterations with no crashes found\n" % config.count)
else:
print("completed (%d) iterations with no additional crashes found\n" % config.count)
#
# fuzzing results
#
else:
if((config.crashes > 0) and (config.dups == 0)):
print("> completed (%d) iterations with (%d) unique crashes" % (config.count, config.crashes))
print(">> check %s for more details\n" % settings.CRASH_DIR)
elif((config.crashes > 0) and (config.dups > 0)):
print("> completed (%d) iterations with (%d) unique crashes and %d dups" % (config.count, config.crashes, config.dups))
print(">> check %s for more details\n" % settings.CRASH_DIR)
elif((config.crashes == 0) and (config.dups > 0)):
print("completed (%d) iterations with no new crashes found (%d dups)" % (config.count, config.dups))
print(">> check %s for more details\n" % settings.CRASH_DIR)
else:
print("completed (%d) iterations with no crashes found\n" % config.count)
#
# main stats
#
def displayStats(cmdline, inputdir, inputs, file):
#print("[CONFIG]")
print("[STATS]")
if(config.debug):
print("pid: %d" % os.getpid())
print("run id: %d" % config.run_id)
if(cmdline != None):
print("cmdline: %s" % cmdline)
if(config.address != None):
print("address: %s" % config.address)
if(config.attach != None):
print("process: %s" % config.attach)
print("crash dir: %s" % settings.CRASH_DIR)
if(config.min or config.repro):
if(os.path.isfile(file)):
print("crasher: %s\n" % os.path.basename(file))
else:
print("crasher: %s\n" % os.path.basename(os.path.normpath(file)))
#
# display only if fuzzing and not for minimization / replay
#
if((inputdir != None) and (inputs != None)):
if(os.path.isdir(inputdir)):
print("input dir: %s" % config.inputs)
else:
print("input: %s" % config.inputs)
print("inputs: %d" % inputs)
print("iterations: %d" % config.iterations)
if(settings.MUTATOR_CHOICE == 0):
print("mutator: random(mutators)\n")
elif(settings.MUTATOR_CHOICE == settings.FLIP_MUTATOR):
print("mutator: flip\n")
elif(settings.MUTATOR_CHOICE == settings.HIGHLOW_MUTATOR):
print("mutator: highlow\n")
elif(settings.MUTATOR_CHOICE == settings.INSERT_MUTATOR):
print("mutator: insert\n")
elif(settings.MUTATOR_CHOICE == settings.REMOVE_MUTATOR):
print("mutator: remove\n")
elif(settings.MUTATOR_CHOICE == settings.CARVE_MUTATOR):
print("mutator: carve\n")
elif(settings.MUTATOR_CHOICE == settings.OVERWRITE_MUTATOR):
print("mutator: overwrite\n")
elif(settings.MUTATOR_CHOICE == settings.RADAMSA_MUTATOR):
print("mutator: radamsa\n")
else:
print("\n[ERROR] invalid mutator setting: %d" % settings.MUTATOR_CHOICE)
sys.exit(FAILURE)
#
# execute a command (quietly)
#
def execute(cmd):
if(config.debug):
print("entering misc.execute()\n")
cmdline = shlex.split(cmd)
try:
process = subprocess.Popen(cmdline,
stdin=None,
stdout=open(settings.null),
stderr=open(settings.null))
(output, error) = process.communicate(timeout=settings.EXEC_TIMEOUT)
if(error):
print("\n[ERROR] '%s' @ pid=%d: %s\n" % (cmdline, process.pid(), error))
except subprocess.TimeoutExpired as error:
if(config.debug):
print("%s\n" % error)
killProcess(process.pid)
except Exception as error:
print("\n[ERROR] misc.execute() cmd=%s: %s\n" % (cmdline, error))
return FAILURE
return SUCCESS
#
# generate certs for fuzzing
#
def generateCert():
if(config.debug):
print("entering misc.generateCert()\n")
if(not os.path.isdir(settings.TLS_DIR)):
try:
os.mkdir(settings.TLS_DIR)
except Exception as error:
print("\n[ERROR] can't mkdir cert directory %s: %s" % (settings.TLS_DIR, error))
return FAILURE
if(execute(settings.GENERATE_CERT_CMD) != SUCCESS):
return FAILURE
if((os.path.isfile(settings.NETWORK_CRT) == False) or
(os.path.isfile(settings.NETWORK_KEY) == False)):
print("\n[ERROR] misc.generateCert() @ cert check: failed to create cert files\n")
if(config.debug):
print("\n[INFO] successfully generated certs for TLS")
return SUCCESS
#
# returns a mutant based on the pick
#
def getMutant(data):
mutations = getRandomInt(settings.MUTATION_MIN, settings.MUTATION_MAX)
if(settings.MUTATOR_CHOICE == 0):
pick = getRandomInt(1, settings.MUTATOR_MAX)
else:
pick = settings.MUTATOR_CHOICE
#
# check for disabled memory intensive mutators (eg. big files) and reassign the picks
#
if((pick == settings.INSERT_MUTATOR) and (settings.INSERT_MUTATOR_ENABLE == False)):
pick = settings.FLIP_MUTATOR
if((pick == settings.REMOVE_MUTATOR) and (settings.REMOVE_MUTATOR_ENABLE == False)):
pick = settings.FLIP_MUTATOR
if((pick == settings.CARVE_MUTATOR) and (settings.CARVE_MUTATOR_ENABLE == False)):
pick = settings.HIGHLOW_MUTATOR
if((pick == settings.OVERWRITE_MUTATOR) and (settings.OVERWRITE_MUTATOR_ENABLE == False)):
pick = settings.HIGHLOW_MUTATOR
if(pick == settings.FLIP_MUTATOR):
mutant = mutator.flip(data, mutations)
elif(pick == settings.HIGHLOW_MUTATOR):
mutant = mutator.highLow(data)
elif(pick == settings.INSERT_MUTATOR):
mutant = mutator.insert(data)
elif(pick == settings.REMOVE_MUTATOR):
mutant = mutator.remove(data)
elif(pick == settings.CARVE_MUTATOR):
mutant = mutator.carve(data)