-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfuzz.cpp
More file actions
executable file
·527 lines (458 loc) · 15.1 KB
/
fuzz.cpp
File metadata and controls
executable file
·527 lines (458 loc) · 15.1 KB
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
#include <pin.H>
#include <stdio.h>
#include <list>
#include <iostream>
#define VERSION "0.21"
#define FUZZ_DATA_SIZE 0x1000
#define MAP_SIZE (1 << 16)
#ifdef _WIN64
#define __win__ 1
#elif _WIN32
#define __win__ 1
#endif
#if defined(__i386__) || defined(_WIN32)
#define HEX_FMT "0x%08x"
#define INT_FMT "%u"
#endif
#if defined(__x86_64__) || defined(_WIN64)
#define HEX_FMT "0x%016lx"
#define INT_FMT "%lu"
#endif
namespace windows {
#include <Windows.h>
HANDLE pipe_sync, pipe_data;
OVERLAPPED pipe_overlapped;
BOOL has_pipe_sync_connected = FALSE;
BOOL has_pipe_data_connected = FALSE;
char read_from_pipe();
void write_to_pipe(char *);
void get_fuzz_data();
}
CONTEXT snapshot;
BOOL is_saved_snapshot = FALSE;
BOOL in_fuzz_area = FALSE;
BOOL was_crash = FALSE;
ADDRINT min_addr = 0;
ADDRINT max_addr = 0;
ADDRINT entry_addr = 0;
ADDRINT exit_addr = 0;
string need_module;
unsigned char original_fuzzed_data[FUZZ_DATA_SIZE];
unsigned int previous_fuzz_data_len = 0;
unsigned char bitmap[MAP_SIZE];
uint8_t *bitmap_shm = 0;
ADDRINT last_id = 0;
long unsigned int fuzz_iters = 0;
struct FuzzData
{
void *data;
UINT32 len;
} fuzz_data;
struct memoryInput
{
ADDRINT addr;
#if defined(__i386__) || defined(_WIN32)
UINT32 val;
#elif defined(__x86_64__) || defined(_WIN64)
UINT64 val;
#endif
};
list<struct memoryInput> memInput;
FILE * f;
KNOB<BOOL> Knob_debug(KNOB_MODE_WRITEONCE, "pintool", "debug", "0", "Enable debug mode");
KNOB<ADDRINT> Knob_entry(KNOB_MODE_WRITEONCE, "pintool", "entry", "0", "start address for coverage signal");
KNOB<ADDRINT> Knob_exit(KNOB_MODE_WRITEONCE, "pintool", "exit", "0", "stop address for coverage signal");
KNOB<string> Knob_module(KNOB_MODE_WRITEONCE, "pintool", "module", "", "fuzz just this module");
/*
void randomizeREG(CONTEXT * ctx, ADDRINT nextAddr)
{
PIN_SetContextReg(ctx, REG_EDX, fuzz_iters);
}
*/
void FUZZ(CONTEXT *ctx)
{
unsigned int i;
if(Knob_debug)
printf("[*] waiting of fuzz data\n");
windows::get_fuzz_data(); /* WAIT */
ADDRINT data_pointer = PIN_GetContextReg(ctx, REG_GCX);
/* save virgin data values */
//printf("saving: ");
for(i = previous_fuzz_data_len; i < fuzz_data.len; i++)
{
original_fuzzed_data[i] = ((unsigned char *)data_pointer)[i];
//printf("%x", original_fuzzed_data[i]);
}
//printf("\n");
/* insert fuzz data values */
//printf("fuzz: ");
for(i = 0; i < fuzz_data.len; i++)
{
((unsigned char *)data_pointer)[i] = ((char *)fuzz_data.data)[i];
//printf("%x", ((unsigned char *)data_pointer)[i]);
}
//printf("\n");
/* restore rewritten data values after fuzz data */
//printf("restore: ");
for(i = fuzz_data.len; i < previous_fuzz_data_len; i++)
{
((unsigned char *)data_pointer)[i] = original_fuzzed_data[i];
//printf("%x", ((unsigned char *)data_pointer)[i]);
}
//printf("\n");
previous_fuzz_data_len = fuzz_data.len;
}
void restore_memory(void)
{
list<struct memoryInput>::iterator i;
for(i = memInput.begin(); i != memInput.end(); ++i)
{
*(reinterpret_cast<ADDRINT*>(i->addr)) = i->val;
if (Knob_debug)
printf("[*] restore " HEX_FMT " <- " HEX_FMT "\n", i->addr, i->val);
}
memInput.clear();
}
void write_mem(ADDRINT addr, ADDRINT memop)
{
struct memoryInput elem;
if(! in_fuzz_area)
return;
elem.addr = memop;
elem.val = *(reinterpret_cast<ADDRINT*>(memop));
memInput.push_back(elem);
if (Knob_debug)
printf("[*] memory write " HEX_FMT ": " HEX_FMT "\n", elem.addr, elem.val);
}
inline ADDRINT valid_addr(ADDRINT addr)
{
if ( addr >= min_addr && addr <= max_addr )
return true;
return false;
}
void exec_instr(ADDRINT addr, CONTEXT * ctx)
{
//if( addr >= 0x401000 && addr <= 0x401024 )
//printf(HEX_FMT "\n", addr - min_addr);
char command;
if(was_crash)
{
was_crash = false;
in_fuzz_area = FALSE;
PIN_SaveContext(&snapshot, ctx);
restore_memory();
PIN_ExecuteAt(ctx);
}
if(addr - min_addr == entry_addr && in_fuzz_area == FALSE)
{
in_fuzz_area = TRUE;
PIN_SaveContext(ctx, &snapshot);
is_saved_snapshot = TRUE;
if (Knob_debug)
printf("[+] fuzz iteration " INT_FMT " started\n", ++fuzz_iters);
FUZZ(ctx); /* WAIT */
PIN_ExecuteAt(ctx);
}
else if(addr - min_addr == exit_addr && in_fuzz_area == TRUE)
{
in_fuzz_area = FALSE;
if (Knob_debug)
printf("[*] fuzz iteration " INT_FMT " finished\n", fuzz_iters);
windows::write_to_pipe("K");
if(is_saved_snapshot)
PIN_SaveContext(&snapshot, ctx);
is_saved_snapshot = FALSE;
restore_memory();
PIN_ExecuteAt(ctx);
}
}
VOID track_branch(ADDRINT cur_addr)
{
ADDRINT cur_id = cur_addr - min_addr;
if (Knob_debug) {
printf( "[+] branch: " HEX_FMT ", rel_addr: 0x%08x, index: 0x%04x\n",
cur_addr, (UINT32)(cur_addr - min_addr), (UINT16)((cur_id ^ last_id) % MAP_SIZE) );
}
if(in_fuzz_area)
{
if (bitmap_shm != 0){
bitmap_shm[((cur_id ^ last_id) % MAP_SIZE)]++;
}
else {
bitmap[((cur_id ^ last_id) % MAP_SIZE)]++;
}
}
last_id = cur_id;
/*
if(entry_addr && entry_addr == cur_id)
{
if(Knob_debug)
std::cout << "entry" << std::endl;
coverage_enable = TRUE;
}
else if(exit_addr && exit_addr == cur_id)
{
if(Knob_debug)
std::cout << "exit" << std::endl;
coverage_enable = FALSE;
}
*/
}
void ins_instrument(INS ins, VOID *v)
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)exec_instr,
IARG_ADDRINT, INS_Address(ins),
IARG_CONTEXT,
IARG_END);
if(INS_MemoryOperandIsWritten(ins, 0))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)write_mem,
IARG_ADDRINT, INS_Address(ins),
IARG_MEMORYOP_EA, 0,
IARG_END);
}
}
VOID trace_intrument(TRACE trace, VOID *v)
{
for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl))
{
for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins))
{
// make sure it is in a segment we want to instrument!
if (valid_addr(INS_Address(ins)))
{
if (INS_IsBranch(ins)) {
// As per afl-as.c we only care about conditional branches (so no JMP instructions)
if (INS_HasFallThrough(ins) || INS_IsCall(ins))
{
/*if (Knob_debug) {
std::cout << "BRACH: 0x" << std::hex << INS_Address(ins) << ":\t" << INS_Disassemble(ins) << std::endl;
}*/
// Instrument the code.
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)track_branch,
IARG_INST_PTR,
IARG_END);
}
}
}
}
}
}
namespace windows {
void write_to_pipe(char *cmd)
{
DWORD num_written;
//Sleep(1000);
if(!has_pipe_sync_connected)
{
ConnectNamedPipe(pipe_sync, NULL); /* WAIT */
has_pipe_sync_connected = TRUE;
}
WriteFile(pipe_sync, cmd, 1, &num_written, NULL);
}
char read_from_pipe()
{
DWORD num_read;
char result;
ReadFile(pipe_sync, &result, 1, &num_read, NULL);
return result;
}
void get_fuzz_data()
{
if(!has_pipe_data_connected)
{
ConnectNamedPipe(pipe_data, NULL); /* WAIT */
has_pipe_data_connected = TRUE;
}
if( ReadFile(pipe_data, fuzz_data.data, FUZZ_DATA_SIZE, (LPDWORD)&fuzz_data.len, &pipe_overlapped) || GetLastError() == ERROR_IO_PENDING )
WaitForSingleObject(pipe_overlapped.hEvent, INFINITE);
if(Knob_debug)
{
printf("[*] fuzz data %d bytes\n", fuzz_data.len);
printf("[*] fuzz data: %s\n", fuzz_data.data);
}
}
void setup_pipe()
{
/* create new pipe */
pipe_sync = CreateNamedPipe(
"\\\\.\\pipe\\afl_sync", // pipe name
PIPE_ACCESS_DUPLEX , // read/write access
// FILE_FLAG_OVERLAPPED, // overlapped mode
0,
1, // max. instances
512, // output buffer size
512, // input buffer size
20000, // client time-out
NULL); // default security attribute
/* create new pipe */
pipe_data = CreateNamedPipe(
"\\\\.\\pipe\\afl_data", // pipe name
PIPE_ACCESS_DUPLEX | // read/write access
FILE_FLAG_OVERLAPPED, // overlapped mode
0,
1, // max. instances
512, // output buffer size
512, // input buffer size
20000, // client time-out
NULL);
memset(&pipe_overlapped, 0, sizeof(pipe_overlapped));
pipe_overlapped.hEvent = CreateEvent(
NULL, // default security attribute
TRUE, // manual-reset event
TRUE, // initial state = signaled
NULL); // unnamed event object
}
void setup_shm()
{
HANDLE map_file;
/* create new shared memory */
map_file = CreateFileMapping(
INVALID_HANDLE_VALUE, // use paging file
NULL, // default security
PAGE_READWRITE, // read/write access
0, // maximum object size (high-order DWORD)
MAP_SIZE, // maximum object size (low-order DWORD)
(char *)"afl_shm_default"); // name of mapping object
bitmap_shm = (unsigned char *) MapViewOfFile(map_file, // handle to map object
FILE_MAP_ALL_ACCESS, // read/write permission
0,
0,
MAP_SIZE);
memset(bitmap_shm, '\x00', MAP_SIZE);
}
}
void dump_registers(CONTEXT *ctx)
{
ADDRINT rax = PIN_GetContextReg(ctx, REG_GAX);
ADDRINT rcx = PIN_GetContextReg(ctx, REG_GCX);
ADDRINT rdx = PIN_GetContextReg(ctx, REG_GDX);
ADDRINT rbx = PIN_GetContextReg(ctx, REG_GBX);
ADDRINT rsp = PIN_GetContextReg(ctx, REG_STACK_PTR);
ADDRINT rbp = PIN_GetContextReg(ctx, REG_GBP);
ADDRINT rsi = PIN_GetContextReg(ctx, REG_GSI);
ADDRINT rdi = PIN_GetContextReg(ctx, REG_GDI);
ADDRINT rip = PIN_GetContextReg(ctx, REG_IP);
printf("RAX: " HEX_FMT "\n"
"RCX: " HEX_FMT "\n"
"RDX: " HEX_FMT "\n"
"RBX: " HEX_FMT "\n"
"RSP: " HEX_FMT "\n"
"RBP: " HEX_FMT "\n"
"RSI: " HEX_FMT "\n"
"RDI: " HEX_FMT "\n"
"RIP: " HEX_FMT "\n"
, rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, rip);
}
void context_change(THREADID tid, CONTEXT_CHANGE_REASON reason, const CONTEXT *ctxtFrom, CONTEXT *ctxtTo, INT32 info, VOID *v)
{
if(reason == CONTEXT_CHANGE_REASON_EXCEPTION)
{
if (Knob_debug)
{
printf("[!] exception " HEX_FMT "\n", info);
dump_registers(ctxtTo);
}
if(info == 0xc0000005)
{
windows::write_to_pipe("C");
was_crash = true;
}
}
}
EXCEPT_HANDLING_RESULT internal_exception(THREADID tid, EXCEPTION_INFO *pExceptInfo, PHYSICAL_CONTEXT *pPhysCtxt, VOID *v)
{
if (Knob_debug)
printf( "[!] internal_exception in " HEX_FMT "\n", PIN_GetPhysicalContextReg(pPhysCtxt, REG_INST_PTR) );
return EHR_HANDLED;
}
VOID entry_point(VOID *ptr)
{
/* Much like the original instrumentation from AFL we only want to instrument the segments of code
* from the actual application and not the link and PIN setup itself.
*
* Inspired by: http://joxeankoret.com/blog/2012/11/04/a-simple-pin-tool-unpacker-for-the-linux-version-of-skype/
*/
IMG img;
SEC sec;
for(img = APP_ImgHead(); IMG_Valid(img); img = IMG_Next(img))
{
if( need_module != "" && strcasestr( IMG_Name(img).c_str(), need_module.c_str() ) == 0 )
continue;
if(Knob_debug)
printf("[*] module %s %lx " HEX_FMT "\n", IMG_Name(img).c_str(), IMG_LowAddress(img), IMG_HighAddress(img));
for(sec= IMG_SecHead(img); SEC_Valid(sec); sec = SEC_Next(sec))
{
if ( SEC_IsExecutable(sec) /*&& SEC_Name(sec) == ".text"*/)
{
ADDRINT sec_addr = SEC_Address(sec);
UINT32 sec_size = SEC_Size(sec);
if(Knob_debug)
printf("[*] section: %s, addr: " HEX_FMT ", size: " INT_FMT "\n", SEC_Name(sec).c_str(), sec_addr, sec_size);
if(sec_addr != 0)
{
ADDRINT high_addr = sec_addr + sec_size;
if(sec_addr > min_addr || min_addr == 0)
min_addr = sec_addr;
if(sec_addr > max_addr || max_addr == 0)
max_addr = sec_addr;
if(high_addr > max_addr)
max_addr = high_addr;
min_addr >>= 12;
min_addr <<= 12;
max_addr |= 0xfff;
}
}
}
}
if(Knob_debug)
{
printf("[+] min_addr: " HEX_FMT "\n", min_addr);
printf("[+] max_addr: " HEX_FMT "\n", max_addr);
printf("[+] entry_addr: " HEX_FMT "\n", min_addr + entry_addr);
printf("[+] exit_addr: " HEX_FMT "\n", min_addr + exit_addr);
}
}
void fini(INT32 code, VOID *v)
{
if (Knob_debug)
printf("[*] end\n");
windows::DisconnectNamedPipe(windows::pipe_sync);
windows::DisconnectNamedPipe(windows::pipe_data);
windows::CloseHandle(windows::pipe_sync);
windows::CloseHandle(windows::pipe_data);
//fflush(f);
//fclose(f);
}
INT32 Usage()
{
std::cerr << "in-memory fuzzer -- A pin tool to enable blackbox binaries to be fuzzed with AFL on Linux/Windows" << std::endl;
std::cerr << " -debug -- prints extra debug information" << std::endl;
std::cerr << " -module module.exe -- module for coverage" << std::endl;
std::cerr << " -entry 0xADDR -- start address for coverage" << std::endl;
std::cerr << " -exit 0xADDR -- stop address for coverage" << std::endl;
return -1;
}
int main(int argc, char ** argv)
{
//f = fopen("fuzz.log", "w");
if(PIN_Init(argc, argv))
return Usage();
fuzz_data.data = malloc(FUZZ_DATA_SIZE);
windows::setup_pipe();
windows::setup_shm();
entry_addr = Knob_entry.Value();
exit_addr = Knob_exit.Value();
need_module = Knob_module.Value();
INS_AddInstrumentFunction(ins_instrument, 0);
TRACE_AddInstrumentFunction(trace_intrument, 0);
PIN_AddContextChangeFunction(context_change, 0);
//PIN_AddInternalExceptionHandler(internal_exception, 0);
PIN_AddApplicationStartFunction(entry_point, 0);
PIN_AddFiniFunction(fini, 0);
PIN_StartProgram();
return 0;
}
/*
this module speed: ~20k/s
*/