• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2    american fuzzy lop++ - network proxy server
3    -------------------------------------------
4 
5    Originally written by Michal Zalewski
6 
7    Forkserver design by Jann Horn <jannhorn@googlemail.com>
8 
9    Now maintained by Marc Heuse <mh@mh-sec.de>,
10                         Heiko Eißfeldt <heiko.eissfeldt@hexco.de> and
11                         Andrea Fioraldi <andreafioraldi@gmail.com> and
12                         Dominik Maier <mail@dmnk.co>
13 
14    Copyright 2016, 2017 Google Inc. All rights reserved.
15    Copyright 2019-2022 AFLplusplus Project. All rights reserved.
16 
17    Licensed under the Apache License, Version 2.0 (the "License");
18    you may not use this file except in compliance with the License.
19    You may obtain a copy of the License at:
20 
21      http://www.apache.org/licenses/LICENSE-2.0
22 
23  */
24 
25 #define AFL_MAIN
26 
27 #include "config.h"
28 #include "types.h"
29 #include "debug.h"
30 #include "alloc-inl.h"
31 #include "hash.h"
32 #include "forkserver.h"
33 #include "sharedmem.h"
34 #include "common.h"
35 
36 #include <stdio.h>
37 #include <unistd.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <time.h>
41 #include <errno.h>
42 #include <signal.h>
43 #include <dirent.h>
44 #include <fcntl.h>
45 
46 #include <sys/wait.h>
47 #include <sys/time.h>
48 #include <sys/stat.h>
49 #include <sys/types.h>
50 #include <sys/resource.h>
51 #include <netinet/in.h>
52 #include <netinet/ip6.h>
53 #include <arpa/inet.h>
54 #include <sys/mman.h>
55 #ifndef USEMMAP
56   #include <sys/shm.h>
57 #endif
58 #include <sys/socket.h>
59 #include <netdb.h>
60 
61 #ifdef USE_DEFLATE
62   #include <libdeflate.h>
63 struct libdeflate_compressor *  compressor;
64 struct libdeflate_decompressor *decompressor;
65 #endif
66 
67 static u8 *in_file,                    /* Minimizer input test case         */
68     *out_file;
69 
70 static u8 *in_data;                    /* Input data for trimming           */
71 static u8 *buf2;
72 
73 static s32 in_len;
74 static s32 buf2_len;
75 static u32 map_size = MAP_SIZE;
76 
77 static volatile u8 stop_soon;          /* Ctrl-C pressed?                   */
78 
79 /* See if any bytes are set in the bitmap. */
80 
anything_set(afl_forkserver_t * fsrv)81 static inline u8 anything_set(afl_forkserver_t *fsrv) {
82 
83   u32 *ptr = (u32 *)fsrv->trace_bits;
84   u32  i = (map_size >> 2);
85 
86   while (i--) {
87 
88     if (*(ptr++)) { return 1; }
89 
90   }
91 
92   return 0;
93 
94 }
95 
at_exit_handler(void)96 static void at_exit_handler(void) {
97 
98   afl_fsrv_killall();
99 
100 }
101 
102 /* Write output file. */
103 
write_to_file(u8 * path,u8 * mem,u32 len)104 static s32 write_to_file(u8 *path, u8 *mem, u32 len) {
105 
106   s32 ret;
107 
108   unlink(path);                                            /* Ignore errors */
109 
110   ret = open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
111 
112   if (ret < 0) { PFATAL("Unable to create '%s'", path); }
113 
114   ck_write(ret, mem, len, path);
115 
116   lseek(ret, 0, SEEK_SET);
117 
118   return ret;
119 
120 }
121 
122 /* Execute target application. Returns 0 if the changes are a dud, or
123    1 if they should be kept. */
124 
run_target(afl_forkserver_t * fsrv,char ** argv,u8 * mem,u32 len,u8 first_run)125 static u8 run_target(afl_forkserver_t *fsrv, char **argv, u8 *mem, u32 len,
126                      u8 first_run) {
127 
128   afl_fsrv_write_to_testcase(fsrv, mem, len);
129 
130   fsrv_run_result_t ret =
131       afl_fsrv_run_target(fsrv, fsrv->exec_tmout, &stop_soon);
132 
133   if (ret == FSRV_RUN_ERROR) { FATAL("Couldn't run child"); }
134 
135   if (stop_soon) {
136 
137     SAYF(cRST cLRD "\n+++ aborted by user +++\n" cRST);
138     exit(1);
139 
140   }
141 
142   return ret;
143 
144 }
145 
146 /* Handle Ctrl-C and the like. */
147 
handle_stop_sig(int sig)148 static void handle_stop_sig(int sig) {
149 
150   stop_soon = 1;
151   afl_fsrv_killall();
152 
153 }
154 
155 /* Do basic preparations - persistent fds, filenames, etc. */
156 
set_up_environment(afl_forkserver_t * fsrv)157 static void set_up_environment(afl_forkserver_t *fsrv) {
158 
159   u8 *x;
160 
161   fsrv->dev_null_fd = open("/dev/null", O_RDWR);
162   if (fsrv->dev_null_fd < 0) { PFATAL("Unable to open /dev/null"); }
163 
164   if (!out_file) {
165 
166     u8 *use_dir = ".";
167 
168     if (access(use_dir, R_OK | W_OK | X_OK)) {
169 
170       use_dir = get_afl_env("TMPDIR");
171       if (!use_dir) { use_dir = "/tmp"; }
172 
173     }
174 
175     out_file = alloc_printf("%s/.afl-input-temp-%u", use_dir, getpid());
176 
177   }
178 
179   unlink(out_file);
180 
181   fsrv->out_fd = open(out_file, O_RDWR | O_CREAT | O_EXCL, 0600);
182 
183   if (fsrv->out_fd < 0) { PFATAL("Unable to create '%s'", out_file); }
184 
185   /* Set sane defaults... */
186 
187   x = get_afl_env("ASAN_OPTIONS");
188 
189   if (x) {
190 
191     if (!strstr(x, "abort_on_error=1")) {
192 
193       FATAL("Custom ASAN_OPTIONS set without abort_on_error=1 - please fix!");
194 
195     }
196 
197     if (!strstr(x, "symbolize=0")) {
198 
199       FATAL("Custom ASAN_OPTIONS set without symbolize=0 - please fix!");
200 
201     }
202 
203   }
204 
205   x = get_afl_env("MSAN_OPTIONS");
206 
207   if (x) {
208 
209     if (!strstr(x, "exit_code=" STRINGIFY(MSAN_ERROR))) {
210 
211       FATAL("Custom MSAN_OPTIONS set without exit_code=" STRINGIFY(
212           MSAN_ERROR) " - please fix!");
213 
214     }
215 
216     if (!strstr(x, "symbolize=0")) {
217 
218       FATAL("Custom MSAN_OPTIONS set without symbolize=0 - please fix!");
219 
220     }
221 
222   }
223 
224   setenv("ASAN_OPTIONS",
225          "abort_on_error=1:"
226          "detect_leaks=0:"
227          "symbolize=0:"
228          "allocator_may_return_null=1",
229          0);
230 
231   setenv("MSAN_OPTIONS", "exit_code=" STRINGIFY(MSAN_ERROR) ":"
232                          "symbolize=0:"
233                          "abort_on_error=1:"
234                          "allocator_may_return_null=1:"
235                          "msan_track_origins=0", 0);
236 
237   if (get_afl_env("AFL_PRELOAD")) {
238 
239     if (fsrv->qemu_mode) {
240 
241       /* afl-qemu-trace takes care of converting AFL_PRELOAD. */
242 
243     } else {
244 
245       setenv("LD_PRELOAD", getenv("AFL_PRELOAD"), 1);
246       setenv("DYLD_INSERT_LIBRARIES", getenv("AFL_PRELOAD"), 1);
247 
248     }
249 
250   }
251 
252 }
253 
254 /* Setup signal handlers, duh. */
255 
setup_signal_handlers(void)256 static void setup_signal_handlers(void) {
257 
258   struct sigaction sa;
259 
260   sa.sa_handler = NULL;
261   sa.sa_flags = SA_RESTART;
262   sa.sa_sigaction = NULL;
263 
264   sigemptyset(&sa.sa_mask);
265 
266   /* Various ways of saying "stop". */
267 
268   sa.sa_handler = handle_stop_sig;
269   sigaction(SIGHUP, &sa, NULL);
270   sigaction(SIGINT, &sa, NULL);
271   sigaction(SIGTERM, &sa, NULL);
272 
273 }
274 
275 /* Display usage hints. */
276 
usage(u8 * argv0)277 static void usage(u8 *argv0) {
278 
279   SAYF(
280       "\n%s [ options ] -- /path/to/target_app [ ... ]\n\n"
281 
282       "Required parameters:\n"
283 
284       "  -i port       - the port to listen for the client to connect to\n\n"
285 
286       "Execution control settings:\n"
287 
288       "  -f file       - input file read by the tested program (stdin)\n"
289       "  -t msec       - timeout for each run (%d ms)\n"
290       "  -m megs       - memory limit for child process (%d MB)\n"
291       "  -Q            - use binary-only instrumentation (QEMU mode)\n"
292       "  -U            - use unicorn-based instrumentation (Unicorn mode)\n"
293       "  -W            - use qemu-based instrumentation with Wine (Wine "
294       "mode)\n\n"
295 
296       "Environment variables used:\n"
297       "TMPDIR: directory to use for temporary input files\n"
298       "ASAN_OPTIONS: custom settings for ASAN\n"
299       "              (must contain abort_on_error=1 and symbolize=0)\n"
300       "MSAN_OPTIONS: custom settings for MSAN\n"
301       "              (must contain exitcode="STRINGIFY(MSAN_ERROR)" and symbolize=0)\n"
302       "AFL_MAP_SIZE: the shared memory size for that target. must be >= the size\n"
303       "              the target was compiled for\n"
304       "AFL_PRELOAD:  LD_PRELOAD / DYLD_INSERT_LIBRARIES settings for target\n"
305 
306       , argv0, EXEC_TIMEOUT, MEM_LIMIT);
307 
308   exit(1);
309 
310 }
311 
recv_testcase(int s,void ** buf)312 int recv_testcase(int s, void **buf) {
313 
314   u32    size;
315   s32    ret;
316   size_t received;
317 
318   received = 0;
319   while (received < 4 && (ret = recv(s, &size + received, 4 - received, 0)) > 0)
320     received += ret;
321   if (received != 4) FATAL("did not receive size information");
322   if (size == 0) FATAL("did not receive valid size information");
323   // fprintf(stderr, "received size information of %d\n", size);
324 
325   if ((size & 0xff000000) != 0xff000000) {
326 
327     *buf = afl_realloc(buf, size);
328     if (unlikely(!*buf)) { PFATAL("Alloc"); }
329     received = 0;
330     // fprintf(stderr, "unCOMPRESS (%u)\n", size);
331     while (received < size &&
332            (ret = recv(s, ((char *)*buf) + received, size - received, 0)) > 0)
333       received += ret;
334 
335   } else {
336 
337 #ifdef USE_DEFLATE
338     u32 clen;
339     size -= 0xff000000;
340     *buf = afl_realloc(buf, size);
341     if (unlikely(!*buf)) { PFATAL("Alloc"); }
342     received = 0;
343     while (received < 4 &&
344            (ret = recv(s, &clen + received, 4 - received, 0)) > 0)
345       received += ret;
346     if (received != 4) FATAL("did not receive clen1 information");
347     // fprintf(stderr, "received clen information of %d\n", clen);
348     if (clen < 1)
349       FATAL("did not receive valid compressed len information: %u", clen);
350     buf2 = afl_realloc((void **)&buf2, clen);
351     buf2_len = clen;
352     if (unlikely(!buf2)) { PFATAL("Alloc"); }
353     received = 0;
354     while (received < clen &&
355            (ret = recv(s, buf2 + received, clen - received, 0)) > 0)
356       received += ret;
357     if (received != clen) FATAL("did not receive compressed information");
358     if (libdeflate_deflate_decompress(decompressor, buf2, clen, (char *)*buf,
359                                       size, &received) != LIBDEFLATE_SUCCESS)
360       FATAL("decompression failed");
361       // fprintf(stderr, "DECOMPRESS (%u->%u):\n", clen, received);
362       // for (u32 i = 0; i < clen; i++) fprintf(stderr, "%02x", buf2[i]);
363       // fprintf(stderr, "\n");
364       // for (u32 i = 0; i < received; i++) fprintf(stderr, "%02x",
365       // ((u8*)(*buf))[i]); fprintf(stderr, "\n");
366 #else
367     FATAL("Received compressed data but not compiled with compression support");
368 #endif
369 
370   }
371 
372   // fprintf(stderr, "receiving testcase %p %p max %u\n", buf, *buf, *max_len);
373   if (received != size)
374     FATAL("did not receive testcase data %lu != %u, %d", received, size, ret);
375   // fprintf(stderr, "received testcase\n");
376   return size;
377 
378 }
379 
380 /* Main entry point */
381 
main(int argc,char ** argv_orig,char ** envp)382 int main(int argc, char **argv_orig, char **envp) {
383 
384   s32    opt, s, sock, on = 1, port = -1;
385   u8     mem_limit_given = 0, timeout_given = 0, unicorn_mode = 0, use_wine = 0;
386   char **use_argv;
387   struct sockaddr_in6 serveraddr, clientaddr;
388   int                 addrlen = sizeof(clientaddr);
389   char                str[INET6_ADDRSTRLEN];
390   char **             argv = argv_cpy_dup(argc, argv_orig);
391   u8 *                send_buf;
392 #ifdef USE_DEFLATE
393   u32 *lenptr;
394 #endif
395 
396   afl_forkserver_t  fsrv_var = {0};
397   afl_forkserver_t *fsrv = &fsrv_var;
398   afl_fsrv_init(fsrv);
399   map_size = get_map_size();
400   fsrv->map_size = map_size;
401 
402   if ((send_buf = malloc(map_size + 4)) == NULL) PFATAL("malloc");
403 
404   while ((opt = getopt(argc, argv, "+i:f:m:t:QUWh")) > 0) {
405 
406     switch (opt) {
407 
408       case 'i':
409 
410         if (port > 0) { FATAL("Multiple -i options not supported"); }
411         port = atoi(optarg);
412         if (port < 1 || port > 65535)
413           FATAL("invalid port definition, must be between 1-65535: %s", optarg);
414         break;
415 
416       case 'f':
417 
418         if (out_file) { FATAL("Multiple -f options not supported"); }
419         fsrv->use_stdin = 0;
420         out_file = optarg;
421         break;
422 
423       case 'm': {
424 
425         u8 suffix = 'M';
426 
427         if (mem_limit_given) { FATAL("Multiple -m options not supported"); }
428         mem_limit_given = 1;
429 
430         if (!optarg) { FATAL("Wrong usage of -m"); }
431 
432         if (!strcmp(optarg, "none")) {
433 
434           fsrv->mem_limit = 0;
435           break;
436 
437         }
438 
439         if (sscanf(optarg, "%llu%c", &fsrv->mem_limit, &suffix) < 1 ||
440             optarg[0] == '-') {
441 
442           FATAL("Bad syntax used for -m");
443 
444         }
445 
446         switch (suffix) {
447 
448           case 'T':
449             fsrv->mem_limit *= 1024 * 1024;
450             break;
451           case 'G':
452             fsrv->mem_limit *= 1024;
453             break;
454           case 'k':
455             fsrv->mem_limit /= 1024;
456             break;
457           case 'M':
458             break;
459 
460           default:
461             FATAL("Unsupported suffix or bad syntax for -m");
462 
463         }
464 
465         if (fsrv->mem_limit < 5) { FATAL("Dangerously low value of -m"); }
466 
467         if (sizeof(rlim_t) == 4 && fsrv->mem_limit > 2000) {
468 
469           FATAL("Value of -m out of range on 32-bit systems");
470 
471         }
472 
473       }
474 
475       break;
476 
477       case 't':
478 
479         if (timeout_given) { FATAL("Multiple -t options not supported"); }
480         timeout_given = 1;
481 
482         if (!optarg) { FATAL("Wrong usage of -t"); }
483 
484         fsrv->exec_tmout = atoi(optarg);
485 
486         if (fsrv->exec_tmout < 10 || optarg[0] == '-') {
487 
488           FATAL("Dangerously low value of -t");
489 
490         }
491 
492         break;
493 
494       case 'Q':
495 
496         if (fsrv->qemu_mode) { FATAL("Multiple -Q options not supported"); }
497         if (!mem_limit_given) { fsrv->mem_limit = MEM_LIMIT_QEMU; }
498 
499         fsrv->qemu_mode = 1;
500         break;
501 
502       case 'U':
503 
504         if (unicorn_mode) { FATAL("Multiple -Q options not supported"); }
505         if (!mem_limit_given) { fsrv->mem_limit = MEM_LIMIT_UNICORN; }
506 
507         unicorn_mode = 1;
508         break;
509 
510       case 'W':                                           /* Wine+QEMU mode */
511 
512         if (use_wine) { FATAL("Multiple -W options not supported"); }
513         fsrv->qemu_mode = 1;
514         use_wine = 1;
515 
516         if (!mem_limit_given) { fsrv->mem_limit = 0; }
517 
518         break;
519 
520       case 'h':
521         usage(argv[0]);
522         return -1;
523         break;
524 
525       default:
526         usage(argv[0]);
527 
528     }
529 
530   }
531 
532   if (optind == argc || port < 1) { usage(argv[0]); }
533 
534   check_environment_vars(envp);
535 
536   sharedmem_t shm = {0};
537   fsrv->trace_bits = afl_shm_init(&shm, map_size, 0);
538 
539   in_data = afl_realloc((void **)&in_data, 65536);
540   if (unlikely(!in_data)) { PFATAL("Alloc"); }
541 
542   atexit(at_exit_handler);
543   setup_signal_handlers();
544 
545   set_up_environment(fsrv);
546 
547   fsrv->target_path = find_binary(argv[optind]);
548   detect_file_args(argv + optind, out_file, &fsrv->use_stdin);
549 
550   if (fsrv->qemu_mode) {
551 
552     if (use_wine) {
553 
554       use_argv = get_wine_argv(argv[0], &fsrv->target_path, argc - optind,
555                                argv + optind);
556 
557     } else {
558 
559       use_argv = get_qemu_argv(argv[0], &fsrv->target_path, argc - optind,
560                                argv + optind);
561 
562     }
563 
564   } else {
565 
566     use_argv = argv + optind;
567 
568   }
569 
570   if ((sock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) PFATAL("socket() failed");
571 
572 #ifdef SO_REUSEADDR
573   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) {
574 
575     WARNF("setsockopt(SO_REUSEADDR) failed");
576 
577   }
578 
579 #endif
580 
581 #ifdef SO_PRIORITY
582   int priority = 7;
583   if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) <
584       0) {
585 
586     priority = 6;
587     if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) <
588         0)
589       WARNF("could not set priority on socket");
590 
591   }
592 
593 #endif
594 
595   memset(&serveraddr, 0, sizeof(serveraddr));
596   serveraddr.sin6_family = AF_INET6;
597   serveraddr.sin6_port = htons(port);
598   serveraddr.sin6_addr = in6addr_any;
599 
600   if (bind(sock, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
601     PFATAL("bind() failed");
602 
603   if (listen(sock, 1) < 0) { PFATAL("listen() failed"); }
604 
605   afl_fsrv_start(
606       fsrv, use_argv, &stop_soon,
607       (get_afl_env("AFL_DEBUG_CHILD") || get_afl_env("AFL_DEBUG_CHILD_OUTPUT"))
608           ? 1
609           : 0);
610 
611 #ifdef USE_DEFLATE
612   compressor = libdeflate_alloc_compressor(1);
613   decompressor = libdeflate_alloc_decompressor();
614   buf2 = afl_realloc((void **)&buf2, map_size + 16);
615   buf2_len = map_size + 16;
616   if (unlikely(!buf2)) { PFATAL("alloc"); }
617   lenptr = (u32 *)(buf2 + 4);
618   fprintf(stderr, "Compiled with compression support\n");
619 #endif
620 
621   fprintf(stderr,
622           "Waiting for incoming connection from afl-network-client on port %d "
623           "...\n",
624           port);
625 
626   if ((s = accept(sock, NULL, NULL)) < 0) { PFATAL("accept() failed"); }
627   fprintf(stderr, "Received connection, starting ...\n");
628 
629 #ifdef SO_PRIORITY
630   priority = 7;
631   if (setsockopt(s, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) < 0) {
632 
633     priority = 6;
634     if (setsockopt(s, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) < 0)
635       WARNF("could not set priority on socket");
636 
637   }
638 
639 #endif
640 
641   while ((in_len = recv_testcase(s, (void **)&in_data)) > 0) {
642 
643     // fprintf(stderr, "received %u\n", in_len);
644     (void)run_target(fsrv, use_argv, in_data, in_len, 1);
645 
646     memcpy(send_buf + 4, fsrv->trace_bits, fsrv->map_size);
647 
648 #ifdef USE_DEFLATE
649     memcpy(buf2, &fsrv->child_status, 4);
650     *lenptr = (u32)libdeflate_deflate_compress(
651         compressor, send_buf + 4, fsrv->map_size, buf2 + 8, buf2_len - 8);
652     // fprintf(stderr, "COMPRESS (%u->%u): ", fsrv->map_size, *lenptr);
653     // for (u32 i = 0; i < fsrv->map_size; i++) fprintf(stderr, "%02x",
654     // fsrv->trace_bits[i]); fprintf(stderr, "\n");
655     if (send(s, buf2, *lenptr + 8, 0) != 8 + *lenptr)
656       FATAL("could not send data");
657 #else
658     memcpy(send_buf, &fsrv->child_status, 4);
659     if (send(s, send_buf, fsrv->map_size + 4, 0) != 4 + fsrv->map_size)
660       FATAL("could not send data");
661 #endif
662 
663     // fprintf(stderr, "sent result\n");
664 
665   }
666 
667   unlink(out_file);
668   if (out_file) { ck_free(out_file); }
669   out_file = NULL;
670 
671   afl_shm_deinit(&shm);
672   afl_fsrv_deinit(fsrv);
673   if (fsrv->target_path) { ck_free(fsrv->target_path); }
674   afl_free(in_data);
675 #if USE_DEFLATE
676   afl_free(buf2);
677   libdeflate_free_compressor(compressor);
678   libdeflate_free_decompressor(decompressor);
679 #endif
680 
681   argv_cpy_free(argv);
682 
683   exit(0);
684 
685 }
686 
687