forked from googleprojectzero/winafl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
winaflpt.c
1664 lines (1408 loc) · 51.6 KB
/
winaflpt.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
/*
WinAFL - Intel PT instrumentation and presistence via debugger code
------------------------------------------------
Written and maintained by Ivan Fratric <[email protected]>
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
#include <stdio.h>
#include <stdbool.h>
#include "windows.h"
#include "psapi.h"
#include "dbghelp.h"
#include "libipt.h"
#include "ipttool.h"
#include "intel-pt.h"
#include "types.h"
#include "config.h"
#include "debug.h"
#include "alloc-inl.h"
#include "winaflpt.h"
#include "ptdecode.h"
// tests the custom decoders gainst the corresponding
// reference implementatopns from Intel
// used only for debugging
// #define DECODER_CORRECTNESS_TEST
u64 get_cur_time(void);
char *argv_to_cmd(char** argv);
#define CALLCONV_MICROSOFT_X64 0
#define CALLCONV_THISCALL 1
#define CALLCONV_FASTCALL 2
#define CALLCONV_CDECL 3
#define CALLCONV_DEFAULT 4
#define BREAKPOINT_UNKNOWN 0
#define BREAKPOINT_ENTRYPOINT 1
#define BREAKPOINT_MODULELOADED 2
#define BREAKPOINT_FUZZMETHOD 3
#define WINAFL_LOOP_EXCEPTION 0x0AF1
#define DEBUGGER_PROCESS_EXIT 0
#define DEBUGGER_FUZZMETHOD_REACHED 1
#define DEBUGGER_FUZZMETHOD_END 2
#define DEBUGGER_CRASHED 3
#define DEBUGGER_HANGED 4
#define DECODER_TIP_FAST 0
#define DECODER_TIP_REFERENCE 1
#define DECODER_FULL_FAST 2
#define DECODER_FULL_REFERENCE 3
static HANDLE child_handle, child_thread_handle;
static HANDLE devnul_handle = INVALID_HANDLE_VALUE;
static int fuzz_iterations_current;
static DWORD fuzz_thread_id;
static DEBUG_EVENT dbg_debug_event;
static DWORD dbg_continue_status;
static bool dbg_continue_needed;
static uint64_t dbg_timeout_time;
static bool child_entrypoint_reached;
static unsigned char *trace_buffer;
static size_t trace_size;
extern u8 *trace_bits;
extern HANDLE child_handle, child_thread_handle;
extern int fuzz_iterations_current;
extern HANDLE devnul_handle;
extern u8 sinkhole_stds;
extern u64 mem_limit;
extern u64 cpu_aff;
extern char *fuzzer_id;
static FILE *debug_log = NULL;
static struct pt_image_section_cache *section_cache;
static char section_cache_dir[MAX_PATH];
static int wow64_target = 0;
static size_t child_ptr_size = sizeof(void *);
address_range* coverage_ip_ranges = NULL;
size_t num_ip_ranges = 0;
static bool need_build_ranges = true;
static size_t last_ring_buffer_offset = 0;
#define USAGE_CHECK(condition, message) if(!(condition)) FATAL("%s\n", message);
enum {
/* 00 */ FAULT_NONE,
/* 01 */ FAULT_TMOUT,
/* 02 */ FAULT_CRASH,
/* 03 */ FAULT_ERROR,
/* 04 */ FAULT_NOINST,
/* 05 */ FAULT_NOBITS
};
typedef struct _module_info_t {
char module_name[MAX_PATH];
int isid;
void *base;
size_t size;
struct _module_info_t *next;
} module_info_t;
static module_info_t *all_modules = NULL;
typedef struct _winafl_option_t {
bool debug_mode;
int coverage_kind;
module_info_t *coverage_modules;
char fuzz_module[MAX_PATH];
char fuzz_method[MAX_PATH];
unsigned long fuzz_offset;
int fuzz_iterations;
int num_fuz_args;
int callconv;
int decoder;
bool thread_coverage;
unsigned long trace_buffer_size;
unsigned long trace_cache_size;
bool persistent_trace;
void **func_args;
void *sp;
void *fuzz_address;
} winafl_option_t;
static winafl_option_t options;
struct winafl_breakpoint {
void *address;
int type;
unsigned char original_opcode;
char module_name[MAX_PATH];
void *module_base;
struct winafl_breakpoint *next;
};
struct winafl_breakpoint *breakpoints;
static void
winaflpt_options_init(int argc, const char *argv[])
{
int i;
const char *token;
module_info_t *coverage_modules;
/* default values */
options.debug_mode = false;
options.coverage_kind = COVERAGE_BB;
options.coverage_modules = NULL;
options.fuzz_module[0] = 0;
options.fuzz_method[0] = 0;
options.fuzz_offset = 0;
options.fuzz_iterations = 1000;
options.func_args = NULL;
options.num_fuz_args = 0;
options.thread_coverage = true;
options.callconv = CALLCONV_DEFAULT;
options.decoder = DECODER_FULL_FAST;
options.trace_buffer_size = TRACE_BUFFER_SIZE_DEFAULT;
options.trace_cache_size = 0;
options.persistent_trace = true;
for (i = 0; i < argc; i++) {
token = argv[i];
if (strcmp(token, "-thread_coverage") == 0)
options.thread_coverage = true;
else if (strcmp(token, "-debug") == 0)
options.debug_mode = true;
else if (strcmp(token, "-nopersistent_trace") == 0)
options.persistent_trace = false;
else if (strcmp(token, "-covtype") == 0) {
USAGE_CHECK((i + 1) < argc, "missing coverage type");
token = argv[++i];
if (strcmp(token, "bb") == 0) options.coverage_kind = COVERAGE_BB;
else if (strcmp(token, "edge") == 0) options.coverage_kind = COVERAGE_EDGE;
else USAGE_CHECK(false, "invalid coverage type");
}
else if (strcmp(token, "-coverage_module") == 0) {
USAGE_CHECK((i + 1) < argc, "missing module");
coverage_modules = options.coverage_modules;
options.coverage_modules = (module_info_t *)malloc(sizeof(module_info_t));
options.coverage_modules->next = coverage_modules;
options.coverage_modules->isid = 0;
options.coverage_modules->base = NULL;
options.coverage_modules->size = 0;
strncpy(options.coverage_modules->module_name, argv[++i], MAX_PATH);
}
else if (strcmp(token, "-target_module") == 0) {
USAGE_CHECK((i + 1) < argc, "missing module");
strncpy(options.fuzz_module, argv[++i], MAX_PATH);
}
else if (strcmp(token, "-target_method") == 0) {
USAGE_CHECK((i + 1) < argc, "missing method");
strncpy(options.fuzz_method, argv[++i], MAX_PATH);
}
else if (strcmp(token, "-fuzz_iterations") == 0) {
USAGE_CHECK((i + 1) < argc, "missing number of iterations");
options.fuzz_iterations = atoi(argv[++i]);
}
else if (strcmp(token, "-nargs") == 0) {
USAGE_CHECK((i + 1) < argc, "missing number of arguments");
options.num_fuz_args = atoi(argv[++i]);
}
else if (strcmp(token, "-target_offset") == 0) {
USAGE_CHECK((i + 1) < argc, "missing offset");
options.fuzz_offset = strtoul(argv[++i], NULL, 0);
}
else if (strcmp(token, "-trace_size") == 0) {
USAGE_CHECK((i + 1) < argc, "missing trace size");
options.trace_buffer_size = strtoul(argv[++i], NULL, 0);
}
else if (strcmp(token, "-trace_cache_size") == 0) {
USAGE_CHECK((i + 1) < argc, "missing trace cache size");
options.trace_cache_size = strtoul(argv[++i], NULL, 0);
}
else if (strcmp(token, "-call_convention") == 0) {
USAGE_CHECK((i + 1) < argc, "missing calling convention");
++i;
if (strcmp(argv[i], "stdcall") == 0)
options.callconv = CALLCONV_CDECL;
else if (strcmp(argv[i], "fastcall") == 0)
options.callconv = CALLCONV_FASTCALL;
else if (strcmp(argv[i], "thiscall") == 0)
options.callconv = CALLCONV_THISCALL;
else if (strcmp(argv[i], "ms64") == 0)
options.callconv = CALLCONV_MICROSOFT_X64;
else
FATAL("Unknown calling convention");
} else if (strcmp(token, "-decoder") == 0) {
USAGE_CHECK((i + 1) < argc, "missing decoder");
++i;
if (strcmp(argv[i], "tip") == 0)
options.decoder = DECODER_TIP_FAST;
else if (strcmp(argv[i], "tip_ref") == 0)
options.decoder = DECODER_TIP_REFERENCE;
else if (strcmp(argv[i], "full") == 0)
options.decoder = DECODER_FULL_FAST;
else if (strcmp(argv[i], "full_ref") == 0)
options.decoder = DECODER_FULL_REFERENCE;
else
FATAL("Unknown decoder value");
} else {
FATAL("UNRECOGNIZED OPTION: \"%s\"\n", token);
}
}
if (options.fuzz_module[0] && (options.fuzz_offset == 0) && (options.fuzz_method[0] == 0)) {
FATAL("If fuzz_module is specified, then either fuzz_method or fuzz_offset must be as well");
}
if (options.num_fuz_args) {
options.func_args = (void **)malloc(options.num_fuz_args * sizeof(void *));
}
}
int address_range_compare(const void * a, const void * b) {
if (((address_range *)a)->start >= ((address_range *)b)->start) return 1;
else return -1;
}
void build_address_ranges() {
int num_loaded_modules;
module_info_t *current_module;
if (coverage_ip_ranges) free(coverage_ip_ranges);
if (!options.coverage_modules) {
num_ip_ranges = 1;
coverage_ip_ranges = (address_range*)malloc(num_ip_ranges * sizeof(address_range));
coverage_ip_ranges[0].start = 0;
coverage_ip_ranges[0].end = 0xFFFFFFFFFFFFFFFFULL;
coverage_ip_ranges[0].collect = 1;
return;
}
// count loaded modules
num_loaded_modules = 0;
current_module = options.coverage_modules;
while (current_module) {
if (current_module->size > 0) {
num_loaded_modules++;
}
current_module = current_module->next;
}
address_range* tmp_buf = (address_range*)malloc(num_loaded_modules * sizeof(address_range));
num_loaded_modules = 0;
current_module = options.coverage_modules;
while (current_module) {
if (current_module->size > 0) {
tmp_buf[num_loaded_modules].start = (uint64_t)current_module->base;
tmp_buf[num_loaded_modules].end = (uint64_t)current_module->base + current_module->size - 1;
tmp_buf[num_loaded_modules].collect = 1;
num_loaded_modules++;
}
current_module = current_module->next;
}
qsort(tmp_buf, num_loaded_modules, sizeof(address_range), address_range_compare);
num_ip_ranges = num_loaded_modules * 2 + 1;
coverage_ip_ranges = (address_range*)malloc(num_ip_ranges * sizeof(address_range));
uint64_t current_address = 0;
for (int i = 0; i < num_loaded_modules; i++) {
coverage_ip_ranges[2 * i].start = current_address;
coverage_ip_ranges[2 * i].end = tmp_buf[i].start - 1;
coverage_ip_ranges[2 * i].collect = 0;
coverage_ip_ranges[2 * i + 1] = tmp_buf[i];
current_address = tmp_buf[i].end + 1;
}
coverage_ip_ranges[2 * num_loaded_modules].start = current_address;
coverage_ip_ranges[2 * num_loaded_modules].end = 0xFFFFFFFFFFFFFFFFULL;
coverage_ip_ranges[2 * num_loaded_modules].collect = 0;
free(tmp_buf);
}
// appends new data to the trace_buffer
void append_trace_data(unsigned char *trace_data, size_t append_size) {
size_t space_left = options.trace_buffer_size - trace_size;
if (!space_left) {
// stop collecting trace if the trace buffer is full;
printf("Warning: Trace buffer is full\n");
return;
}
if (append_size > space_left) {
append_size = space_left;
}
if (append_size == 0) return;
memcpy(trace_buffer + trace_size, trace_data, append_size);
trace_size += append_size;
}
// returns true if the ring buffer was overflowed
bool collect_thread_trace(PIPT_TRACE_HEADER traceHeader) {
// printf("ring offset: %u\n", traceHeader->RingBufferOffset);
bool trace_buffer_overflow = false;
unsigned char psb_and_psbend[] = {
0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82,
0x02, 0x82, 0x02, 0x82, 0x02, 0x82, 0x02, 0x82,
0x02, 0x23
};
trace_size = 0;
if (options.persistent_trace) {
// an ugly hack: trace might not start with a psb (synchronization) packet
// so we are just adding one. This assumes the state has been properly
// flushed when a breakpoint between two iterations has been hit
// which does appear to be the case. However, if this doesn't occur
// persistent tracing will not work properly
append_trace_data(psb_and_psbend, sizeof(psb_and_psbend));
// first, optimistically assume the buffer didn't overflow
if (traceHeader->RingBufferOffset > last_ring_buffer_offset) {
append_trace_data(traceHeader->Trace + last_ring_buffer_offset, traceHeader->RingBufferOffset - last_ring_buffer_offset);
}
else if (traceHeader->RingBufferOffset < last_ring_buffer_offset) {
append_trace_data(traceHeader->Trace + last_ring_buffer_offset, traceHeader->TraceSize - last_ring_buffer_offset);
append_trace_data(traceHeader->Trace, traceHeader->RingBufferOffset);
}
if (!check_trace_start(trace_buffer, trace_size, (uint64_t)options.fuzz_address)) {
// most likely the ring buffer overflowd, extract what we can (trace tail)
trace_size = 0;
trace_buffer_overflow = true;
printf("Warning: Trace buffer overflowed, trace will be truncated\n");
if (options.debug_mode) fprintf(debug_log, "Trace buffer overflowed, trace will be truncated\n");
char *trailing_data = traceHeader->Trace + traceHeader->RingBufferOffset;
size_t trailing_size = traceHeader->TraceSize - traceHeader->RingBufferOffset;
append_trace_data(trailing_data, trailing_size);
append_trace_data(traceHeader->Trace, traceHeader->RingBufferOffset);
}
last_ring_buffer_offset = traceHeader->RingBufferOffset;
} else {
// check if the trace buffer overflowed
char *trailing_data = traceHeader->Trace + traceHeader->RingBufferOffset;
size_t trailing_size = traceHeader->TraceSize - traceHeader->RingBufferOffset;
if (findpsb(&trailing_data, &trailing_size)) {
trace_buffer_overflow = true;
printf("Warning: Trace buffer overflowed, trace will be truncated\n");
if (options.debug_mode) fprintf(debug_log, "Trace buffer overflowed, trace will be truncated\n");
append_trace_data(trailing_data, trailing_size);
}
append_trace_data(traceHeader->Trace, traceHeader->RingBufferOffset);
}
return trace_buffer_overflow;
}
// parse PIPT_TRACE_DATA, extract trace bits and add them to the trace_buffer
// returns true if the trace ring buffer overflowed
bool collect_trace(PIPT_TRACE_DATA pTraceData)
{
bool trace_buffer_overflow = false;
PIPT_TRACE_HEADER traceHeader;
DWORD dwTraceSize;
dwTraceSize = pTraceData->TraceSize;
traceHeader = (PIPT_TRACE_HEADER)pTraceData->TraceData;
while (dwTraceSize > (unsigned)(FIELD_OFFSET(IPT_TRACE_HEADER, Trace))) {
if (traceHeader->ThreadId == fuzz_thread_id) {
trace_buffer_overflow = collect_thread_trace(traceHeader);
}
dwTraceSize -= (FIELD_OFFSET(IPT_TRACE_HEADER, Trace) + traceHeader->TraceSize);
traceHeader = (PIPT_TRACE_HEADER)(traceHeader->Trace +
traceHeader->TraceSize);
}
return trace_buffer_overflow;
}
// returns an array of handles for all modules loaded in the target process
DWORD get_all_modules(HMODULE **modules) {
DWORD module_handle_storage_size = 1024 * sizeof(HMODULE);
HMODULE *module_handles = (HMODULE *)malloc(module_handle_storage_size);
DWORD hmodules_size;
while (true) {
if (!EnumProcessModulesEx(child_handle, module_handles, module_handle_storage_size, &hmodules_size, LIST_MODULES_ALL)) {
FATAL("EnumProcessModules failed, %x\n", GetLastError());
}
if (hmodules_size <= module_handle_storage_size) break;
module_handle_storage_size *= 2;
module_handles = (HMODULE *)realloc(module_handles, module_handle_storage_size);
}
*modules = module_handles;
return hmodules_size / sizeof(HMODULE);
}
// parses PE headers and gets the module entypoint
void *get_entrypoint(void *base_address) {
unsigned char headers[4096];
size_t num_read = 0;
if (!ReadProcessMemory(child_handle, base_address, headers, 4096, &num_read) || (num_read != 4096)) {
FATAL("Error reading target memory\n");
}
DWORD pe_offset;
pe_offset = *((DWORD *)(headers + 0x3C));
char *pe = headers + pe_offset;
DWORD signature = *((DWORD *)pe);
if (signature != 0x00004550) {
FATAL("PE signature error\n");
}
pe = pe + 0x18;
WORD magic = *((WORD *)pe);
if ((magic != 0x10b) && (magic != 0x20b)) {
FATAL("Unknown PE magic value\n");
}
DWORD entrypoint_offset = *((DWORD *)(pe + 16));
if (entrypoint_offset == 0) return NULL;
return (char *)base_address + entrypoint_offset;
}
// adds a breakpoint at a specified address
// type, module_name and module_base are all additional information
// that can be accessed later when the breakpoint gets hit
void add_breakpoint(void *address, int type, char *module_name, void *module_base) {
struct winafl_breakpoint *new_breakpoint = (struct winafl_breakpoint *)malloc(sizeof(struct winafl_breakpoint));
size_t rwsize = 0;
if(!ReadProcessMemory(child_handle, address, &(new_breakpoint->original_opcode), 1, &rwsize) || (rwsize != 1)) {
FATAL("Error reading target memory\n");
}
rwsize = 0;
unsigned char cc = 0xCC;
if (!WriteProcessMemory(child_handle, address, &cc, 1, &rwsize) || (rwsize != 1)) {
FATAL("Error writing target memory\n");
}
FlushInstructionCache(child_handle, address, 1);
new_breakpoint->address = address;
new_breakpoint->type = type;
if (module_name) {
strcpy(new_breakpoint->module_name, module_name);
} else {
new_breakpoint->module_name[0] = 0;
}
new_breakpoint->module_base = module_base;
new_breakpoint->next = breakpoints;
breakpoints = new_breakpoint;
}
// damn it Windows, why don't you have a GetProcAddress
// that works on another process
DWORD get_proc_offset(char *data, char *name) {
DWORD pe_offset;
pe_offset = *((DWORD *)(data + 0x3C));
char *pe = data + pe_offset;
DWORD signature = *((DWORD *)pe);
if (signature != 0x00004550) {
return 0;
}
pe = pe + 0x18;
WORD magic = *((WORD *)pe);
DWORD exporttableoffset;
if (magic == 0x10b) {
exporttableoffset = *(DWORD *)(pe + 96);
} else if (magic == 0x20b) {
exporttableoffset = *(DWORD *)(pe + 112);
} else {
return 0;
}
if (!exporttableoffset) return 0;
char *exporttable = data + exporttableoffset;
DWORD numentries = *(DWORD *)(exporttable + 24);
DWORD addresstableoffset = *(DWORD *)(exporttable + 28);
DWORD nameptrtableoffset = *(DWORD *)(exporttable + 32);
DWORD ordinaltableoffset = *(DWORD *)(exporttable + 36);
DWORD *nameptrtable = (DWORD *)(data + nameptrtableoffset);
WORD *ordinaltable = (WORD *)(data + ordinaltableoffset);
DWORD *addresstable = (DWORD *)(data + addresstableoffset);
DWORD i;
for (i = 0; i < numentries; i++) {
char *nameptr = data + nameptrtable[i];
if (strcmp(name, nameptr) == 0) break;
}
if (i == numentries) return 0;
WORD oridnal = ordinaltable[i];
DWORD offset = addresstable[oridnal];
return offset;
}
// attempt to obtain the fuzz_offset in various ways
char *get_fuzz_method_offset(HMODULE module) {
MODULEINFO module_info;
GetModuleInformation(child_handle, module, &module_info, sizeof(module_info));
// if fuzz_offset is defined, use that
if (options.fuzz_offset) {
return (char *)module_info.lpBaseOfDll + options.fuzz_offset;
}
// try the exported symbols next
BYTE *modulebuf = (BYTE *)malloc(module_info.SizeOfImage);
size_t num_read;
if (!ReadProcessMemory(child_handle, module_info.lpBaseOfDll, modulebuf, module_info.SizeOfImage, &num_read) || (num_read != module_info.SizeOfImage)) {
FATAL("Error reading target memory\n");
}
DWORD fuzz_offset = get_proc_offset(modulebuf, options.fuzz_method);
free(modulebuf);
if (fuzz_offset) {
return (char *)module + fuzz_offset;
}
// finally, try the debug symbols
char *fuzz_method = NULL;
char base_name[MAX_PATH];
GetModuleBaseNameA(child_handle, module, (LPSTR)(&base_name), sizeof(base_name));
char module_path[MAX_PATH];
if(!GetModuleFileNameExA(child_handle, module, module_path, sizeof(module_path))) return NULL;
ULONG64 buffer[(sizeof(SYMBOL_INFO) +
MAX_SYM_NAME * sizeof(TCHAR) +
sizeof(ULONG64) - 1) /
sizeof(ULONG64)];
PSYMBOL_INFO pSymbol = (PSYMBOL_INFO)buffer;
pSymbol->SizeOfStruct = sizeof(SYMBOL_INFO);
pSymbol->MaxNameLen = MAX_SYM_NAME;
SymInitialize(child_handle, NULL, false);
DWORD64 sym_base_address = SymLoadModuleEx(child_handle, NULL, module_path, NULL, 0, 0, NULL, 0);
if (SymFromName(child_handle, options.fuzz_method, pSymbol)) {
options.fuzz_offset = (unsigned long)(pSymbol->Address - sym_base_address);
fuzz_method = (char *)module_info.lpBaseOfDll + options.fuzz_offset;
}
SymCleanup(child_handle);
return fuzz_method;
}
// should we collect coverage for this module
module_info_t *is_coverage_module(char *module_name) {
module_info_t *current_module = options.coverage_modules;
while (current_module) {
if (_stricmp(module_name, current_module->module_name) == 0) {
return current_module;
}
current_module = current_module->next;
}
return NULL;
}
// check if the same module was already loaded
module_info_t *get_loaded_module(char *module_name, void *base) {
module_info_t *current_module = all_modules;
while (current_module) {
if (_stricmp(module_name, current_module->module_name) == 0) {
if (base == NULL || base == current_module->base) {
return current_module;
}
}
current_module = current_module->next;
}
return NULL;
}
// find if there is a *different* module that previously occupied
// the same space
module_info_t *get_intersecting_module(char *module_name, void *base, DWORD size) {
module_info_t *current_module = all_modules;
while (current_module) {
if (((uint64_t)current_module->base + current_module->size <= (uint64_t)base) ||
((uint64_t)base + size <= (uint64_t)current_module->base)) {
current_module = current_module->next;
continue;
}
return current_module;
}
return NULL;
}
void on_coverage_module_loaded(HMODULE module, module_info_t *target_module) {
MODULEINFO module_info;
GetModuleInformation(child_handle, module, &module_info, sizeof(module_info));
target_module->base = module_info.lpBaseOfDll;
target_module->size = module_info.SizeOfImage;
need_build_ranges = true;
}
size_t ReadProcessMemory_tolerant(HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize) {
LPCVOID end_address = (char *)lpBaseAddress + nSize;
LPCVOID cur_address = lpBaseAddress;
MEMORY_BASIC_INFORMATION meminfobuf;
size_t size_read;
size_t total_size_read = 0;
while (cur_address < end_address) {
size_t ret = VirtualQueryEx(hProcess, (LPCVOID)cur_address, &meminfobuf, sizeof(MEMORY_BASIC_INFORMATION));
if (!ret) break;
size_t offset = (size_t)meminfobuf.BaseAddress - (size_t)lpBaseAddress;
size_t to_read = meminfobuf.RegionSize;
if ((offset + to_read) > nSize) {
to_read = nSize - offset;
}
if (ReadProcessMemory(child_handle, meminfobuf.BaseAddress, (char *)lpBuffer + offset, to_read, &size_read)) {
total_size_read += size_read;
}
cur_address = (char *)meminfobuf.BaseAddress + meminfobuf.RegionSize;
}
return total_size_read;
}
void add_module_to_section_cache(HMODULE module, char *module_name) {
module_info_t *loaded_module;
MODULEINFO module_info;
GetModuleInformation(child_handle, module, &module_info, sizeof(module_info));
// handle the case where module was loaded previously
loaded_module = get_loaded_module(module_name, module_info.lpBaseOfDll);
if (loaded_module) {
// same module loaded on the same address, skip
return;
}
// this will *probably* never happen but check for it anyway
loaded_module = get_intersecting_module(module_name, module_info.lpBaseOfDll, module_info.SizeOfImage);
if (loaded_module) {
FATAL("Module %s loaded in the address range that module %s previously occupied. This is currently unsupported.",
module_name, loaded_module->module_name);
}
loaded_module = (module_info_t *)malloc(sizeof(module_info_t));
strcpy(loaded_module->module_name, module_name);
loaded_module->base = module_info.lpBaseOfDll;
loaded_module->size = module_info.SizeOfImage;
// todo put these files in a separate directory and clean it periodically
char tmpfilename[MAX_PATH];
sprintf(tmpfilename, "%s\\sectioncache_%p.dat", section_cache_dir, module_info.lpBaseOfDll);
BYTE *modulebuf = (BYTE *)malloc(module_info.SizeOfImage);
size_t num_read;
if (!ReadProcessMemory(child_handle, module_info.lpBaseOfDll, modulebuf, module_info.SizeOfImage, &num_read) || (num_read != module_info.SizeOfImage)) {
if (!ReadProcessMemory_tolerant(child_handle, module_info.lpBaseOfDll, modulebuf, module_info.SizeOfImage)) {
FATAL("Error reading memory for module %s", module_name);
}
}
// this is pretty horrible, writing a file only to be read again
// but libipt only supports reading sections from file, not memory
FILE *fp = fopen(tmpfilename, "wb");
if (!fp) {
FATAL("Error opening image cache file.");
}
fwrite(modulebuf, 1, module_info.SizeOfImage, fp);
fclose(fp);
loaded_module->isid = pt_iscache_add_file(section_cache, tmpfilename, 0, module_info.SizeOfImage, (uint64_t)module_info.lpBaseOfDll);
free(modulebuf);
if (loaded_module->isid <= 0) {
FATAL("Error adding file to pt cache.");
}
loaded_module->next = all_modules;
all_modules = loaded_module;
}
// called when a potentialy interesting module gets loaded
void on_module_loaded(HMODULE module, char *module_name) {
MODULEINFO module_info;
GetModuleInformation(child_handle, module, &module_info, sizeof(module_info));
// printf("In on_module_loaded, name: %s, base: %p\n", module_name, module_info.lpBaseOfDll);
module_info_t *coverage_module = is_coverage_module(module_name);
if (coverage_module) {
on_coverage_module_loaded(module, coverage_module);
}
if (options.decoder == DECODER_FULL_FAST || options.decoder == DECODER_FULL_REFERENCE) {
add_module_to_section_cache(module, module_name);
}
if (_stricmp(module_name, options.fuzz_module) == 0) {
char * fuzz_address = get_fuzz_method_offset(module);
if (!fuzz_address) {
FATAL("Error determining target method address\n");
}
// printf("Fuzz method address: %p\n", fuzz_address);
options.fuzz_address = fuzz_address;
add_breakpoint(fuzz_address, BREAKPOINT_FUZZMETHOD, NULL, 0);
}
}
void read_stack(void *stack_addr, void **buffer, size_t numitems) {
size_t numrw = 0;
#ifdef _WIN64
if (wow64_target) {
uint32_t *buf32 = (uint32_t *)malloc(numitems * child_ptr_size);
ReadProcessMemory(child_handle, stack_addr, buf32, numitems * child_ptr_size, &numrw);
for (size_t i = 0; i < numitems; i++) {
buffer[i] = (void *)((size_t)buf32[i]);
}
free(buf32);
return;
}
#endif
ReadProcessMemory(child_handle, stack_addr, buffer, numitems * child_ptr_size, &numrw);
}
void write_stack(void *stack_addr, void **buffer, size_t numitems) {
size_t numrw = 0;
#ifdef _WIN64
if (wow64_target) {
uint32_t *buf32 = (uint32_t *)malloc(numitems * child_ptr_size);
for (size_t i = 0; i < numitems; i++) {
buf32[i] = (uint32_t)((size_t)buffer[i]);
}
WriteProcessMemory(child_handle, stack_addr, buf32, numitems * child_ptr_size, &numrw);
free(buf32);
return;
}
#endif
WriteProcessMemory(child_handle, stack_addr, buffer, numitems * child_ptr_size, &numrw);
}
// called when the target method is called *for the first time only*
void on_target_method(DWORD thread_id) {
// printf("in OnTargetMethod\n");
fuzz_thread_id = thread_id;
size_t numrw = 0;
CONTEXT lcContext;
lcContext.ContextFlags = CONTEXT_ALL;
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
GetThreadContext(thread_handle, &lcContext);
// read out and save the params
#ifdef _WIN64
options.sp = (void *)lcContext.Rsp;
#else
options.sp = (void *)lcContext.Esp;
#endif
switch (options.callconv) {
#ifdef _WIN64
case CALLCONV_DEFAULT:
case CALLCONV_MICROSOFT_X64:
if (options.num_fuz_args > 0) options.func_args[0] = (void *)lcContext.Rcx;
if (options.num_fuz_args > 1) options.func_args[1] = (void *)lcContext.Rdx;
if (options.num_fuz_args > 2) options.func_args[2] = (void *)lcContext.R8;
if (options.num_fuz_args > 3) options.func_args[3] = (void *)lcContext.R9;
if (options.num_fuz_args > 4) {
read_stack((void *)(lcContext.Rsp + 5 * child_ptr_size), options.func_args + 4, options.num_fuz_args - 4);
}
break;
case CALLCONV_CDECL:
if (options.num_fuz_args > 0) {
read_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args, options.num_fuz_args);
}
break;
case CALLCONV_FASTCALL:
if (options.num_fuz_args > 0) options.func_args[0] = (void *)lcContext.Rcx;
if (options.num_fuz_args > 1) options.func_args[1] = (void *)lcContext.Rdx;
if (options.num_fuz_args > 3) {
read_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args + 2, options.num_fuz_args - 2);
}
break;
case CALLCONV_THISCALL:
if (options.num_fuz_args > 0) options.func_args[0] = (void *)lcContext.Rcx;
if (options.num_fuz_args > 3) {
read_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args + 1, options.num_fuz_args - 1);
}
break;
#else
case CALLCONV_MICROSOFT_X64:
FATAL("X64 callong convention not supported for 32-bit targets");
break;
case CALLCONV_DEFAULT:
case CALLCONV_CDECL:
if (options.num_fuz_args > 0) {
read_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args, options.num_fuz_args);
}
break;
case CALLCONV_FASTCALL:
if (options.num_fuz_args > 0) options.func_args[0] = (void *)lcContext.Ecx;
if (options.num_fuz_args > 1) options.func_args[1] = (void *)lcContext.Edx;
if (options.num_fuz_args > 3) {
read_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args + 2, options.num_fuz_args - 2);
}
break;
case CALLCONV_THISCALL:
if (options.num_fuz_args > 0) options.func_args[0] = (void *)lcContext.Ecx;
if (options.num_fuz_args > 3) {
read_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args + 1, options.num_fuz_args - 1);
}
break;
#endif
default:
break;
}
// todo store any target-specific additional context here
// modify the return address on the stack so that an exception is triggered
// when the target function finishes executing
// another option would be to allocate a block of executable memory
// and point return address over there, but this is quicker
size_t return_address = WINAFL_LOOP_EXCEPTION;
WriteProcessMemory(child_handle, options.sp, &return_address, child_ptr_size, &numrw);
CloseHandle(thread_handle);
}
// called every time the target method returns
void on_target_method_ended(DWORD thread_id) {
// printf("in OnTargetMethodEnded\n");
CONTEXT lcContext;
lcContext.ContextFlags = CONTEXT_ALL;
HANDLE thread_handle = OpenThread(THREAD_ALL_ACCESS, FALSE, thread_id);
GetThreadContext(thread_handle, &lcContext);
// restore params
#ifdef _WIN64
lcContext.Rip = (size_t)options.fuzz_address;
lcContext.Rsp = (size_t)options.sp;
#else
lcContext.Eip = (size_t)options.fuzz_address;
lcContext.Esp = (size_t)options.sp;
#endif
switch (options.callconv) {
#ifdef _WIN64
case CALLCONV_DEFAULT:
case CALLCONV_MICROSOFT_X64:
if (options.num_fuz_args > 0) lcContext.Rcx = (size_t)options.func_args[0];
if (options.num_fuz_args > 1) lcContext.Rdx = (size_t)options.func_args[1];
if (options.num_fuz_args > 2) lcContext.R8 = (size_t)options.func_args[2];
if (options.num_fuz_args > 3) lcContext.R9 = (size_t)options.func_args[3];
if (options.num_fuz_args > 4) {
write_stack((void *)(lcContext.Rsp + 5 * child_ptr_size), options.func_args + 4, options.num_fuz_args - 4);
}
break;
case CALLCONV_CDECL:
if (options.num_fuz_args > 0) {
write_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args, options.num_fuz_args);
}
break;
case CALLCONV_FASTCALL:
if (options.num_fuz_args > 0) lcContext.Rcx = (size_t)options.func_args[0];
if (options.num_fuz_args > 1) lcContext.Rdx = (size_t)options.func_args[1];
if (options.num_fuz_args > 3) {
write_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args + 2, options.num_fuz_args - 2);
}
break;
case CALLCONV_THISCALL:
if (options.num_fuz_args > 0) lcContext.Rcx = (size_t)options.func_args[0];
if (options.num_fuz_args > 3) {
write_stack((void *)(lcContext.Rsp + child_ptr_size), options.func_args + 1, options.num_fuz_args - 1);
}
break;
#else
case CALLCONV_MICROSOFT_X64:
FATAL("X64 callong convention not supported for 32-bit targets");
break;
case CALLCONV_DEFAULT:
case CALLCONV_CDECL:
if (options.num_fuz_args > 0) {
write_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args, options.num_fuz_args);
}
break;
case CALLCONV_FASTCALL:
if (options.num_fuz_args > 0) lcContext.Ecx = (size_t)options.func_args[0];
if (options.num_fuz_args > 1) lcContext.Edx = (size_t)options.func_args[1];
if (options.num_fuz_args > 3) {
write_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args + 2, options.num_fuz_args - 2);
}
break;
case CALLCONV_THISCALL:
if (options.num_fuz_args > 0) lcContext.Ecx = (size_t)options.func_args[0];
if (options.num_fuz_args > 3) {
write_stack((void *)(lcContext.Esp + child_ptr_size), options.func_args + 1, options.num_fuz_args - 1);
}
break;
#endif
default:
break;
}
// todo restore any target-specific additional context here
SetThreadContext(thread_handle, &lcContext);
CloseHandle(thread_handle);
}
// called when process entrypoint gets reached