-
Notifications
You must be signed in to change notification settings - Fork 2
/
bunny-main.c
2144 lines (1565 loc) · 63.6 KB
/
bunny-main.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
/*
bunny - main executable
-----------------------
Orchestrates a fuzzing effort with the aid of bunny-exec and bunny-flow.
Author: Michal Zalewski <[email protected]>
Copyright 2007 Google Inc.
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.
*/
/* set default to resume interrupted primitives, avoiding EINTR,
cf. GNU LIBC manual 24.5 "Primitives Interrupted by Signals" */
#define _GNU_SOURCE
#define __USE_LARGEFILE64
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#ifndef __FreeBSD__
# include <getopt.h>
#endif /* !__FreeBSD__ */
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <ctype.h>
#include <time.h>
#include <sys/time.h>
#include <openssl/md5.h>
#include <signal.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sched.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <dirent.h>
#include <sys/stat.h>
#include <openssl/md5.h>
#include <math.h>
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif /* !O_LARGEFILE */
#include "types.h"
#include "config.h"
#include "debug.h"
#include "nlist.h"
#include "message.h"
#include "range.h"
#include "util.h"
#define R(x) (random() % (x))
#define R32() ((random() << 16) ^ random())
static FILE* outfile;
#define outf(x...) do { \
printf(x); \
/* Static parameters only, x is inlined twice, but it's so much simpler. */ \
if (outfile) fprintf(outfile,x); \
} while (0)
#undef debug
#define debug outf
static _u8 *in_dir, /* Input directory name */
*out_dir, /* Output directory name */
*write_file, /* Data output file, if any */
*inflow_dir, /* Input flow directory */
*outflow_dir; /* Output flow directory */
static _s32 flow_pid = -1, /* bunny-flow process ID */
exec_pid = -1, /* bunny-exec process ID */
flow_pipe_cmd = -1, /* bunny-flow command fd */
flow_pipe_ret = -1, /* bunny-flow response fd */
exec_pipe_ret = -1; /* bunny-exec response fd */
static _u32 write_host, /* Data output host, if any */
write_port, /* Data output port, if any */
use_udp, /* Protocol to use */
stall_limit = 2000, /* Stalled process timeout */
time_limit = 5000, /* General process timeout */
assure_crash = 0, /* Number crash confirmations */
bitflip_inc = 1, /* Bitflip stepover */
bitflip_max = 8, /* Max bitflip width */
chunk_inc = 1, /* Chunk modifier stepover */
chunk_max = 8, /* Max chunk size */
chunk_off_max = 8, /* Max chunk offset */
eff_count_max = 10, /* Max effector bytes per param */
rand_val_walks = 8, /* Random value walks per cycle */
rand_phase_cycles = 4096, /* Random fuzz cycles */
rand_phase_stacking = 8, /* Random operations per cycle */
cycle_branch_limit = 32, /* Max new branches per cycle */
cycle_value_limit = 16, /* Max new param values per cycle */
cal_cycles = 2, /* Calibration cycle count */
func_limit = 200, /* Max number of function calls */
cur_cycle, /* Current fuzzing cycle */
epath_cnt, /* call path count */
ppath_cnt, /* Patam path count */
epath_ign, /* Ignored path count */
ppath_ign, /* Ignored path count */
fuzz_ign, /* Fuzz step ignore count */
crash_cnt, /* Crash condition count */
effect_cnt, /* Effector count */
usleeps_done, /* usleep(1.1M) count */
queue_real, /* Filled queue entries */
size_limit, /* Fuzzable input size limit */
total_queue, /* Total queue entry count */
rand_seed; /* Random seed in use */
static _u8 use_builtin_vals = 1, /* Rely on builtin Val tables? */
use_all8, /* Use all 8-bit values? */
keep_fault, /* Do not abandon timeouted paths */
allow_dummy, /* Permit dummy mode? */
full_range, /* Use fine-grained ranging. */
zero_range, /* Do not use ranging at all! */
skip_rounds, /* Skip deterministic fuzzing */
use_qrand, /* Randomize queue processing */
use_beep; /* Beep on crash? */
struct timeval st, en;
static struct naive_list_int byte_val_list, /* User defined value tables */
word_val_list, /* (for various value widths) */
dword_val_list;
static _u64 exec_cnt, /* Exec counter */
input_cnt; /* Input generator counter */
static _u8** program_args; /* Arguments for the executed app */
struct bunny_traceitem { /* Trace session descriptor */
_u32 exit_status; /* Exit status (EXITF_*) */
_u32 fuzzable, /* Fuzzable byte count */
thread_count; /* Number of traced processes */
_u64 exec_cksum, /* All-process execution checksum */
param_cksum; /* All-process parameter checksum */
_u8* fault_loc; /* Fault function name, if any */
_u32 param_count; /* Number of parameters */
_u32* param_data; /* Parameter values (32-bit) */
_u32 func_skip; /* Parameter skip count */
_u64* param_range; /* Parameter behavior tracing */
_u8* param_chgmap; /* Parameter values (32-bit) */
_u32 eff_lwarn; /* Last effector position warn */
_u32 func_count; /* Function count (informative) */
struct naive_list_int2* eff; /* Per-param effector pos list */
struct naive_list_int has_eff; /* Has effector? */
};
static _u8** queue_fn; /* Trace queue: filenames */
static struct bunny_traceitem** queue_ck; /* Trace queue: reference traces. */
static _u32 queue_len; /* Trace queue length */
static _u8* queue_af; /* New affectors witnessed? */
static struct naive_list_int64 known_exec[0x1000];
static struct naive_list_ptr known_exti[0x1000];
static struct naive_list_int64 known_param[0x1000];
/* CYGWIN runtime 'cygserver' compatibility check */
static void check_shm_cap(void) {
#ifdef __CYGWIN__
if (!getenv("CYGWIN")) {
outf("Sorry, you need to enable SHM support in Cygwin first:\n"
" 1. Install Cygwin IPC service ('cygserver-config').\n"
" 2. Launch the service ('net start cygserver').\n"
" 3. Export 'CYGWIN=server' to your environment.\n");
exit(1);
}
#endif /* __CYGWIN__ */
}
void print_stats() {
gettimeofday(&en,0);
float dtime = en.tv_sec - st.tv_sec + ((float)en.tv_usec - st.tv_usec)/1e6;
outf("\n"
" Fuzz cycles executed : %u (%u partial)\n"
" Processes launched : %llu\n"
" Fault conditions : %u\n"
" Call path count : %u (+%u ignored)\n"
" Parameter variations : %u (+%u ignored)\n"
" Effector segments : %u\n"
" Total running time : %u:%02u:%02u\n"
" Average performance : %0.02f execs/sec\n",
cur_cycle, fuzz_ign, exec_cnt, crash_cnt, epath_cnt, epath_ign,
ppath_cnt, ppath_ign, effect_cnt,
(int)(dtime/3600.), (int)((dtime-floorf(dtime/3600.)*3600.)/60.), (int)(dtime-floorf(dtime/60.)*60.),
(float)exec_cnt / (dtime - 1.1 * usleeps_done ));
}
/* Termination signal handler; sending SIGTERM to bunny-flow and bunny-exec
ensures a proper cleanup of SHM regions and child processes. */
static void handle_sig(int sig) {
print_stats();
outf("\n+++ Fuzzing stopped on signal %d +++\n", sig);
if (flow_pid != -1) kill(flow_pid,SIGTERM);
if (exec_pid != -1) kill(exec_pid,SIGTERM);
fclose(outfile);
exit(1);
}
/* ... */
static void usage(_u8* argv0) {
outf("%s [ options ] -- /path/to/traced_app [ ... ]\n\n"
"Mandatory job parameters:\n"
" -i dir - fuzzer input data directory\n"
" -o dir - output directory (crash cases)\n\n"
"Non-standard output control:\n"
" -f file - write data to file\n"
" -t host:port - send data to a TCP service\n"
" -u host:port - send data to a UDP service\n"
" -l port - wait for a local TCP client\n\n"
"Execution control:\n"
" -s nn - no-action execution time limit [2000 ms]\n"
" -x nn - total execution time limit [5000 ms]\n"
" -d - allow 'dummy' mode with no instrumentation\n\n"
"Fuzzing process control:\n"
" -B nn[+s] - maximum bitflip length, +stepover [8+1]\n"
" -C nn[+s] - maximum chunk operation size, +stepover [8+1]\n"
" -O nn - chunk offset limit [8]\n"
" -E nn - per-parameter effector size limit [10]\n"
" -X b:nn - add a custom pattern walk value\n"
" -Y nn - number of random pattern walk cyclces [8]\n"
" -R nn - random exploration repeat count [2096]\n"
" -S nn - random exploration stacking count [8]\n"
" -N nn - new call path limit per fuzzing round [32]\n"
" -P nn - new function parameter limit per round [16]\n"
" -L nn - fuzz calibration cycle count [2]\n"
" -M nn - maximum number of function calls to follow [200]\n"
" -F nn - fuzzable input data size limit [start*2]\n"
" -8 - use all possible 8-bit values in walks\n"
" -n - do not abandon execution paths after a fault\n"
" -r - use fine-grained 64-bit parameter ranging\n"
" -z - do not use parameter ranging at all\n"
" -k - skip deterministic fuzz rounds\n"
" -q - randomize queue processing order\n"
" -g - use audible crash notification\n\n"
"Predictably, a somewhat less cryptic explanation of these parameters\n"
"is generously provided in the documentation.\n\n", argv0);
exit(1);
}
/* Concatenate dir + file into a single string. Uses a cyclic buffer -
subsequent calls to N() will automatically deallocate previous data. */
static _u8* N(_u8* dir, _u8* file) {
static _u8* fn = 0;
if (fn) free(fn);
fn = malloc(strlen(dir) + strlen(file) + 2);
if (!fn) fatal("out of memory");
sprintf(fn,"%s/%s",dir,file);
return fn;
}
/* Converts pathname into a canonical fully-qualified one, if needed, to
make symlinks work. */
static _u8* Ncanon( _u8* file) {
static _u8* fn = 0;
static char* cwd = 0;
if (file[0] == '/') return file;
if (!cwd) {
cwd = getcwd(0,MAXTOKEN);
if (!cwd) fatal("out of memory");
}
if (fn) free(fn);
fn = malloc(strlen(cwd) + strlen(file) + 2);
if (!fn) fatal("out of memory");
sprintf(fn,"%s/%s",cwd,file);
return fn;
}
/* Opens a main logfile for outf() calls */
static void init_outfile(void) {
_s32 fd;
_u8* fn = N(out_dir,"BUNNY.log");
unlink(fn);
fd = open(fn,O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE,0600);
if (fd < 0) pfatal("cannot create '%s'",fn);
outfile = fdopen(fd,"w");
setvbuf(outfile, 0, _IOLBF, 0);
}
/* Splash screen */
static void display_info(char** argv, int argc1) {
time_t t = time(0);
_u8* ct= ctime(&t);
_u8* ip = (_u8*)&write_host;
if (ct[strlen(ct)-1] == '\n') ct[strlen(ct)-1] = 0;
outf("Bunny the Fuzzer - a high-performance instrumented fuzzer by <[email protected]>\n"
"---------------------------------------------------------------------------------\n\n");
outf(" Code version : " VERSION " (" __DATE__ " " __TIME__ ")\n");
outf(" Start date : %s\n", ct);
outf(" Target exec : %s\n", argv[0]);
outf(" Command line : ");
if (argc1 == 1) outf("<none>"); else {
_u32 i;
for (i=1;i<argc1;i++) outf("%s ",argv[i]);
}
outf("\n");
outf(" Input files : %s/\n", in_dir);
outf(" State files : %s/\n", out_dir);
outf(" Fuzz output : ");
if (!write_file && !write_port) outf("<target stdin>\n");
else if (write_file) outf("%s\n",write_file);
else if (!write_host) outf("client on %u/tcp\n",write_port);
else outf("server at %u.%u.%u.%u %u/%s\n", ip[0], ip[1], ip[2], ip[3],
write_port, use_udp ? "udp" : "tcp");
outf(" Random seed : %08x\n",rand_seed);
outf(" All settings : T=%u,%u B=%u+%u C=%u+%u,%u A=%u X=%u,%u,%u+%u R=%u*%u L%u=%u,%u r%u%u c=%u U%u E=%u f%u k%u F=%u\n\n",
time_limit, stall_limit, bitflip_max, bitflip_inc, chunk_max,
chunk_inc, chunk_off_max, eff_count_max, byte_val_list.c,
word_val_list.c, dword_val_list.c, rand_val_walks, rand_phase_cycles,
rand_phase_stacking, use_qrand, cycle_branch_limit, cycle_value_limit, full_range, zero_range,
cal_cycles, use_all8, func_limit, keep_fault, skip_rounds, size_limit);
}
/* Issue a generic command to bunny-flow; see message.h for more info */
static _u32 flow_command(_u32 type, _u32 p1, _u32 p2, _u32 p3) {
_u32 r;
struct bunny_flowreq f;
if (type == FLOW_SAVEFILE) fatal("flow_command called with FLOW_SAVEFILE");
f.type = type;
f.p1 = p1;
f.p2 = p2;
f.p3 = p3;
if (sure_write(flow_pipe_cmd,&f,sizeof(struct bunny_flowreq)) != sizeof(struct bunny_flowreq))
fatal("unable to communicate with the component (see bunny-flow.out)");
if (sure_read(flow_pipe_ret,&r,sizeof(_u32)) != sizeof(_u32))
fatal("short response on command 0x%x(%d,%d,%d) (see bunny-flow.out)",type,p1,p2,p3);
if (type != FLOW_GET_FUZZABLE && r)
fatal("NOK response on command 0x%x(%d,%d,%d) (see bunny-flow.out)",type,p1,p2,p3);
else
if (type == FLOW_GET_FUZZABLE && !r)
fatal("FLOW_GET_FUZZABLE == 0 (see bunny-flow.out)");
return r;
}
/* Special handling of FLOW_SAVEFILE command, with a separately transmitted filename */
static void flow_savefile(_u8* fname) {
_u32 r;
struct bunny_flowreq f;
f.type = FLOW_SAVEFILE;
f.p1 = strlen(fname);
f.p2 = 0;
f.p3 = 0;
if (sure_write(flow_pipe_cmd,&f,sizeof(struct bunny_flowreq)) != sizeof(struct bunny_flowreq))
fatal("unable to communicate with the component (see bunny-flow.out)");
if (sure_write(flow_pipe_cmd,fname,f.p1) != f.p1)
fatal("unable to communicate with the component (see bunny-flow.out)");
if (sure_read(flow_pipe_ret,&r,sizeof(_u32)) != sizeof(_u32))
fatal("short response on FLOW_SAVEFILE (see bunny-flow.out)");
if (r)
fatal("NOK response on FLOW_SAVEFILE (see bunny-flow.out)");
}
/* Point bunny-flow input to an existing directory. The directory is not copied over,
simply symlinked. */
static void point_inflow(_u8* target_dir) {
if (!inflow_dir) fatal("inflow_dir is NULL");
unlink(inflow_dir); /* Ignore errors */
if (!target_dir) target_dir = in_dir;
if (symlink(Ncanon(target_dir),inflow_dir))
pfatal("unable to symlink %s -> %s",target_dir,inflow_dir);
}
/* Remove all files in bunny-flow output directory. */
static void purge_outflow(void) {
DIR* d;
struct dirent* dent;
_u8 wbuf[MAXTOKEN];
if (!outflow_dir) fatal("inflow_dir is NULL");
if (!(d = opendir(outflow_dir))) pfatal("unable to open %s",outflow_dir);
while ((dent = readdir(d))) {
if (dent->d_name[0] == '.') continue;
snprintf(wbuf,MAXTOKEN,"%s/%s",outflow_dir,dent->d_name);
if (unlink(wbuf)) pfatal("unable to unlink %s\n",wbuf);
}
closedir(d);
}
/* Start up bunny-flow, set up its input and output directories, comm pipes. */
static void start_flow(void) {
int toflow[2], fromflow[2];
_u32 fuzzable;
if (pipe(toflow) || pipe(fromflow)) pfatal("unable to create a pipe");
inflow_dir = strdup(N(out_dir,".flow-in"));
point_inflow(in_dir);
outflow_dir = strdup(N(out_dir,".flow-out"));
if (!outflow_dir) fatal("out of memory");
mkdir(outflow_dir,0755); /* Ignore errors */
purge_outflow();
flow_pid = fork();
if (flow_pid < 0) pfatal("unable to create a child process");
if (!flow_pid) {
_u8 *logfile;
_s32 fd;
logfile = N(out_dir,"bunny-flow.out");
unlink(logfile);
fd = open(logfile,O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE,0600);
if (fd >= 0) { dup2(fd, 2); close(fd); }
if (dup2(toflow[0],0) < 0 || dup2(fromflow[1],1) < 0) pfatal("dup2() failed");
close(toflow[0]); close(toflow[1]);
close(fromflow[0]); close(fromflow[1]);
#ifdef USE_EXEC_CWD
if (access("bunny-flow",X_OK))
#endif /* USE_EXEC_CWD */
execlp("bunny-flow","bunny-flow",inflow_dir,outflow_dir, (char*) NULL);
#ifdef USE_EXEC_CWD
else
execl("./bunny-flow","bunny-flow",inflow_dir,outflow_dir, (char*) NULL);
#endif /* USE_EXEC_CWD */
pfatal("cannot execute bunny-flow");
}
flow_pipe_cmd = toflow[1];
flow_pipe_ret = fromflow[0];
close(toflow[0]);
close(fromflow[1]);
fuzzable = flow_command(FLOW_GET_FUZZABLE,0,0,0);
if (!size_limit) size_limit = 2*fuzzable;
outf("[+] Flow controller launched, %u bytes fuzzable.\n",fuzzable);
}
/* Find a master descriptor for a known execution path */
static struct bunny_traceitem* lookup_exec(_u64 cksum) {
_u32 pos = cksum & 0xFFF;
_u32 i;
for (i=0;i<known_exec[pos].c;i++)
if (known_exec[pos].v[i] == cksum)
return (struct bunny_traceitem*)known_exti[pos].v[i];
return 0;
}
/* Queue a specified directory for later fuzzing cycles. */
static _u32 add_queue(_u8* indir, struct bunny_traceitem* ref) {
_u32 i;
for (i=0;i<queue_len;i++)
if (!queue_fn[i]) break;
if (i == queue_len) {
queue_len++;
if ((queue_len % ALLOC_CHUNK) == 1) {
queue_fn = realloc(queue_fn,(queue_len + ALLOC_CHUNK) * sizeof(_u8*));
queue_ck = realloc(queue_ck,(queue_len + ALLOC_CHUNK) * sizeof(struct bunny_traceitem*));
queue_af = realloc(queue_af,(queue_len + ALLOC_CHUNK) * sizeof(_u8));
if (!queue_fn || !queue_ck || !queue_af) fatal("out of memory");
}
}
queue_af[i] = 0;
queue_ck[i] = ref;
queue_fn[i] = strdup(indir);
if (!queue_fn[i]) fatal("out of memory");
total_queue++;
queue_real++;
return i;
}
/* Fetch the first queue entry, and mark this slot as unused, return pathname
to a testing directory, fill in effector and reference path data. Subsequent
calls to get_queue free the previously returned dynamic string, too. */
static _u8* get_queue(struct bunny_traceitem** ref, _u8* new_af) {
static _u8* ret = 0;
_u32 i, skip = 0;;
if (!queue_real) return 0;
if (use_qrand) skip = R(queue_real);
for (i=0;i<queue_len;i++)
if (queue_fn[i] && !skip--) break;
if (ret) free(ret);
ret = queue_fn[i];
queue_fn[i] = 0;
*ref = queue_ck[i];
*new_af = queue_af[i];
queue_real--;
return ret;
}
/* bunny-exec cannot checksum parameter variations on its own, because
it does not have all the path calibration data ahead of time (this is
applied, if available, by run_program()). We can do the checksumming here.
CRC64 would perhaps be faster, but MD5 is far more robust for all patterns. */
static void do_param_cksum(struct bunny_traceitem* t) {
MD5_CTX ctx;
_u8 res[16];
MD5_Init(&ctx);
MD5_Update(&ctx,t->param_range,sizeof(_u64) * t->param_count);
MD5_Final((char*)res,&ctx);
t->param_cksum = *(_u64*)res;
}
/* Start bunny-exec in keep-alive mode. */
static void launch_exec(_u8* infn) {
_s32 exec_pipe[2];
_s32 infd = 0;
if (infn) {
infd = open(infn,O_RDONLY|O_LARGEFILE);
if (infd < 0) pfatal("unable to open %s for reading",infn);
}
if (pipe(exec_pipe)) pfatal("unable to create pipe");
exec_pid = fork();
if (exec_pid < 0) pfatal("unable to create a child process");
if (!exec_pid) {
_u8 tmp[64];
_u8* logfile = N(out_dir,"bunny-exec.out");
_u32 fd;
unlink(logfile);
fd = open(logfile,O_WRONLY|O_CREAT|O_EXCL|O_LARGEFILE,0600);
if (fd >= 0) {
dup2(fd, 2);
#ifdef DEBUG_TRACE
dup2(fd, 1);
#else
close(fd);
fd = open("/dev/null",O_WRONLY);
if (fd >= 0) dup2(fd,1);
#endif /* ^DEBUG_TRACE */
close(fd);
}
if (dup2(exec_pipe[1],99) < 0) pfatal("dup2() failed");
close(exec_pipe[0]);
close(exec_pipe[1]);
if (infn) {
if (dup2(infd,0) < 0) pfatal("dup2() failed");
close(infd);
} else {
close(0);
fd = open("/dev/null",O_RDONLY);
if (fd) fatal("unable to open /dev/null as fd 0");
}
sprintf(tmp,"%u",time_limit);
setenv("BUNNY_MAXTIME",tmp,1);
sprintf(tmp,"%u",stall_limit);
setenv("BUNNY_MAXSTUCK",tmp,1);
sprintf(tmp,"%u",func_limit);
setenv("BUNNY_MAXFUNC",tmp,1);
setenv("BUNNY_KEEPALIVE","yes",1);
#ifdef USE_EXEC_CWD
if (access("bunny-exec",X_OK))
#endif /* USE_EXEC_CWD */
execvp("bunny-exec",(char**)program_args);
#ifdef USE_EXEC_CWD
else execv("./bunny-exec",(char**)program_args);
#endif /* USE_EXEC_CWD */
pfatal("cannot execute bunny-exec");
}
close(exec_pipe[1]);
if (infn) close(infd);
exec_pipe_ret = exec_pipe[0];
}
/* Launch a program, apply path profiling data if reference trace is available,
allocate all the structures necessary, etc... */
static struct bunny_traceitem* run_program(void) {
struct bunny_traceitem *ret, *ref;
struct bunny_tracedesc btd;
_s32 i;
_u8* infn = 0;
exec_cnt++;
ret = malloc(sizeof(struct bunny_traceitem));
if (!ret) fatal("out of memory");
purge_outflow();
/* Produce input for the traced application. Note that TCP connect()
will loop until next command on connection refused, so we're cool. */
if (!write_file && !write_port) {
infn = N(out_dir,".fake-pipe");
flow_savefile(infn);
} else if (write_file) flow_savefile(write_file);
else if (!write_host) flow_command(FLOW_TCP_ACCEPT, htons(write_port), 0, 0);
else flow_command(use_udp ? FLOW_UDP_SEND : FLOW_TCP_CONNECT, write_host, htons(write_port), 0);
if (exec_pid < 0) launch_exec(infn);
else kill(exec_pid,SIGUSR1);
if (sure_read(exec_pipe_ret,&btd,sizeof(struct bunny_tracedesc)) != sizeof(struct bunny_tracedesc))
fatal("short trace struct read (see bunny-exec.out)");
ret->fuzzable = 0;
ret->exit_status = btd.exit_status;
ret->thread_count = btd.thread_count;
ret->exec_cksum = btd.exec_cksum;
ret->param_count = btd.param_count;
ret->func_count = btd.func_count;
ret->func_skip = btd.func_skip;
/* Grab fault function name, if any */
if (btd.fault_len) {
_u8* tmp = malloc(btd.fault_len + 1);
if (!tmp) fatal("out of memory");
if (sure_read(exec_pipe_ret,tmp,btd.fault_len) != btd.fault_len)
fatal("short fault location read (see bunny-exec.out)");
tmp[btd.fault_len] = 0;
ret->fault_loc = tmp;
} else ret->fault_loc = 0;
ret->eff_lwarn = 0xFFFFFFFF;
ret->param_data = malloc(btd.param_count * sizeof(_u32));
ret->param_range = malloc(btd.param_count * sizeof(_u64));
ret->param_chgmap = calloc(1,btd.param_count * sizeof(_u8)); /* zero */
if (!ret->param_data || !ret->param_range || !ret->param_chgmap) fatal("out of memory");
if (sure_read(exec_pipe_ret,ret->param_data,btd.param_count * sizeof(_u32))
!= btd.param_count * sizeof(_u32))
fatal("short param read, len %u (see bunny-exec.out)",btd.param_count);
if (allow_dummy) ret->exit_status &= ~EXITF_NOCALLS;
ref = lookup_exec(ret->exec_cksum);
/* If we can look up reference data for checksumming, use it and calculate
a parameter checksum, also updating the known range for reference
path; otherwise, just map arguments and default to checksum of 0. */
if (ref && ref->param_cksum) {
/* If we're dealing with a crash / stall, and the trace is shorter than
expected, cut the traced application some slack - on timeouts, there
is no guarantee that all SHM writes were completed. */
if ((!btd.exit_status && btd.param_count != ref->param_count) ||
(btd.exit_status && btd.param_count > ref->param_count))
fatal("parameter count varies for a known call path %016llx (%u != %u) - bad use of BunnySnoop?",
ret->exec_cksum, btd.param_count, ref->param_count);
for (i=0;i<btd.param_count;i++)
if (ref->param_range[i] != RANGE64_VOLATILE) {
_u64 nr = zero_range ? 1 : (full_range ? RANGE64(ret->param_data[i]) : RANGE8(ret->param_data[i]));
/* Update both the reference data and the current checksum */
ret->param_range[i] = nr;
if (!(ref->param_range[i] & nr)) {
ref->param_range[i] |= nr;
ret->param_chgmap[i] = 1;
}
} else ret->param_range[i] = RANGE64_VOLATILE;
do_param_cksum(ret);
} else {
for (i=0;i<btd.param_count;i++)
ret->param_range[i] = zero_range ? 1 : (full_range ? RANGE64(ret->param_data[i]) : RANGE8(ret->param_data[i]));
ret->param_cksum = 0;
}
ret->eff = calloc(1, btd.param_count * sizeof(struct naive_list_int2)); /* zero */
if (!ret->eff) fatal("out of memory");
ret->has_eff.c = 0;
ret->has_eff.v = 0;
return ret;
}
/* Recycle memory allocated by run_program(), should the resulting execution path
prove to be previously explored and otherwise uninteresting. */
static void discard_context(struct bunny_traceitem* t, _u8 free_t) {
_u32 i;
if (!t->param_data) fatal("context freed more than once");
free(t->param_data);
free(t->param_range);
free(t->param_chgmap);
/* To detect access... */
t->param_data = 0;
t->param_range = 0;
for (i=0;i<t->param_count;i++) FREEINT2(t->eff[i]);
free(t->eff);
t->eff = 0;
FREEINT(t->has_eff);
if (t->fault_loc) free(t->fault_loc);
if (free_t) free(t);
}
/* Loop the program until it doesn't crash once or 'assure_crash+1' crashes in
a row have been observed. */
static struct bunny_traceitem* retry_program(void) {
int count = 0;
struct bunny_traceitem *t = run_program();
while (count < assure_crash && t->exit_status & (EXITF_CRASH | EXITF_TIMEOUT | EXITF_STUCK)) {
discard_context(t,1);
t = run_program();
count++;
}
if (t->exit_status & (EXITF_CRASH | EXITF_TIMEOUT | EXITF_STUCK)) count++;
if (count) outf(" A crash was encountered that could be re-produced %i time(s).\n", count-1);
return t;
}
/* Empty an input directory for a fully processed queue entry. */
static void free_input(_u8* dir,_u8 deldir) {
DIR* d;
struct dirent* dent;
if (!strcmp(in_dir,dir) || !dir[0]) return;
d = opendir(dir);
if (!d) pfatal("cannot open '%s' for reading",dir);
while ((dent = readdir(d))) {
if (dent->d_name[0] == '.') continue;
unlink(N(dir,dent->d_name));
}
closedir(d);
if (deldir) {
_u8* x = strrchr(dir,'/');
rmdir(dir);
if (x) { *x = 0; rmdir(dir); }
}
}
/* Build a new input directory based on current bunny-flow output.
Note that hard links, not copies of files, are created. */
static _u8* make_input(_u8* prefix) {
_u8 *curdir, tmp[MAXTOKEN];
DIR* d;
struct dirent* dent;
static _u8 *newdir = 0;
if (newdir) free(newdir);
curdir = strdup(N(out_dir,".flow-out"));
if (!curdir) fatal("out of memory");
sprintf(tmp,"%s%03llu",prefix, input_cnt / 1000);
mkdir(N(out_dir,tmp),0755);
sprintf(tmp,"%s%03llu/%03llu",prefix, input_cnt / 1000, input_cnt % 1000);
newdir = strdup(N(out_dir,tmp));
if (!newdir) fatal("out of memory");
input_cnt++;
mkdir(newdir,0755);
free_input(newdir,0);
d = opendir(curdir);
if (!d) pfatal("cannot open '%s' for reading",curdir);
while ((dent = readdir(d))) {
_u8 *odname;
if (dent->d_name[0] == '.') continue;
odname = strdup(N(curdir,dent->d_name));
if (!odname) fatal("out of memory");
if (link(odname, N(newdir,dent->d_name)))
pfatal("cannot link '%s' to '%s/",odname,newdir);
free(odname);
}
closedir(d);
free(curdir);
return newdir;
}
/* Register a new execution path; if 'queue' is set, a new queue entry is created, too. */
static _u8 register_new_exec(struct bunny_traceitem* t, _u8 queue) {
_u8* inp;
_u32 pos = t->exec_cksum & 0xFFF;
_u32 i;
for (i=0;i<known_exec[pos].c;i++)
if (known_exec[pos].v[i] == t->exec_cksum) return 0;
ADDINT64(known_exec[pos],t->exec_cksum);
ADDPTR(known_exti[pos],t);
epath_cnt++;
t->param_cksum = 0; /* unknown */
if (queue) {
inp = make_input("case");
add_queue(inp,0);
outf(" + New call path stored at '%s' (c=%016llx).\n",inp,t->exec_cksum);
if (t->func_skip)
outf(" >>> Skipped %u function calls (limit is %u, use -M to adjust).\n",t->func_skip,func_limit);
}
return 1;
}
#define EFF_UNUSED 0xF0000000
/* Register a new effector for a given location in the parameter trace block for the current
execution path. Merge overlapping blocks, mind the limits. */
static _u8 add_effector(struct bunny_traceitem* t, _u32 param, _u32 bytepos, _u8 bytelen) {
_u32 i, efflen = 0;
for (i=0;i<t->eff[param].c;i++) {
if (t->eff[param].v1[i] == EFF_UNUSED) continue;
/* New effector fully contained within an existing one. */
if (t->eff[param].v1[i] <= bytepos &&
t->eff[param].v1[i] + t->eff[param].v2[i] >= bytepos + bytelen) return 0;
/* Beginning of eff[param] inside our block, or adjacent to its end;
or beginning of our block inside eff[param], or adjacent to its end. */
if ((t->eff[param].v1[i] >= bytepos && t->eff[param].v1[i] <= bytepos + bytelen) ||
(bytepos >= t->eff[param].v1[i] && bytepos <= t->eff[param].v1[i] + t->eff[param].v2[i])) {
_u32 newbeg = (t->eff[param].v1[i] < bytepos) ? t->eff[param].v1[i] : bytepos,
newend1 = ((t->eff[param].v1[i] + t->eff[param].v2[i]) > (bytepos + bytelen)) ?
(t->eff[param].v1[i] + t->eff[param].v2[i]) : (bytepos + bytelen),
j;
if (newend1 - newbeg > eff_count_max) {
if (t->eff_lwarn != param) {
outf(" >>> Capping function parameter #%u effectors at %u - possible checksum?\n",
param, eff_count_max);
t->eff_lwarn = param;
}
return 0;
}
bytepos = t->eff[param].v1[i] = newbeg;
bytelen = t->eff[param].v2[i] = newend1 - newbeg;
effect_cnt++;
/* Note that we now might have an overlap with another effector located elsewhere on the
list - better safe than sorry, it's less expensive to check than to dilute fuzzing
quality; bytepos and bytelen now point to the boundaries of the existing block. */
for (j=i+1;j != i; j = (j+1) % t->eff[param].c) {
if ((t->eff[param].v1[j] >= bytepos && t->eff[param].v1[j] <= bytepos + bytelen) ||
(bytepos >= t->eff[param].v1[j] && bytepos <= t->eff[param].v1[j] + t->eff[param].v2[j])) {