xref: /aosp_15_r20/external/AFLplusplus/utils/afl_network_proxy/afl-network-server.c (revision 08b48e0b10e97b33e7b60c5b6e2243bd915777f2)
1 /*
2    american fuzzy lop++ - network proxy server
3    -------------------------------------------
4 
5    Originally written by Michal Zalewski
6 
7    Forkserver design by Jann Horn <[email protected]>
8 
9    Now maintained by Marc Heuse <[email protected]>,
10                         Heiko Eißfeldt <[email protected]> and
11                         Andrea Fioraldi <[email protected]> and
12                         Dominik Maier <[email protected]>
13 
14    Copyright 2016, 2017 Google Inc. All rights reserved.
15    Copyright 2019-2024 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     fsrv->out_file = out_file;
177 
178   }
179 
180   unlink(out_file);
181 
182   fsrv->out_fd = open(out_file, O_RDWR | O_CREAT | O_EXCL, 0600);
183 
184   if (fsrv->out_fd < 0) { PFATAL("Unable to create '%s'", out_file); }
185 
186   /* Set sane defaults... */
187 
188   x = get_afl_env("ASAN_OPTIONS");
189 
190   if (x) {
191 
192     if (!strstr(x, "abort_on_error=1")) {
193 
194       FATAL("Custom ASAN_OPTIONS set without abort_on_error=1 - please fix!");
195 
196     }
197 
198     if (!getenv("AFL_DEBUG") && !strstr(x, "symbolize=0")) {
199 
200       FATAL("Custom ASAN_OPTIONS set without symbolize=0 - please fix!");
201 
202     }
203 
204   }
205 
206   x = get_afl_env("MSAN_OPTIONS");
207 
208   if (x) {
209 
210     if (!strstr(x, "exit_code=" STRINGIFY(MSAN_ERROR))) {
211 
212       FATAL("Custom MSAN_OPTIONS set without exit_code=" STRINGIFY(
213           MSAN_ERROR) " - please fix!");
214 
215     }
216 
217     if (!getenv("AFL_DEBUG") && !strstr(x, "symbolize=0")) {
218 
219       FATAL("Custom MSAN_OPTIONS set without symbolize=0 - please fix!");
220 
221     }
222 
223   }
224 
225   set_sanitizer_defaults();
226 
227   if (get_afl_env("AFL_PRELOAD")) {
228 
229     if (fsrv->qemu_mode) {
230 
231       /* afl-qemu-trace takes care of converting AFL_PRELOAD. */
232 
233     } else {
234 
235       setenv("LD_PRELOAD", getenv("AFL_PRELOAD"), 1);
236       setenv("DYLD_INSERT_LIBRARIES", getenv("AFL_PRELOAD"), 1);
237 
238     }
239 
240   }
241 
242 }
243 
244 /* Setup signal handlers, duh. */
245 
setup_signal_handlers(void)246 static void setup_signal_handlers(void) {
247 
248   struct sigaction sa;
249 
250   sa.sa_handler = NULL;
251   sa.sa_flags = SA_RESTART;
252   sa.sa_sigaction = NULL;
253 
254   sigemptyset(&sa.sa_mask);
255 
256   /* Various ways of saying "stop". */
257 
258   sa.sa_handler = handle_stop_sig;
259   sigaction(SIGHUP, &sa, NULL);
260   sigaction(SIGINT, &sa, NULL);
261   sigaction(SIGTERM, &sa, NULL);
262 
263 }
264 
265 /* Display usage hints. */
266 
usage(u8 * argv0)267 static void usage(u8 *argv0) {
268 
269   SAYF(
270       "\n%s [ options ] -- /path/to/target_app [ ... ]\n\n"
271 
272       "Required parameters:\n"
273 
274       "  -i port       - the port to listen for the client to connect to\n\n"
275 
276       "Execution control settings:\n"
277 
278       "  -f file       - input file read by the tested program (stdin)\n"
279       "  -t msec       - timeout for each run (%d ms)\n"
280       "  -m megs       - memory limit for child process (%d MB)\n"
281       "  -Q            - use binary-only instrumentation (QEMU mode)\n"
282       "  -U            - use unicorn-based instrumentation (Unicorn mode)\n"
283       "  -W            - use qemu-based instrumentation with Wine (Wine "
284       "mode)\n\n"
285 
286       "Environment variables used:\n"
287       "TMPDIR: directory to use for temporary input files\n"
288       "ASAN_OPTIONS: custom settings for ASAN\n"
289       "              (must contain abort_on_error=1 and symbolize=0)\n"
290       "MSAN_OPTIONS: custom settings for MSAN\n"
291       "              (must contain exitcode="STRINGIFY(MSAN_ERROR)" and symbolize=0)\n"
292       "AFL_MAP_SIZE: the shared memory size for that target. must be >= the size\n"
293       "              the target was compiled for\n"
294       "AFL_PRELOAD:  LD_PRELOAD / DYLD_INSERT_LIBRARIES settings for target\n"
295 
296       , argv0, EXEC_TIMEOUT, MEM_LIMIT);
297 
298   exit(1);
299 
300 }
301 
recv_testcase(int s,void ** buf)302 int recv_testcase(int s, void **buf) {
303 
304   u32    size;
305   s32    ret;
306   size_t received;
307 
308   received = 0;
309   while (received < 4 && (ret = recv(s, &size + received, 4 - received, 0)) > 0)
310     received += ret;
311   if (received != 4) FATAL("did not receive size information");
312   if (size == 0) FATAL("did not receive valid size information");
313   // fprintf(stderr, "received size information of %d\n", size);
314 
315   if ((size & 0xff000000) != 0xff000000) {
316 
317     *buf = afl_realloc(buf, size);
318     if (unlikely(!*buf)) { PFATAL("Alloc"); }
319     received = 0;
320     // fprintf(stderr, "unCOMPRESS (%u)\n", size);
321     while (received < size &&
322            (ret = recv(s, ((char *)*buf) + received, size - received, 0)) > 0)
323       received += ret;
324 
325   } else {
326 
327 #ifdef USE_DEFLATE
328     u32 clen;
329     size -= 0xff000000;
330     *buf = afl_realloc(buf, size);
331     if (unlikely(!*buf)) { PFATAL("Alloc"); }
332     received = 0;
333     while (received < 4 &&
334            (ret = recv(s, &clen + received, 4 - received, 0)) > 0)
335       received += ret;
336     if (received != 4) FATAL("did not receive clen1 information");
337     // fprintf(stderr, "received clen information of %d\n", clen);
338     if (clen < 1)
339       FATAL("did not receive valid compressed len information: %u", clen);
340     buf2 = afl_realloc((void **)&buf2, clen);
341     buf2_len = clen;
342     if (unlikely(!buf2)) { PFATAL("Alloc"); }
343     received = 0;
344     while (received < clen &&
345            (ret = recv(s, buf2 + received, clen - received, 0)) > 0)
346       received += ret;
347     if (received != clen) FATAL("did not receive compressed information");
348     if (libdeflate_deflate_decompress(decompressor, buf2, clen, (char *)*buf,
349                                       size, &received) != LIBDEFLATE_SUCCESS)
350       FATAL("decompression failed");
351       // fprintf(stderr, "DECOMPRESS (%u->%u):\n", clen, received);
352       // for (u32 i = 0; i < clen; i++) fprintf(stderr, "%02x", buf2[i]);
353       // fprintf(stderr, "\n");
354       // for (u32 i = 0; i < received; i++) fprintf(stderr, "%02x",
355       // ((u8*)(*buf))[i]); fprintf(stderr, "\n");
356 #else
357     FATAL("Received compressed data but not compiled with compression support");
358 #endif
359 
360   }
361 
362   // fprintf(stderr, "receiving testcase %p %p max %u\n", buf, *buf, *max_len);
363   if (received != size)
364     FATAL("did not receive testcase data %lu != %u, %d", received, size, ret);
365   // fprintf(stderr, "received testcase\n");
366   return size;
367 
368 }
369 
370 /* Main entry point */
371 
main(int argc,char ** argv_orig,char ** envp)372 int main(int argc, char **argv_orig, char **envp) {
373 
374   s32    opt, s, sock, on = 1, port = -1;
375   u8     mem_limit_given = 0, timeout_given = 0, unicorn_mode = 0, use_wine = 0;
376   char **use_argv;
377   struct sockaddr_in6 serveraddr, clientaddr;
378   int                 addrlen = sizeof(clientaddr);
379   char                str[INET6_ADDRSTRLEN];
380   char              **argv = argv_cpy_dup(argc, argv_orig);
381   u8                 *send_buf;
382 #ifdef USE_DEFLATE
383   u32 *lenptr;
384 #endif
385 
386   afl_forkserver_t  fsrv_var = {0};
387   afl_forkserver_t *fsrv = &fsrv_var;
388   afl_fsrv_init(fsrv);
389   map_size = get_map_size();
390   fsrv->map_size = map_size;
391 
392   if ((send_buf = malloc(map_size + 4)) == NULL) PFATAL("malloc");
393 
394   while ((opt = getopt(argc, argv, "+i:f:m:t:QUWh")) > 0) {
395 
396     switch (opt) {
397 
398       case 'i':
399 
400         if (port > 0) { FATAL("Multiple -i options not supported"); }
401         port = atoi(optarg);
402         if (port < 1 || port > 65535)
403           FATAL("invalid port definition, must be between 1-65535: %s", optarg);
404         break;
405 
406       case 'f':
407 
408         if (out_file) { FATAL("Multiple -f options not supported"); }
409         fsrv->use_stdin = 0;
410         out_file = optarg;
411         break;
412 
413       case 'm': {
414 
415         u8 suffix = 'M';
416 
417         if (mem_limit_given) { FATAL("Multiple -m options not supported"); }
418         mem_limit_given = 1;
419 
420         if (!optarg) { FATAL("Wrong usage of -m"); }
421 
422         if (!strcmp(optarg, "none")) {
423 
424           fsrv->mem_limit = 0;
425           break;
426 
427         }
428 
429         if (sscanf(optarg, "%llu%c", &fsrv->mem_limit, &suffix) < 1 ||
430             optarg[0] == '-') {
431 
432           FATAL("Bad syntax used for -m");
433 
434         }
435 
436         switch (suffix) {
437 
438           case 'T':
439             fsrv->mem_limit *= 1024 * 1024;
440             break;
441           case 'G':
442             fsrv->mem_limit *= 1024;
443             break;
444           case 'k':
445             fsrv->mem_limit /= 1024;
446             break;
447           case 'M':
448             break;
449 
450           default:
451             FATAL("Unsupported suffix or bad syntax for -m");
452 
453         }
454 
455         if (fsrv->mem_limit < 5) { FATAL("Dangerously low value of -m"); }
456 
457         if (sizeof(rlim_t) == 4 && fsrv->mem_limit > 2000) {
458 
459           FATAL("Value of -m out of range on 32-bit systems");
460 
461         }
462 
463       }
464 
465       break;
466 
467       case 't':
468 
469         if (timeout_given) { FATAL("Multiple -t options not supported"); }
470         timeout_given = 1;
471 
472         if (!optarg) { FATAL("Wrong usage of -t"); }
473 
474         fsrv->exec_tmout = atoi(optarg);
475 
476         if (fsrv->exec_tmout < 10 || optarg[0] == '-') {
477 
478           FATAL("Dangerously low value of -t");
479 
480         }
481 
482         break;
483 
484       case 'Q':
485 
486         if (fsrv->qemu_mode) { FATAL("Multiple -Q options not supported"); }
487         if (!mem_limit_given) { fsrv->mem_limit = MEM_LIMIT_QEMU; }
488 
489         fsrv->qemu_mode = 1;
490         break;
491 
492       case 'U':
493 
494         if (unicorn_mode) { FATAL("Multiple -Q options not supported"); }
495         if (!mem_limit_given) { fsrv->mem_limit = MEM_LIMIT_UNICORN; }
496 
497         unicorn_mode = 1;
498         break;
499 
500       case 'W':                                           /* Wine+QEMU mode */
501 
502         if (use_wine) { FATAL("Multiple -W options not supported"); }
503         fsrv->qemu_mode = 1;
504         use_wine = 1;
505 
506         if (!mem_limit_given) { fsrv->mem_limit = 0; }
507 
508         break;
509 
510       case 'h':
511         usage(argv[0]);
512         return -1;
513         break;
514 
515       default:
516         usage(argv[0]);
517 
518     }
519 
520   }
521 
522   if (optind == argc || port < 1) { usage(argv[0]); }
523 
524   check_environment_vars(envp);
525 
526   sharedmem_t shm = {0};
527   fsrv->trace_bits = afl_shm_init(&shm, map_size, 0);
528 
529   in_data = afl_realloc((void **)&in_data, 65536);
530   if (unlikely(!in_data)) { PFATAL("Alloc"); }
531 
532   atexit(at_exit_handler);
533   setup_signal_handlers();
534 
535   set_up_environment(fsrv);
536 
537   fsrv->target_path = find_binary(argv[optind]);
538   detect_file_args(argv + optind, out_file, &fsrv->use_stdin);
539 
540   if (fsrv->qemu_mode) {
541 
542     if (use_wine) {
543 
544       use_argv = get_wine_argv(argv[0], &fsrv->target_path, argc - optind,
545                                argv + optind);
546 
547     } else {
548 
549       use_argv = get_qemu_argv(argv[0], &fsrv->target_path, argc - optind,
550                                argv + optind);
551 
552     }
553 
554   } else {
555 
556     use_argv = argv + optind;
557 
558   }
559 
560   if ((sock = socket(AF_INET6, SOCK_STREAM, 0)) < 0) PFATAL("socket() failed");
561 
562 #ifdef SO_REUSEADDR
563   if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&on, sizeof(on)) < 0) {
564 
565     WARNF("setsockopt(SO_REUSEADDR) failed");
566 
567   }
568 
569 #endif
570 
571 #ifdef SO_PRIORITY
572   int priority = 7;
573   if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) <
574       0) {
575 
576     priority = 6;
577     if (setsockopt(sock, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) <
578         0)
579       WARNF("could not set priority on socket");
580 
581   }
582 
583 #endif
584 
585   memset(&serveraddr, 0, sizeof(serveraddr));
586   serveraddr.sin6_family = AF_INET6;
587   serveraddr.sin6_port = htons(port);
588   serveraddr.sin6_addr = in6addr_any;
589 
590   if (bind(sock, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0)
591     PFATAL("bind() failed");
592 
593   if (listen(sock, 1) < 0) { PFATAL("listen() failed"); }
594 
595   afl_fsrv_start(
596       fsrv, use_argv, &stop_soon,
597       (get_afl_env("AFL_DEBUG_CHILD") || get_afl_env("AFL_DEBUG_CHILD_OUTPUT"))
598           ? 1
599           : 0);
600 
601 #ifdef USE_DEFLATE
602   compressor = libdeflate_alloc_compressor(1);
603   decompressor = libdeflate_alloc_decompressor();
604   buf2 = afl_realloc((void **)&buf2, map_size + 16);
605   buf2_len = map_size + 16;
606   if (unlikely(!buf2)) { PFATAL("alloc"); }
607   lenptr = (u32 *)(buf2 + 4);
608   fprintf(stderr, "Compiled with compression support\n");
609 #endif
610 
611   fprintf(stderr,
612           "Waiting for incoming connection from afl-network-client on port %d "
613           "...\n",
614           port);
615 
616   if ((s = accept(sock, NULL, NULL)) < 0) { PFATAL("accept() failed"); }
617   fprintf(stderr, "Received connection, starting ...\n");
618 
619 #ifdef SO_PRIORITY
620   priority = 7;
621   if (setsockopt(s, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) < 0) {
622 
623     priority = 6;
624     if (setsockopt(s, SOL_SOCKET, SO_PRIORITY, &priority, sizeof(priority)) < 0)
625       WARNF("could not set priority on socket");
626 
627   }
628 
629 #endif
630 
631   while ((in_len = recv_testcase(s, (void **)&in_data)) > 0) {
632 
633     // fprintf(stderr, "received %u\n", in_len);
634     (void)run_target(fsrv, use_argv, in_data, in_len, 1);
635 
636     memcpy(send_buf + 4, fsrv->trace_bits, fsrv->map_size);
637 
638 #ifdef USE_DEFLATE
639     memcpy(buf2, &fsrv->child_status, 4);
640     *lenptr = (u32)libdeflate_deflate_compress(
641         compressor, send_buf + 4, fsrv->map_size, buf2 + 8, buf2_len - 8);
642     // fprintf(stderr, "COMPRESS (%u->%u): ", fsrv->map_size, *lenptr);
643     // for (u32 i = 0; i < fsrv->map_size; i++) fprintf(stderr, "%02x",
644     // fsrv->trace_bits[i]); fprintf(stderr, "\n");
645     if (send(s, buf2, *lenptr + 8, 0) != 8 + *lenptr)
646       FATAL("could not send data");
647 #else
648     memcpy(send_buf, &fsrv->child_status, 4);
649     if (send(s, send_buf, fsrv->map_size + 4, 0) != 4 + fsrv->map_size)
650       FATAL("could not send data");
651 #endif
652 
653     // fprintf(stderr, "sent result\n");
654 
655   }
656 
657   unlink(out_file);
658   if (out_file) { ck_free(out_file); }
659   out_file = NULL;
660 
661   afl_shm_deinit(&shm);
662   afl_fsrv_deinit(fsrv);
663   if (fsrv->target_path) { ck_free(fsrv->target_path); }
664   afl_free(in_data);
665 #if USE_DEFLATE
666   afl_free(buf2);
667   libdeflate_free_compressor(compressor);
668   libdeflate_free_decompressor(decompressor);
669 #endif
670 
671   argv_cpy_free(argv);
672 
673   exit(0);
674 
675 }
676 
677