forked from googleprojectzero/winafl
-
Notifications
You must be signed in to change notification settings - Fork 9
/
afl-fuzz.c
executable file
·9401 lines (6335 loc) · 228 KB
/
afl-fuzz.c
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
/*
american fuzzy lop - fuzzer code
--------------------------------
Original AFL code written by Michal Zalewski <lcamtuf@google.com>
Windows fork written and maintained by Ivan Fratric <ifratric@google.com>
Copyright 2016 Google 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.
*/
#define _CRT_SECURE_NO_WARNINGS
#define AFL_MAIN
#define MESSAGES_TO_STDOUT
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#define WIN32_LEAN_AND_MEAN /* prevent winsock.h to be included in windows.h */
#define _CRT_RAND_S
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <TlHelp32.h>
#include <stdarg.h>
#include <io.h>
#include <direct.h>
#define VERSION "2.43b"
#define WINAFL_VERSION "1.15"
#include "config.h"
#include "types.h"
#include "debug.h"
#include "alloc-inl.h"
#include "hash.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#if defined(__APPLE__) || defined(__FreeBSD__) || defined (__OpenBSD__)
# include <sys/sysctl.h>
#endif /* __APPLE__ || __FreeBSD__ || __OpenBSD__ */
// IntelPT includes
#define INTELPT 1
#define PROCESS_DEBUG 0
#define MEM_LIMIT_INTELPT 200
#ifdef INTELPT
#include ".\\winipt\\inc\\libipt.h"
#pragma comment (lib, "..\\winipt\\x64\\Release\\libipt.lib")
#define IPT_TOOL_USE_MTC_TIMING_PACKETS 0x01
#define IPT_TOOL_USE_CYC_TIMING_PACKETS 0x02
#define IPT_TOOL_TRACE_KERNEL_MODE 0x04
#define IPT_TOOL_TRACE_ALL_MODE 0x08
#define IPT_TOOL_VALID_FLAGS \
(IPT_TOOL_USE_MTC_TIMING_PACKETS | \
IPT_TOOL_USE_CYC_TIMING_PACKETS | \
IPT_TOOL_TRACE_KERNEL_MODE | \
IPT_TOOL_TRACE_ALL_MODE)
typedef enum _IPT_TL_ACTION
{
IptTlStartTrace,
IptTlStopTrace,
IptTlGetTrace,
IptTlQueryTrace,
IptTlPauseTrace,
IptTlResumeTrace
} IPT_TL_ACTION;
IPT_OPTIONS ipt_options = { 0 };
HANDLE hIptTraceFile = INVALID_HANDLE_VALUE;
PIPT_TRACE_DATA pIptTraceData = { 0 };
FORCEINLINE
DWORD
ConvertToPASizeToSizeOption(
_In_ DWORD dwSize
)
{
DWORD dwIndex;
//
// Cap the size to 128MB. Sizes below 4KB will result in 0 anyway.
//
if (dwSize > (128 * 1024 * 1024))
{
dwSize = 128 * 1024 * 1024;
}
//
// Find the nearest power of two that's set (align down)
//
BitScanReverse(&dwIndex, dwSize);
//
// The value starts at 4KB
//
dwIndex -= 12;
return dwIndex;
}
BOOL
EnableIpt(
VOID
)
{
SC_HANDLE hScm, hSc;
BOOL bRes;
bRes = FALSE;
//
// Open a handle to the SCM
//
hScm = OpenSCManagerW(NULL, NULL, SC_MANAGER_CONNECT);
if (hScm != NULL)
{
//
// Open a handle to the IPT Service
//
hSc = OpenServiceW(hScm, L"Ipt", SERVICE_START);
if (hSc != NULL)
{
//
// Start it
//
bRes = StartServiceW(hSc, 0, NULL);
if ((bRes == FALSE) &&
(GetLastError() == ERROR_SERVICE_ALREADY_RUNNING))
{
//
// If it's already started, that's OK
//
bRes = TRUE;
}
else if (bRes == FALSE)
{
fwprintf(stderr, L"[-] Unable to start IPT Service (err=%d)\n",
GetLastError());
if (GetLastError() == ERROR_NOT_SUPPORTED)
{
fwprintf(stderr, L"[-] This is likely due to missing PT support\n");
}
}
//
// Done with the service
//
CloseServiceHandle(hSc);
}
else
{
fwprintf(stderr, L"[-] Unable to open IPT Service (err=%d). "
L"Are you running Windows 10 1809?\n",
GetLastError());
}
//
// Done with the SCM
//
CloseServiceHandle(hScm);
}
else
{
fwprintf(stderr, L"[-] Unable to open a handle to the SCM (err=%d)\n",
GetLastError());
}
//
// Return the result
//
return bRes;
}
BOOL
EnableAndValidateIptServices(
VOID
)
{
WORD wTraceVersion;
DWORD dwBufferVersion;
BOOL bRes;
//
// First enable IPT
//
bRes = EnableIpt();
if (bRes == FALSE)
{
fwprintf(stderr, L"[-] Intel PT Service could not be started!\n");
goto Cleanup;
}
//
// Next, check if the driver uses a dialect we understand
//
bRes = GetIptBufferVersion(&dwBufferVersion);
if (bRes == FALSE)
{
fwprintf(stderr, L"[-] Failed to communicate with IPT Service: (err=%d)\n",
GetLastError());
goto Cleanup;
}
if (dwBufferVersion != IPT_BUFFER_MAJOR_VERSION_CURRENT)
{
fwprintf(stderr, L"[-] IPT Service buffer version is not supported: %d\n",
dwBufferVersion);
goto Cleanup;
}
//
// Then, check if the driver uses trace versions we speak
//
bRes = GetIptTraceVersion(&wTraceVersion);
if (bRes == FALSE)
{
fwprintf(stderr, L"[-] Failed to get Trace Version from IPT Service (err=%d)\n",
GetLastError());
goto Cleanup;
}
if (wTraceVersion != IPT_TRACE_VERSION_CURRENT)
{
fwprintf(stderr, L"[-] IPT Service trace version is not supported %d\n",
wTraceVersion);
goto Cleanup;
}
Cleanup:
//
// Return result
//
return bRes;
}
BOOL
ConfigureTraceFlags(
_In_ PWCHAR pwszFlags,
_Inout_ PIPT_OPTIONS pOptions
)
{
DWORD dwFlags;
BOOL bRes;
bRes = FALSE;
//
// Read the flags now and make sure they're valid
//
dwFlags = wcstoul(pwszFlags, NULL, 16);
if (dwFlags & ~IPT_TOOL_VALID_FLAGS)
{
fwprintf(stderr, L"[-] Invalid flags: %s\n", pwszFlags);
goto Cleanup;
}
//
// If the user didn't specify MTC, but wants CYC, set MTC too as the IPT
// driver wil enable those packets anyway.
//
if ((dwFlags & IPT_TOOL_USE_CYC_TIMING_PACKETS) &&
!(dwFlags & IPT_TOOL_USE_MTC_TIMING_PACKETS))
{
fwprintf(stderr, L"[*] CYC Packets require MTC packets, adjusting flags!\n");
dwFlags |= IPT_TOOL_USE_MTC_TIMING_PACKETS;
}
//
// If the user didn't specify MTC, but wants CYC, set MTC too as the IPT
// driver wil enable those packets anyway.
//
if ((dwFlags & (IPT_TOOL_TRACE_KERNEL_MODE | IPT_TOOL_TRACE_ALL_MODE)) ==
(IPT_TOOL_TRACE_KERNEL_MODE | IPT_TOOL_TRACE_ALL_MODE))
{
fwprintf(stderr, L"[-] Cannot enable both `kernel` and `user + kernel` tracing."
L" Please pick a single flag to use!\n");
goto Cleanup;
}
//
// There are no matching options for process tradces
//
pOptions->MatchSettings = IptMatchByAnyApp;
//
// Choose the right timing setting
//
if (dwFlags & IPT_TOOL_USE_MTC_TIMING_PACKETS)
{
pOptions->TimingSettings = IptEnableMtcPackets;
pOptions->MtcFrequency = 3; // FIXME
}
else if (dwFlags & IPT_TOOL_USE_CYC_TIMING_PACKETS)
{
pOptions->TimingSettings = IptEnableCycPackets;
pOptions->CycThreshold = 1; // FIXME
}
else
{
pOptions->TimingSettings = IptNoTimingPackets;
}
//
// Choose the right mode setting
//
if (dwFlags & IPT_TOOL_TRACE_KERNEL_MODE)
{
pOptions->ModeSettings = IptCtlKernelModeOnly;
}
else if (dwFlags & IPT_TOOL_TRACE_ALL_MODE)
{
pOptions->ModeSettings = IptCtlUserAndKernelMode;
}
else
{
pOptions->ModeSettings = IptCtlUserModeOnly;
}
//
// Print out chosen options
//
bRes = TRUE;
fwprintf(stderr, L"[+] Tracing Options:\n"
L" Match by: %s\n"
L" Trace mode: %s\n"
L" Timing packets: %s\n",
L"Any process",
(pOptions->ModeSettings == IptCtlUserAndKernelMode) ?
L"Kernel and user-mode" :
(pOptions->ModeSettings == IptCtlKernelModeOnly) ?
L"Kernel-mode only" : L"User-mode only",
(pOptions->TimingSettings == IptEnableMtcPackets) ?
L"MTC Packets" :
(pOptions->TimingSettings == IptEnableCycPackets) ?
L"CYC Packets" : L"No Packets");
Cleanup:
//
// Return result
//
return bRes;
}
BOOL
ConfigureBufferSize(
_In_ PWCHAR pwszSize,
_Inout_ PIPT_OPTIONS pOptions
)
{
DWORD dwSize;
BOOL bRes;
bRes = FALSE;
//
// Get the buffer size
//
dwSize = wcstoul(pwszSize, NULL, 10);
if (dwSize == 0)
{
fwprintf(stderr, L"[-] Invalid size: %s\n", pwszSize);
goto Cleanup;
}
//
// Warn the user about incorrect values
//
if (!((dwSize) && ((dwSize & (~dwSize + 1)) == dwSize)))
{
fwprintf(stderr, L"[*] Size will be aligned to a power of 2\n");
}
else if (dwSize < 4096)
{
fwprintf(stderr, L"[*] Size will be set to minimum of 4KB\n");
}
else if (dwSize >(128 * 1024 * 1024))
{
fwprintf(stderr, L"[*] Size will be set to a maximum of 128MB\n");
}
//
// Compute the size option
//
pOptions->TopaPagesPow2 = ConvertToPASizeToSizeOption(dwSize);
bRes = TRUE;
fwprintf(stderr, L"[+] Using size: %d bytes\n",
1 << (pOptions->TopaPagesPow2 + 12));
Cleanup:
//
// Return result
//
return bRes;
}
BOOL
ConfigureProcess(
_In_ PWCHAR pwszPid,
_Out_ PHANDLE phProcess
)
{
DWORD dwPid;
BOOL bRes;
bRes = FALSE;
*phProcess = NULL;
//
// Get the PID first
//
dwPid = wcstoul(pwszPid, NULL, 0);
if (dwPid == 0)
{
fwprintf(stderr, L"[-] Invalid PID: %s\n", pwszPid);
goto Cleanup;
}
//
// Open a handle to it
//
*phProcess = OpenProcess(PROCESS_VM_READ, FALSE, dwPid);
if (*phProcess == NULL)
{
fwprintf(stderr, L"[-] Unable to open PID %d (err=%d)\n",
dwPid, GetLastError());
goto Cleanup;
}
bRes = TRUE;
Cleanup:
//
// Return result
//
return bRes;
}
BOOL
ConfigureThread(
_In_ PWCHAR pwszTid,
_Out_ PHANDLE phThread
)
{
DWORD dwPid;
BOOL bRes;
bRes = FALSE;
*phThread = NULL;
//
// Get the PID first
//
dwPid = wcstoul(pwszTid, NULL, 0);
if (dwPid == 0)
{
fwprintf(stderr, L"[-] Invalid TID: %s\n", pwszTid);
goto Cleanup;
}
//
// Open a handle to it
//
*phThread = OpenThread(THREAD_GET_CONTEXT, FALSE, dwPid);
if (*phThread == NULL)
{
fwprintf(stderr, L"[-] Unable to open TID %d (err=%d)\n",
dwPid, GetLastError());
goto Cleanup;
}
bRes = TRUE;
Cleanup:
//
// Return result
//
return bRes;
}
#endif // INTELPT
/* Lots of globals, but mostly for the status UI and other things where it
really makes no sense to haul them around as function parameters. */
static u8 *in_dir, /* Input directory with test cases */
*out_file, /* File to fuzz, if any */
*out_dir, /* Working & output directory */
*sync_dir, /* Synchronization directory */
*sync_id, /* Fuzzer ID */
*use_banner, /* Display banner */
*in_bitmap, /* Input bitmap */
*doc_path, /* Path to documentation dir */
*target_path, /* Path to target binary */
*target_cmd, /* command line of target */
*orig_cmdline; /* Original command line */
static u32 exec_tmout = EXEC_TIMEOUT; /* Configurable exec timeout (ms) */
static u32 init_tmout = 0; /* Configurable init timeout (ms) */
static u32 hang_tmout = EXEC_TIMEOUT; /* Timeout used for hang det (ms) */
static u64 mem_limit = MEM_LIMIT; /* Memory cap for child (MB) */
static u32 stats_update_freq = 1; /* Stats update frequency (execs) */
static u8 skip_deterministic, /* Skip deterministic stages? */
force_deterministic, /* Force deterministic stages? */
use_splicing, /* Recombine input files? */
dumb_mode, /* Run in non-instrumented mode? */
score_changed, /* Scoring for favorites changed? */
kill_signal, /* Signal that killed the child */
resuming_fuzz, /* Resuming an older fuzzing job? */
timeout_given, /* Specific timeout given? */
not_on_tty, /* stdout is not a tty */
term_too_small, /* terminal dimensions too small */
uses_asan, /* Target uses ASAN? */
no_forkserver, /* Disable forkserver? */
crash_mode, /* Crash mode! Yeah! */
in_place_resume, /* Attempt in-place resume? */
auto_changed, /* Auto-generated tokens changed? */
no_cpu_meter_red, /* Feng shui on the status screen */
no_arith, /* Skip most arithmetic ops */
shuffle_queue, /* Shuffle input queue? */
bitmap_changed = 1, /* Time to update bitmap? */
qemu_mode, /* Running in QEMU mode? */
skip_requested, /* Skip request, via SIGUSR1 */
run_over10m, /* Run time over 10 minutes? */
persistent_mode, /* Running in persistent mode? */
#ifdef INTELPT
intelpt_mode, /* Running in Intel PT mode? */
kernel_mode; /* Tracing kernel mode? */
#endif
drioless = 0; /* Running without DRIO? */
custom_dll_defined = 0; /* Custom DLL path defined ? */
persist_dr_cache = 0; /* Custom DLL path defined ? */
static s32 out_fd, /* Persistent fd for out_file */
dev_urandom_fd = -1, /* Persistent fd for /dev/urandom */
dev_null_fd = -1, /* Persistent fd for /dev/null */
fsrv_ctl_fd, /* Fork server control pipe (write) */
fsrv_st_fd; /* Fork server status pipe (read) */
child_pid = -1, /* PID of the fuzzed program */
out_dir_fd = -1; /* FD of the lock file */
HANDLE child_handle, child_thread_handle, child_debug_handle, child_debug_thread_handle;
char *dynamorio_dir;
char *client_params;
int fuzz_iterations_max = 5000, fuzz_iterations_current;
CRITICAL_SECTION critical_section;
u64 watchdog_timeout_time;
int watchdog_enabled;
static u8* trace_bits; /* SHM with instrumentation bitmap */
static u8 virgin_bits[MAP_SIZE], /* Regions yet untouched by fuzzing */
virgin_tmout[MAP_SIZE], /* Bits we haven't seen in tmouts */
virgin_crash[MAP_SIZE]; /* Bits we haven't seen in crashes */
static u8 var_bytes[MAP_SIZE]; /* Bytes that appear to be variable */
static HANDLE shm_handle; /* Handle of the SHM region */
static HANDLE pipe_handle; /* Handle of the name pipe */
static OVERLAPPED pipe_overlapped; /* Overlapped structure of pipe */
static char *fuzzer_id = NULL; /* The fuzzer ID or a randomized
seed allowing multiple instances */
static HANDLE devnul_handle; /* Handle of the nul device */
static u8 sinkhole_stds = 1; /* Sink-hole stdout/stderr messages?*/
static volatile u8 stop_soon, /* Ctrl-C pressed? */
clear_screen = 1, /* Window resized? */
child_timed_out; /* Traced process timed out? */
static u32 queued_paths, /* Total number of queued testcases */
queued_variable, /* Testcases with variable behavior */
queued_at_start, /* Total number of initial inputs */
queued_discovered, /* Items discovered during this run */
queued_imported, /* Items imported via -S */
queued_favored, /* Paths deemed favorable */
queued_with_cov, /* Paths with new coverage bytes */
pending_not_fuzzed, /* Queued but not done yet */
pending_favored, /* Pending favored paths */
cur_skipped_paths, /* Abandoned inputs in cur cycle */
cur_depth, /* Current path depth */
max_depth, /* Max path depth */
useless_at_start, /* Number of useless starting paths */
var_byte_count, /* Bitmap bytes with var behavior */
current_entry, /* Current queue entry ID */
havoc_div = 1; /* Cycle count divisor for havoc */
static u64 total_crashes, /* Total number of crashes */
unique_crashes, /* Crashes with unique signatures */
total_tmouts, /* Total number of timeouts */
unique_tmouts, /* Timeouts with unique signatures */
unique_hangs, /* Hangs with unique signatures */
total_execs, /* Total execve() calls */
start_time, /* Unix start time (ms) */
last_path_time, /* Time for most recent path (ms) */
last_crash_time, /* Time for most recent crash (ms) */
last_hang_time, /* Time for most recent hang (ms) */
last_crash_execs, /* Exec counter at last crash */
queue_cycle, /* Queue round counter */
cycles_wo_finds, /* Cycles without any new paths */
trim_execs, /* Execs done to trim input files */
bytes_trim_in, /* Bytes coming into the trimmer */
bytes_trim_out, /* Bytes coming outa the trimmer */
blocks_eff_total, /* Blocks subject to effector maps */
blocks_eff_select; /* Blocks selected as fuzzable */
static u32 subseq_tmouts; /* Number of timeouts in a row */
static u8 *stage_name = "init", /* Name of the current fuzz stage */
*stage_short, /* Short stage name */
*syncing_party; /* Currently syncing with... */
static s32 stage_cur, stage_max; /* Stage progression */
static s32 splicing_with = -1; /* Splicing with which test case? */
static u32 master_id, master_max; /* Master instance job splitting */
static u32 syncing_case; /* Syncing with case #... */
static s32 stage_cur_byte, /* Byte offset of current stage op */
stage_cur_val; /* Value used for stage op */
static u8 stage_val_type; /* Value type (STAGE_VAL_*) */
static u64 stage_finds[32], /* Patterns found per fuzz stage */
stage_cycles[32]; /* Execs per fuzz stage */
static u32 rand_cnt; /* Random number counter */
static u64 total_cal_us, /* Total calibration time (us) */
total_cal_cycles; /* Total calibration cycles */
static u64 total_bitmap_size, /* Total bit count for all bitmaps */
total_bitmap_entries; /* Number of bitmaps counted */
static u32 cpu_core_count; /* CPU core count */
static u64 cpu_aff = 0; /* Selected CPU core */
static FILE* plot_file; /* Gnuplot output file */
struct queue_entry {
u8* fname; /* File name for the test case */
u32 len; /* Input length */
u8 cal_failed, /* Calibration failed? */
trim_done, /* Trimmed? */
was_fuzzed, /* Had any fuzzing done yet? */
passed_det, /* Deterministic stages passed? */
has_new_cov, /* Triggers new coverage? */
var_behavior, /* Variable behavior? */
favored, /* Currently favored? */
fs_redundant; /* Marked as redundant in the fs? */
u32 bitmap_size, /* Number of bits set in bitmap */
exec_cksum; /* Checksum of the execution trace */
u64 exec_us, /* Execution time (us) */
handicap, /* Number of queue cycles behind */
depth; /* Path depth */
u8* trace_mini; /* Trace bytes, if kept */
u32 tc_ref; /* Trace bytes ref count */
struct queue_entry *next, /* Next element, if any */
*next_100; /* 100 elements ahead */
};
static struct queue_entry *queue, /* Fuzzing queue (linked list) */
*queue_cur, /* Current offset within the queue */
*queue_top, /* Top of the list */
*q_prev100; /* Previous 100 marker */
static struct queue_entry*
top_rated[MAP_SIZE]; /* Top entries for bitmap bytes */
struct extra_data {
u8* data; /* Dictionary token data */
u32 len; /* Dictionary token length */
u32 hit_cnt; /* Use count in the corpus */
};
static struct extra_data* extras; /* Extra tokens to fuzz with */
static u32 extras_cnt; /* Total number of tokens read */
static struct extra_data* a_extras; /* Automatically selected extras */
static u32 a_extras_cnt; /* Total number of tokens available */
static u8* (*post_handler)(u8* buf, u32* len);
/* Interesting values, as per config.h */
static s8 interesting_8[] = { INTERESTING_8 };
static s16 interesting_16[] = { INTERESTING_8, INTERESTING_16 };
static s32 interesting_32[] = { INTERESTING_8, INTERESTING_16, INTERESTING_32 };
/* Fuzzing stages */
enum {
/* 00 */ STAGE_FLIP1,
/* 01 */ STAGE_FLIP2,
/* 02 */ STAGE_FLIP4,
/* 03 */ STAGE_FLIP8,
/* 04 */ STAGE_FLIP16,
/* 05 */ STAGE_FLIP32,
/* 06 */ STAGE_ARITH8,
/* 07 */ STAGE_ARITH16,
/* 08 */ STAGE_ARITH32,
/* 09 */ STAGE_INTEREST8,
/* 10 */ STAGE_INTEREST16,
/* 11 */ STAGE_INTEREST32,
/* 12 */ STAGE_EXTRAS_UO,
/* 13 */ STAGE_EXTRAS_UI,
/* 14 */ STAGE_EXTRAS_AO,
/* 15 */ STAGE_HAVOC,
/* 16 */ STAGE_SPLICE
};
/* Stage value types */
enum {
/* 00 */ STAGE_VAL_NONE,
/* 01 */ STAGE_VAL_LE,
/* 02 */ STAGE_VAL_BE
};
/* Execution status fault codes */
enum {
/* 00 */ FAULT_NONE,
/* 01 */ FAULT_TMOUT,
/* 02 */ FAULT_CRASH,
/* 03 */ FAULT_ERROR,
/* 04 */ FAULT_NOINST,
/* 05 */ FAULT_NOBITS
};
/* Get unix time in milliseconds */
static u64 get_cur_time(void) {
u64 ret;
FILETIME filetime;
GetSystemTimeAsFileTime(&filetime);
ret = (((u64)filetime.dwHighDateTime)<<32) + (u64)filetime.dwLowDateTime;
return ret / 10000;
}
/* Get unix time in microseconds */
static u64 get_cur_time_us(void) {
u64 ret;
FILETIME filetime;
GetSystemTimeAsFileTime(&filetime);
ret = (((u64)filetime.dwHighDateTime)<<32) + (u64)filetime.dwLowDateTime;
return ret / 10;
}
/* Generate a random number (from 0 to limit - 1). This may
have slight bias. */
static inline u32 UR(u32 limit) {
if (!rand_cnt--) {
u32 seed[2];
rand_s(&seed[0]);
rand_s(&seed[1]);
srand(seed[0]);
rand_cnt = (RESEED_RNG / 2) + (seed[1] % RESEED_RNG);
}
return rand() % limit;
}
/* Shuffle an array of pointers. Might be slightly biased. */
static void shuffle_ptrs(void** ptrs, u32 cnt) {
u32 i;
for (i = 0; i < cnt - 2; i++) {
u32 j = i + UR(cnt - i);
void *s = ptrs[i];
ptrs[i] = ptrs[j];
ptrs[j] = s;
}
}
static u64 get_process_affinity(u32 process_id) {
/* if we can't get process affinity we treat it as if he doesn't have affinity */
u64 affinity = -1ULL;
DWORD_PTR process_affinity_mask = 0;
DWORD_PTR system_affinity_mask = 0;
HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, process_id);
if (process == NULL) {
return affinity;
}
if (GetProcessAffinityMask(process, &process_affinity_mask, &system_affinity_mask)) {
affinity = (u64)process_affinity_mask;
}
CloseHandle(process);
return affinity;
}
static u32 count_mask_bits(u64 mask) {
u32 count = 0;
while (mask) {
if (mask & 1) {
count++;
}
mask >>= 1;
}
return count;
}
static u32 get_bit_idx(u64 mask) {
u32 i;
for (i = 0; i < 64; i++) {
if (mask & (1ULL << i)) {
return i;
}
}
return 0;
}
static void bind_to_free_cpu(void) {
u8 cpu_used[64];
u32 i = 0;
PROCESSENTRY32 process_entry;
HANDLE process_snap = INVALID_HANDLE_VALUE;
memset(cpu_used, 0, sizeof(cpu_used));
if (cpu_core_count < 2) return;
/* Currently winafl doesn't support more than 64 cores */
if (cpu_core_count > 64) {
SAYF("\n" cLRD "[-] " cRST
"Uh-oh, looks like you have %u CPU cores on your system\n"
" winafl doesn't support more than 64 cores at the momement\n"
" you can set AFL_NO_AFFINITY and try again.\n",
cpu_core_count);
FATAL("Too many cpus for automatic binding");
}
if (getenv("AFL_NO_AFFINITY")) {
WARNF("Not binding to a CPU core (AFL_NO_AFFINITY set).");
return;
}
ACTF("Checking CPU core loadout...");
/* Introduce some jitter, in case multiple AFL tasks are doing the same
thing at the same time... */
srand(GetTickCount() + GetCurrentProcessId());
Sleep(R(1000) * 3);
process_snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (process_snap == INVALID_HANDLE_VALUE) {
FATAL("Failed to create snapshot");
}
process_entry.dwSize = sizeof(PROCESSENTRY32);
if (!Process32First(process_snap, &process_entry)) {
CloseHandle(process_snap);
FATAL("Failed to enumerate processes");
}
do {
unsigned long cpu_idx = 0;
u64 affinity = get_process_affinity(process_entry.th32ProcessID);
if ((affinity == 0) || (count_mask_bits(affinity) > 1)) continue;
cpu_idx = get_bit_idx(affinity);
cpu_used[cpu_idx] = 1;
} while (Process32Next(process_snap, &process_entry));
CloseHandle(process_snap);
/* If the user only uses subset of the core, prefer non-sequential cores
to avoid pinning two hyper threads of the same core */
for(i = 0; i < cpu_core_count; i += 2) if (!cpu_used[i]) break;
/* Fallback to the sequential scan */
if (i >= cpu_core_count) {
for(i = 0; i < cpu_core_count; i++) if (!cpu_used[i]) break;
}
if (i == cpu_core_count) {
SAYF("\n" cLRD "[-] " cRST
"Uh-oh, looks like all %u CPU cores on your system are allocated to\n"
" other instances of afl-fuzz (or similar CPU-locked tasks). Starting\n"
" another fuzzer on this machine is probably a bad plan, but if you are\n"
" absolutely sure, you can set AFL_NO_AFFINITY and try again.\n",
cpu_core_count);
FATAL("No more free CPU cores");
}
OKF("Found a free CPU core, binding to #%u.", i);
cpu_aff = 1ULL << i;
if (!SetProcessAffinityMask(GetCurrentProcess(), (DWORD_PTR)cpu_aff)) {
FATAL("Failed to set process affinity");
}
}
#ifndef IGNORE_FINDS
/* Helper function to compare buffers; returns first and last differing offset. We
use this to find reasonable locations for splicing two files. */
static void locate_diffs(u8* ptr1, u8* ptr2, u32 len, s32* first, s32* last) {
s32 f_loc = -1;
s32 l_loc = -1;
u32 pos;
for (pos = 0; pos < len; pos++) {
if (*(ptr1++) != *(ptr2++)) {
if (f_loc == -1) f_loc = pos;
l_loc = pos;
}
}
*first = f_loc;
*last = l_loc;
return;
}