-
Notifications
You must be signed in to change notification settings - Fork 23
/
e9AFLPlugin.cpp
705 lines (653 loc) · 20.4 KB
/
e9AFLPlugin.cpp
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
/*
* ___ _ _____ _
* ___ / _ \ / \ | ___| |
* / _ \ (_) |/ _ \ | |_ | |
* | __/\__, / ___ \| _| | |___
* \___| /_/_/ \_\_| |_____|
*
* Copyright (C) 2022 National University of Singapore
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <initializer_list>
#include <map>
#include <sstream>
#include <string>
#include <set>
#include <vector>
#include <getopt.h>
#include "e9plugin.h"
using namespace e9tool;
#define AREA_BASE 0x2A0000
#define AREA_SIZE ((size_t)1 << 16)
/*
* Options.
*/
enum Option
{
OPTION_NEVER,
OPTION_DEFAULT,
OPTION_ALWAYS
};
static Option option_debug = OPTION_DEFAULT;
static Option option_Oselect = OPTION_DEFAULT;
static Option option_Oblock = OPTION_DEFAULT;
enum Counter
{
COUNTER_CLASSIC,
COUNTER_NEVER_ZERO,
COUNTER_SATURATED
};
static Option parseOption(const char *str)
{
if (strcmp(str, "never") == 0)
return OPTION_NEVER;
if (strcmp(str, "default") == 0)
return OPTION_DEFAULT;
if (strcmp(str, "always") == 0)
return OPTION_ALWAYS;
error("bad option value \"%s\"; expected one of {\"never\", \"default\", "
"\"always\"}", str);
}
static Counter parseCounter(const char *str)
{
if (strcmp(str, "classic") == 0)
return COUNTER_CLASSIC;
if (strcmp(str, "neverzero") == 0)
return COUNTER_NEVER_ZERO;
if (strcmp(str, "saturated") == 0)
return COUNTER_SATURATED;
error("bad counter value \"%s\"; expected one of {\"classic\", \"neverzero\", "
"\"saturated\"}", str);
}
/*
* CFG
*/
struct BasicBlock
{
std::vector<intptr_t> preds; // Predecessor BBs
std::vector<intptr_t> succs; // Successor BBs
intptr_t instrument = -1; // Instrumentation point
int id = -1; // ID
bool optimized = false; // Optimize block?
bool bad = false; // Bad block?
};
typedef std::map<intptr_t, BasicBlock> CFG;
#define BB_INDIRECT (-1)
/*
* Paths
*/
typedef std::map<BasicBlock *, BasicBlock *> Paths;
/*
* To compile:
* $ g++ -std=c++11 -fPIC -shared -o e9afl.so -O2 e9afl.cpp \
* -I .
*/
/*
* All instrumentation points.
*/
static std::set<intptr_t> instrument;
/*
* Options.
*/
enum
{
OPTION_COUNTER,
OPTION_OBLOCK,
OPTION_OSELECT,
OPTION_DEBUG,
OPTION_PATH,
};
/*
* Initialization.
*/
extern void *e9_plugin_init(const Context *cxt)
{
static const struct option long_options[] =
{
{"counter", required_argument, nullptr, OPTION_COUNTER},
{"Oblock", required_argument, nullptr, OPTION_OBLOCK},
{"Oselect", required_argument, nullptr, OPTION_OSELECT},
{"debug", no_argument, nullptr, OPTION_DEBUG},
{"path", required_argument, nullptr, OPTION_PATH},
{nullptr, no_argument, nullptr, 0}
};
std::string option_path(".");
Counter option_counter = COUNTER_CLASSIC;
optind = 1;
char * const *argv = cxt->argv->data();
int argc = (int)cxt->argv->size();
while (true)
{
int idx;
int opt = getopt_long_only(argc, argv, "Po:v", long_options, &idx);
if (opt < 0)
break;
switch (opt)
{
case OPTION_COUNTER:
option_counter = parseCounter(optarg);
break;
case OPTION_OBLOCK:
option_Oblock = parseOption(optarg);
break;
case OPTION_OSELECT:
option_Oselect = parseOption(optarg);
break;
case OPTION_DEBUG:
option_debug = OPTION_ALWAYS;
break;
case OPTION_PATH:
option_path = optarg;
break;
default:
error("invalid command-line options for %s", argv[0]);
}
}
if (option_Oblock == OPTION_ALWAYS)
warning("always removing AFL instrumentation for bad blocks; coverage "
"may be incomplete");
// Make seed depend on filename.
unsigned seed = 0;
const char *filename = getELFFilename(cxt->elf);
for (int i = 0; filename[i] != '\0'; i++)
seed = 101 * seed + (unsigned)filename[i];
srand(seed);
const int32_t stack_adjust = 0x4000;
const int32_t afl_rt_ptr = 0x50000000;
const int32_t afl_area_ptr = AREA_BASE;
// Reserve memory used by the afl_area_ptr:
sendReserveMessage(cxt->out, afl_area_ptr, AREA_SIZE, /*absolute=*/true);
// Send the AFL runtime (if not shared object):
std::string path(option_path);
path += "/afl-rt";
const ELF *rt = parseELF(path.c_str(), afl_rt_ptr);
sendELFFileMessage(cxt->out, rt);
// Send the AFL instrumentation:
//
// Save state:
//
// lea -0x4000(%rsp),%rsp
// push %rax
// seto %al
// lahf
// push %rax
//
std::stringstream code;
code << 0x48 << ',' << 0x8d << ',' << 0xa4 << ',' << 0x24 << ','
<< "{\"int32\":" << -stack_adjust << "},";
code << 0x50 << ',';
code << 0x0f << ',' << 0x90 << ',' << 0xc0 << ',';
code << 0x9f << ',';
code << 0x50 << ',';
// AFL instrumentation:
//
// mov %fs:0x4c,%eax // mov prev_loc,%eax
// xor $curr_loc,%eax
// ... // Increment hitcount
// movl $(curr_loc>>1),%fs:0x4c // mov (curr_loc>>1),prev_loc
//
const unsigned TLS = 0x4c; // tcbhead_t.__glibc_unused1
code << 0x64 << ',' << 0x8b << ',' << 0x04 << ',' << 0x25 << ','
<< TLS << ',' << 0x00 << ',' << 0x00 << ',' << 0x00 << ',';
code << 0x35 << ',' << "\"$curr_loc\"" << ',';
switch (option_counter)
{
default:
case COUNTER_CLASSIC:
// incb afl_area_ptr(%eax)
code << 0x67 << ',' << 0xfe << ',' << 0x80 << ','
<< "{\"int32\":" << afl_area_ptr << "},";
break;
case COUNTER_NEVER_ZERO:
// addb $0x1,afl_area_ptr(%eax)
// adcb $0x0,afl_area_ptr(%eax)
code << 0x67 << ',' << 0x80 << ',' << 0x80 << ','
<< "{\"int32\":" << afl_area_ptr << "}," << 0x01 << ',';
code << 0x67 << ',' << 0x80 << ',' << 0x90 << ','
<< "{\"int32\":" << afl_area_ptr << "}," << 0x00 << ',';
break;
case COUNTER_SATURATED:
// addb $0x1,afl_area_ptr(%eax)
// sbbb $0x0,afl_area_ptr(%eax)
code << 0x67 << ',' << 0x80 << ',' << 0x80 << ','
<< "{\"int32\":" << afl_area_ptr << "}," << 0x01 << ',';
code << 0x67 << ',' << 0x80 << ',' << 0x98 << ','
<< "{\"int32\":" << afl_area_ptr << "}," << 0x00 << ',';
break;
}
code << 0x64 << ',' << 0xc7 << ',' << 0x04 << ',' << 0x25 << ','
<< TLS << ',' << 0x00 << ',' << 0x00 << ',' << 0x00 << ','
<< "\"$curr_loc_1\"" << ',';
// Restore state:
//
// pop %rax
// add $0x7f,%al
// sahf
// pop %rax
// lea 0x4000(%rsp),%rsp
//
code << 0x58 << ',';
code << 0x04 << ',' << 0x7f << ',';
code << 0x9e << ',';
code << 0x58 << ',';
code << 0x48 << ',' << 0x8d << ',' << 0xa4 << ',' << 0x24 << ','
<< "{\"int32\":" << stack_adjust << "}";
sendTrampolineMessage(cxt->out, "$afl", code.str().c_str());
return nullptr;
}
/*
* Normalize a block address.
*/
static intptr_t normalize(intptr_t addr, const Targets &targets)
{
if (addr == BB_INDIRECT)
return BB_INDIRECT;
auto i = targets.lower_bound(addr);
if (i == targets.end())
return BB_INDIRECT;
return i->first;
}
/*
* Add a predecessor block.
*/
static void addPredecessor(intptr_t pred, intptr_t succ,
const Targets &targets, CFG &cfg)
{
pred = normalize(pred, targets);
succ = normalize(succ, targets);
auto j = cfg.find(succ);
if (j == cfg.end())
{
BasicBlock empty;
auto r = cfg.insert({succ, empty});
j = r.first;
}
j->second.preds.push_back(pred);
}
/*
* Add a successor block.
*/
static void addSuccessor(intptr_t pred, intptr_t succ,
const Targets &targets, CFG &cfg)
{
pred = normalize(pred, targets);
succ = normalize(succ, targets);
auto j = cfg.find(pred);
if (j == cfg.end())
{
BasicBlock empty;
auto r = cfg.insert({pred, empty});
j = r.first;
}
j->second.succs.push_back(succ);
}
/*
* Build the CFG from the set of jump targets.
*/
static void buildCFG(const ELF *elf, const Instr *Is, size_t size,
const Targets &targets, CFG &cfg)
{
for (const auto &entry: targets)
{
intptr_t target = entry.first, bb = target;
TargetKind kind = entry.second;
size_t i = findInstr(Is, size, target);
if (i >= size)
continue;
BasicBlock empty;
(void)cfg.insert({bb, empty});
if ((kind & TARGET_INDIRECT) != 0)
addPredecessor(BB_INDIRECT, bb, targets, cfg);
const Instr *I = Is + i;
for (++i; i < size; i++)
{
InstrInfo info0, *info = &info0;
getInstrInfo(elf, I, info);
bool end = false;
intptr_t target = -1, next = -1;
switch (info->mnemonic)
{
case MNEMONIC_RET:
end = true;
break;
case MNEMONIC_JMP:
end = true;
// Fallthrough:
case MNEMONIC_CALL:
if (info->op[0].type == OPTYPE_IMM)
target = (intptr_t)info->address +
(intptr_t)info->size + (intptr_t)info->op[0].imm;
break;
case MNEMONIC_JO: case MNEMONIC_JNO: case MNEMONIC_JB:
case MNEMONIC_JAE: case MNEMONIC_JE: case MNEMONIC_JNE:
case MNEMONIC_JBE: case MNEMONIC_JA: case MNEMONIC_JS:
case MNEMONIC_JNS: case MNEMONIC_JP: case MNEMONIC_JNP:
case MNEMONIC_JL: case MNEMONIC_JGE: case MNEMONIC_JLE:
case MNEMONIC_JG:
end = true;
next = (intptr_t)info->address + (intptr_t)info->size;
target = next + (intptr_t)info->op[0].imm;
break;
default:
break;
}
if (target > 0x0)
addPredecessor(bb, target, targets, cfg);
if (next > 0x0)
addPredecessor(bb, next, targets, cfg);
if (end)
{
if (target > 0)
addSuccessor(bb, target, targets, cfg);
if (next > 0)
addSuccessor(bb, next, targets, cfg);
if (!(target > 0 || next > 0))
addSuccessor(bb, BB_INDIRECT, targets, cfg);
break;
}
const Instr *J = I+1;
if (I->address + I->size != J->address)
break;
if (targets.find(J->address) != targets.end())
{
// Fallthrough:
addPredecessor(bb, J->address, targets, cfg);
addSuccessor(bb, J->address, targets, cfg);
break;
}
I = J;
}
}
int id = 0;
for (auto &entry: cfg)
entry.second.id = id++;
}
/*
* Attempt to optimize away a bad block.
*/
static void optimizeBlock(CFG &cfg, BasicBlock &bb);
static void optimizePaths(CFG &cfg, BasicBlock *pred_bb, BasicBlock *succ_bb,
Paths &paths)
{
auto i = paths.find(succ_bb);
if (i != paths.end())
{
// Multiple paths to succ_bb;
BasicBlock *unopt_bb = nullptr;
if (pred_bb != nullptr)
unopt_bb = pred_bb;
else if (i->second != nullptr)
unopt_bb = i->second;
// Note: (unopt_bb == nullptr) can happen in degenerate cases, e.g.:
// jne .Lnext; .Lnext: ...
if (unopt_bb != nullptr)
{
unopt_bb->optimized = false;
optimizeBlock(cfg, *unopt_bb);
}
return;
}
paths.insert({succ_bb, pred_bb});
if (succ_bb == nullptr || !succ_bb->optimized)
return;
pred_bb = succ_bb;
for (auto succ: succ_bb->succs)
{
auto i = cfg.find(succ);
succ_bb = (i == cfg.end()? nullptr: &i->second);
optimizePaths(cfg, pred_bb, succ_bb, paths);
}
}
static void optimizeBlock(CFG &cfg, BasicBlock &bb)
{
if (bb.optimized)
return;
Paths paths;
for (auto succ: bb.succs)
{
auto i = cfg.find(succ);
BasicBlock *succ_bb = (i == cfg.end()? nullptr: &i->second);
optimizePaths(cfg, nullptr, succ_bb, paths);
}
}
/*
* Verify the optimization is correct (for debugging).
*/
static void verify(CFG &cfg, intptr_t curr, BasicBlock *bb,
std::set<BasicBlock *> &seen)
{
for (auto succ: bb->succs)
{
auto i = cfg.find(succ);
BasicBlock *succ_bb = (i == cfg.end()? nullptr: &i->second);
if (succ_bb == nullptr)
fprintf(stderr, " BB_%d->indirect", bb->id);
else
fprintf(stderr, " BB_%d->BB_%d", bb->id,
cfg.find(succ)->second.id);
auto r = seen.insert(succ_bb);
if (!r.second)
{
putc('\n', stderr);
error("multiple non-instrumented paths detected");
}
if (succ_bb != nullptr && succ_bb->optimized)
verify(cfg, succ, succ_bb, seen);
}
}
static void verify(CFG &cfg)
{
if (option_Oblock == OPTION_ALWAYS)
return;
putc('\n', stderr);
for (auto &entry: cfg)
{
BasicBlock *bb = &entry.second;
if (bb->optimized)
continue;
fprintf(stderr, "\33[32mVERIFY\33[0m BB_%d:",
cfg.find(entry.first)->second.id);
std::set<BasicBlock *> seen;
verify(cfg, entry.first, bb, seen);
putc('\n', stderr);
}
putc('\n', stderr);
}
/*
* Calculate all instrumentation points.
*/
static void calcInstrumentPoints(const ELF *elf, const Instr *Is, size_t size,
Targets &targets, std::set<intptr_t> &instrument)
{
// Step #1: build the CFG:
CFG cfg;
buildCFG(elf, Is, size, targets, cfg);
// Step #2: find all instrumentation-points/bad-blocks
for (const auto &entry: targets)
{
intptr_t target = entry.first, bb = target;
TargetKind kind = entry.second;
size_t i = findInstr(Is, size, target);
if (i >= size)
continue;
const Instr *I = Is + i;
uint8_t target_size = I->size;
for (++i; option_Oselect != OPTION_NEVER && i < size &&
target_size < /*sizeof(jmpq)=*/5; i++)
{
InstrInfo info0, *info = &info0;
getInstrInfo(elf, I, info);
bool end = false;
switch (info->mnemonic)
{
case MNEMONIC_RET:
case MNEMONIC_CALL:
case MNEMONIC_JMP:
case MNEMONIC_JO: case MNEMONIC_JNO: case MNEMONIC_JB:
case MNEMONIC_JAE: case MNEMONIC_JE: case MNEMONIC_JNE:
case MNEMONIC_JBE: case MNEMONIC_JA: case MNEMONIC_JS:
case MNEMONIC_JNS: case MNEMONIC_JP: case MNEMONIC_JNP:
case MNEMONIC_JL: case MNEMONIC_JGE: case MNEMONIC_JLE:
case MNEMONIC_JG:
end = true;
break;
default:
break;
}
if (end)
break;
const Instr *J = I+1;
if (I->address + I->size != J->address)
break;
if (targets.find(J->address) != targets.end())
break;
if (J->size > target_size)
{
target = J->address;
target_size = J->size;
}
I = J;
}
auto j = cfg.find(bb);
assert(j != cfg.end());
j->second.instrument = target;
j->second.bad = (target_size < /*sizeof(jmpq)=*/5);
switch (option_Oblock)
{
case OPTION_NEVER:
j->second.optimized = false;
break;
case OPTION_DEFAULT:
// To be refined in Step #3
j->second.optimized =
(j->second.bad && (kind & TARGET_INDIRECT) == 0);
break;
case OPTION_ALWAYS:
j->second.optimized = j->second.bad;
break;
}
}
// Step #3: Optimize away bad blocks:
if (option_Oblock == OPTION_DEFAULT)
for (auto &entry: cfg)
optimizeBlock(cfg, entry.second);
// Step #4: Collect final instrumentation points.
for (auto &entry: cfg)
{
if (!entry.second.optimized)
instrument.insert(entry.second.instrument);
}
// Setp #5: Print debugging information (if necessary)
for (size_t i = 0; (option_debug == OPTION_ALWAYS) && i < size; i++)
{
InstrInfo I0, *I = &I0;
getInstrInfo(elf, Is + i, I);
auto j = cfg.find(I->address);
if (j != cfg.end())
{
fprintf(stderr, "\n# \33[32mBB_%d\33[0m%s%s\n", cfg[I->address].id,
(j->second.bad? " [\33[31mBAD\33[0m]": ""),
(j->second.bad && !j->second.optimized?
" [\33[31mUNOPTIMIZED\33[0m]": ""));
fprintf(stderr, "# preds = ");
int count = 0;
for (auto pred: j->second.preds)
{
if (count++ != 0)
putc(',', stderr);
if (pred == BB_INDIRECT)
{
fprintf(stderr, "indirect");
continue;
}
auto l = cfg.find(pred);
if (l != cfg.end())
fprintf(stderr, "BB_%u", l->second.id);
else
fprintf(stderr, "%p", (void *)pred);
}
fprintf(stderr, "\n# succs = ");
count = 0;
for (auto succ: j->second.succs)
{
if (count++ != 0)
putc(',', stderr);
if (succ == BB_INDIRECT)
{
fprintf(stderr, "indirect");
continue;
}
auto l = cfg.find(succ);
if (l != cfg.end())
fprintf(stderr, "BB_%u", l->second.id);
else
fprintf(stderr, "%p", (void *)succ);
}
putc('\n', stderr);
}
if (instrument.find(I->address) != instrument.end())
fprintf(stderr, "%lx: \33[33m%s\33[0m\n", I->address,
I->string.instr);
else
fprintf(stderr, "%lx: %s\n", I->address, I->string.instr);
}
if (option_debug == OPTION_ALWAYS)
verify(cfg);
}
/*
* Events.
*/
extern void e9_plugin_event(const Context *cxt, Event event)
{
switch (event)
{
case EVENT_DISASSEMBLY_COMPLETE:
{
Targets targets;
buildTargets(cxt->elf, cxt->Is->data(), cxt->Is->size(), targets);
calcInstrumentPoints(cxt->elf, cxt->Is->data(), cxt->Is->size(),
targets, instrument);
break;
}
default:
break;
}
}
/*
* Matching. Return `true' iff we should instrument this instruction.
*/
extern intptr_t e9_plugin_match(const Context *cxt)
{
return (instrument.find(cxt->I->address) != instrument.end());
}
/*
* Patch template.
*/
extern void e9_plugin_code(const Context *cxt)
{
fputs("\"$afl\",", cxt->out);
}
/*
* Patching.
*/
extern void e9_plugin_patch(const Context *cxt)
{
if (instrument.find(cxt->I->address) == instrument.end())
return;
int32_t curr_loc = rand() & 0xFFFF;
fprintf(cxt->out, "\"$curr_loc\":{\"int32\":%d},", curr_loc);
fprintf(cxt->out, "\"$curr_loc_1\":{\"int32\":%d},", curr_loc >> 1);
}