source: zzuf/trunk/src/zzuf.c @ 1727

Last change on this file since 1727 was 1727, checked in by Sam Hocevar, 16 years ago
  • Only include <sys/time.h> conditionally.
  • Property svn:keywords set to Id
File size: 33.1 KB
Line 
1/*
2 *  zzuf - general purpose fuzzer
3 *  Copyright (c) 2002, 2007 Sam Hocevar <sam@zoy.org>
4 *                All Rights Reserved
5 *
6 *  $Id: zzuf.c 1727 2007-02-01 15:57:10Z sam $
7 *
8 *  This program is free software. It comes without any warranty, to
9 *  the extent permitted by applicable law. You can redistribute it
10 *  and/or modify it under the terms of the Do What The Fuck You Want
11 *  To Public License, Version 2, as published by Sam Hocevar. See
12 *  http://sam.zoy.org/wtfpl/COPYING for more details.
13 */
14
15/*
16 *  main.c: main program
17 */
18
19#include "config.h"
20
21#if defined HAVE_STDINT_H
22#   include <stdint.h>
23#elif defined HAVE_INTTYPES_H
24#   include <inttypes.h>
25#endif
26#if defined HAVE_GETOPT_H
27#   include <getopt.h>
28#endif
29#include <stdio.h>
30#include <stdlib.h>
31#include <unistd.h>
32#if defined HAVE_REGEX_H
33#   include <regex.h>
34#endif
35#if defined HAVE_WINDOWS_H
36#   include <windows.h>
37#endif
38#if defined HAVE_WINSOCK2_H
39#   include <winsock2.h>
40#endif
41#if defined HAVE_IO_H
42#   include <io.h>
43#endif
44#include <string.h>
45#include <fcntl.h>
46#include <errno.h>
47#include <signal.h>
48#if defined HAVE_SYS_WAIT_H
49#   include <sys/wait.h>
50#endif
51#if defined HAVE_SYS_RESOURCE_H
52#   include <sys/resource.h>
53#endif
54
55#include "libzzuf.h"
56#include "opts.h"
57#include "random.h"
58#include "fd.h"
59#include "fuzz.h"
60#include "md5.h"
61#include "timer.h"
62
63#if !defined SIGKILL
64#   define SIGKILL 9
65#endif
66
67/* We use file descriptor 17 as the debug channel */
68#define DEBUG_FILENO 17
69#define DEBUG_FILENO_STR "17"
70
71static void loop_stdin(struct opts *);
72static int run_process(char const *, char *[]);
73
74static void spawn_children(struct opts *);
75static void clean_children(struct opts *);
76static void read_children(struct opts *);
77
78#if !defined HAVE_SETENV
79static void setenv(char const *, char const *, int);
80#endif
81#if defined HAVE_WAITPID
82static char const *sig2str(int);
83#endif
84#if defined HAVE_WINDOWS_H
85static int dll_inject(void *, void *);
86static void *get_entry(char const *);
87#endif
88static void finfo(FILE *, struct opts *, uint32_t);
89#if defined HAVE_REGEX_H
90static char *merge_regex(char *, char *);
91static char *merge_file(char *, char *);
92#endif
93static void version(void);
94#if defined HAVE_GETOPT_H
95static void usage(void);
96#endif
97
98#if defined HAVE_WINDOWS_H
99static inline void addcpy(void *buf, void *x)
100{
101    memcpy(buf, &x, 4);
102}
103#endif
104
105#define ZZUF_FD_SET(fd, p_fdset, maxfd) \
106    if(fd >= 0) \
107    { \
108        FD_SET((unsigned int)fd, p_fdset); \
109        if(fd > maxfd) \
110            maxfd = fd; \
111    }
112
113#define ZZUF_FD_ISSET(fd, p_fdset) \
114    ((fd >= 0) && (FD_ISSET(fd, p_fdset)))
115
116int main(int argc, char *argv[])
117{
118    struct opts _opts, *opts = &_opts;
119    char *tmp;
120#if defined HAVE_REGEX_H
121    char *include = NULL, *exclude = NULL;
122    int cmdline = 0;
123#endif
124    int i;
125
126    _zz_opts_init(opts);
127
128#if defined HAVE_GETOPT_H
129    for(;;)
130    {
131#   if defined HAVE_REGEX_H
132#       define OPTSTR "Ab:B:cC:dD:E:f:F:iI:mM:nP:qr:R:s:ST:vxhV"
133#   else
134#       define OPTSTR "Ab:B:C:dD:f:F:imM:nP:qr:R:s:ST:vxhV"
135#   endif
136#   if defined HAVE_GETOPT_LONG
137#       define MOREINFO "Try `%s --help' for more information.\n"
138        int option_index = 0;
139        static struct option long_options[] =
140        {
141            /* Long option, needs arg, flag, short option */
142            { "autoinc",     0, NULL, 'A' },
143            { "bytes",       1, NULL, 'b' },
144            { "max-bytes",   1, NULL, 'B' },
145#if defined HAVE_REGEX_H
146            { "cmdline",     0, NULL, 'c' },
147#endif
148            { "max-crashes", 1, NULL, 'C' },
149            { "debug",       0, NULL, 'd' },
150            { "delay",       1, NULL, 'D' },
151#if defined HAVE_REGEX_H
152            { "exclude",     1, NULL, 'E' },
153#endif
154            { "fuzzing",     1, NULL, 'f' },
155            { "max-forks",   1, NULL, 'F' },
156            { "stdin",       0, NULL, 'i' },
157#if defined HAVE_REGEX_H
158            { "include",     1, NULL, 'I' },
159#endif
160            { "md5",         0, NULL, 'm' },
161            { "max-memory",  1, NULL, 'M' },
162            { "network",     0, NULL, 'n' },
163            { "protect",     1, NULL, 'P' },
164            { "quiet",       0, NULL, 'q' },
165            { "ratio",       1, NULL, 'r' },
166            { "refuse",      1, NULL, 'R' },
167            { "seed",        1, NULL, 's' },
168            { "signal",      0, NULL, 'S' },
169            { "max-time",    1, NULL, 'T' },
170            { "verbose",     0, NULL, 'v' },
171            { "check-exit",  0, NULL, 'x' },
172            { "help",        0, NULL, 'h' },
173            { "version",     0, NULL, 'V' },
174            { NULL,          0, NULL,  0  }
175        };
176        int c = getopt_long(argc, argv, OPTSTR, long_options, &option_index);
177#   else
178#       define MOREINFO "Try `%s -h' for more information.\n"
179        int c = getopt(argc, argv, OPTSTR);
180#   endif
181        if(c == -1)
182            break;
183
184        switch(c)
185        {
186        case 'A': /* --autoinc */
187            setenv("ZZUF_AUTOINC", "1", 1);
188            break;
189        case 'b': /* --bytes */
190            opts->bytes = optarg;
191            break;
192        case 'B': /* --max-bytes */
193            opts->maxbytes = atoi(optarg);
194            break;
195#if defined HAVE_REGEX_H
196        case 'c': /* --cmdline */
197            cmdline = 1;
198            break;
199#endif
200        case 'C': /* --max-crashes */
201            opts->maxcrashes = atoi(optarg);
202            if(opts->maxcrashes <= 0)
203                opts->maxcrashes = 0;
204            break;
205        case 'd': /* --debug */
206            setenv("ZZUF_DEBUG", DEBUG_FILENO_STR, 1);
207            break;
208        case 'D': /* --delay */
209            opts->delay = (int64_t)(atof(optarg) * 1000000.0);
210            break;
211#if defined HAVE_REGEX_H
212        case 'E': /* --exclude */
213            exclude = merge_regex(exclude, optarg);
214            if(!exclude)
215            {
216                printf("%s: invalid regex -- `%s'\n", argv[0], optarg);
217                _zz_opts_fini(opts);
218                return EXIT_FAILURE;
219            }
220            break;
221#endif
222        case 'f': /* --fuzzing */
223            opts->fuzzing = optarg;
224            break;
225        case 'F': /* --max-forks */
226            opts->maxchild = atoi(optarg) > 1 ? atoi(optarg) : 1;
227            break;
228        case 'i': /* --stdin */
229            setenv("ZZUF_STDIN", "1", 1);
230            break;
231#if defined HAVE_REGEX_H
232        case 'I': /* --include */
233            include = merge_regex(include, optarg);
234            if(!include)
235            {
236                printf("%s: invalid regex -- `%s'\n", argv[0], optarg);
237                _zz_opts_fini(opts);
238                return EXIT_FAILURE;
239            }
240            break;
241#endif
242        case 'm': /* --md5 */
243            opts->md5 = 1;
244            break;
245#if defined HAVE_SETRLIMIT
246        case 'M': /* --max-memory */
247            setenv("ZZUF_MEMORY", "1", 1);
248            opts->maxmem = atoi(optarg);
249            break;
250#endif
251        case 'n': /* --network */
252            setenv("ZZUF_NETWORK", "1", 1);
253            break;
254        case 'P': /* --protect */
255            opts->protect = optarg;
256            break;
257        case 'q': /* --quiet */
258            opts->quiet = 1;
259            break;
260        case 'r': /* --ratio */
261            tmp = strchr(optarg, ':');
262            opts->minratio = atof(optarg);
263            opts->maxratio = tmp ? atof(tmp + 1) : opts->minratio;
264            break;
265        case 'R': /* --refuse */
266            opts->refuse = optarg;
267            break;
268        case 's': /* --seed */
269            tmp = strchr(optarg, ':');
270            opts->seed = atol(optarg);
271            opts->endseed = tmp ? (uint32_t)atoi(tmp + 1) : opts->seed + 1;
272            break;
273        case 'S': /* --signal */
274            setenv("ZZUF_SIGNAL", "1", 1);
275            break;
276        case 'T': /* --max-time */
277            opts->maxtime = (int64_t)(atof(optarg) * 1000000.0);
278            break;
279        case 'x': /* --check-exit */
280            opts->checkexit = 1;
281            break;
282        case 'v': /* --verbose */
283            opts->verbose = 1;
284            break;
285        case 'h': /* --help */
286            usage();
287            _zz_opts_fini(opts);
288            return 0;
289        case 'V': /* --version */
290            version();
291            _zz_opts_fini(opts);
292            return 0;
293        default:
294            printf("%s: invalid option -- %c\n", argv[0], c);
295            printf(MOREINFO, argv[0]);
296            _zz_opts_fini(opts);
297            return EXIT_FAILURE;
298        }
299    }
300#else
301#   define MOREINFO "Usage: %s message...\n"
302    int optind = 1;
303#endif
304
305    _zz_setratio(opts->minratio, opts->maxratio);
306    _zz_setseed(opts->seed);
307
308    /* If asked to read from the standard input */
309    if(optind >= argc)
310    {
311        if(opts->endseed != opts->seed + 1)
312        {
313            printf("%s: seed ranges are incompatible with stdin fuzzing\n",
314                   argv[0]);
315            printf(MOREINFO, argv[0]);
316            _zz_opts_fini(opts);
317            return EXIT_FAILURE;
318        }
319
320        loop_stdin(opts);
321
322        _zz_opts_fini(opts);
323        return EXIT_SUCCESS;
324    }
325
326    /* If asked to launch programs */
327#if defined HAVE_REGEX_H
328    if(cmdline)
329    {
330        int dashdash = 0;
331
332        for(i = optind + 1; i < argc; i++)
333        {
334            if(dashdash)
335                include = merge_file(include, argv[i]);
336            else if(!strcmp("--", argv[i]))
337                dashdash = 1;
338            else if(argv[i][0] != '-')
339                include = merge_file(include, argv[i]);
340        }
341    }
342
343    if(include)
344        setenv("ZZUF_INCLUDE", include, 1);
345    if(exclude)
346        setenv("ZZUF_EXCLUDE", exclude, 1);
347#endif
348
349    if(opts->fuzzing)
350        setenv("ZZUF_FUZZING", opts->fuzzing, 1);
351    if(opts->bytes)
352        setenv("ZZUF_BYTES", opts->bytes, 1);
353    if(opts->protect)
354        setenv("ZZUF_PROTECT", opts->protect, 1);
355    if(opts->refuse)
356        setenv("ZZUF_REFUSE", opts->refuse, 1);
357
358    /* Allocate memory for children handling */
359    opts->child = malloc(opts->maxchild * sizeof(struct child));
360    for(i = 0; i < opts->maxchild; i++)
361        opts->child[i].status = STATUS_FREE;
362    opts->nchild = 0;
363
364    /* Create new argv */
365    opts->oldargv = argv;
366    opts->newargv = malloc((argc - optind + 1) * sizeof(char *));
367    memcpy(opts->newargv, argv + optind, (argc - optind) * sizeof(char *));
368    opts->newargv[argc - optind] = (char *)NULL;
369
370    /* Main loop */
371    while(opts->nchild || opts->seed < opts->endseed)
372    {
373        /* Spawn new children, if necessary */
374        spawn_children(opts);
375
376        /* Cleanup dead or dying children */
377        clean_children(opts);
378
379        /* Read data from children */
380        read_children(opts);
381
382        if(opts->maxcrashes && opts->crashes >= opts->maxcrashes
383            && opts->nchild == 0)
384            break;
385    }
386
387    /* Clean up */
388    _zz_opts_fini(opts);
389
390    return opts->crashes ? EXIT_FAILURE : EXIT_SUCCESS;   
391}
392
393static void loop_stdin(struct opts *opts)
394{
395    uint8_t md5sum[16];
396    struct md5 *ctx = NULL;
397
398    if(opts->md5)
399        ctx = _zz_md5_init();
400
401    if(opts->fuzzing)
402        _zz_fuzzing(opts->fuzzing);
403    if(opts->bytes)
404        _zz_bytes(opts->bytes);
405    if(opts->protect)
406        _zz_protect(opts->protect);
407    if(opts->refuse)
408        _zz_refuse(opts->refuse);
409
410    _zz_fd_init();
411    _zz_register(0);
412
413    for(;;)
414    {
415        uint8_t buf[BUFSIZ];
416        int ret, off = 0, nw = 0;
417
418        ret = read(0, buf, BUFSIZ);
419        if(ret <= 0)
420            break;
421
422        _zz_fuzz(0, buf, ret);
423        _zz_addpos(0, ret);
424
425        if(opts->md5)
426            _zz_md5_add(ctx, buf, ret);
427        else while(ret)
428        {
429            if((nw = write(1, buf + off, (size_t)ret)) < 0)
430                break;
431            ret -= nw;
432            off += nw;
433        }
434    }
435
436    if(opts->md5)
437    {
438        _zz_md5_fini(md5sum, ctx);
439        finfo(stdout, opts, opts->seed);
440        fprintf(stdout, "%.02x%.02x%.02x%.02x%.02x%.02x%.02x%.02x%.02x%.02x"
441                "%.02x%.02x%.02x%.02x%.02x%.02x\n", md5sum[0], md5sum[1],
442                md5sum[2], md5sum[3], md5sum[4], md5sum[5], md5sum[6],
443                md5sum[7], md5sum[8], md5sum[9], md5sum[10], md5sum[11],
444                md5sum[12], md5sum[13], md5sum[14], md5sum[15]);
445        fflush(stdout);
446    }
447
448    _zz_unregister(0);
449    _zz_fd_fini();
450}
451
452static void finfo(FILE *fp, struct opts *opts, uint32_t seed)
453{
454    if(opts->minratio == opts->maxratio)
455        fprintf(fp, "zzuf[s=%i,r=%g]: ", seed, opts->minratio);
456    else
457        fprintf(fp, "zzuf[s=%i,r=%g:%g]: ", seed,
458                opts->minratio, opts->maxratio);
459}
460
461#if defined HAVE_REGEX_H
462static char *merge_file(char *regex, char *file)
463{
464    char *newfile = malloc(5 + 2 * strlen(file) + 1 + 1), *tmp = newfile;
465
466    *tmp++ = '(';
467    *tmp++ = '^';
468    *tmp++ = '|';
469    *tmp++ = '/';
470    *tmp++ = ')';
471    while(*file)
472    {
473        if(strchr("^.[$()|*+?{\\", *file))
474            *tmp++ = '\\';
475        *tmp++ = *file++;
476    }
477    *tmp++ = '$';
478    *tmp++ = '\0';
479
480    tmp = merge_regex(regex, newfile);
481    free(newfile);
482    return tmp;
483}
484
485static char *merge_regex(char *regex, char *string)
486{
487    regex_t optre;
488
489    if(regex)
490    {
491        regex = realloc(regex, strlen(regex) + strlen(string) + 1 + 1);
492        sprintf(regex + strlen(regex) - 1, "|%s)", string);
493    }
494    else
495    {
496        regex = malloc(1 + strlen(string) + 1 + 1);
497        sprintf(regex, "(%s)", string);
498    }
499
500    if(regcomp(&optre, regex, REG_EXTENDED) != 0)
501    {
502        free(regex);
503        return NULL;
504    }
505    regfree(&optre);
506
507    return regex;
508}
509#endif
510
511static void spawn_children(struct opts *opts)
512{
513    static int const files[] = { DEBUG_FILENO, STDERR_FILENO, STDOUT_FILENO };
514    char buf[64];
515    int fd[3][2];
516    int64_t now = _zz_time();
517    pid_t pid;
518    int i, j;
519
520    if(opts->nchild == opts->maxchild)
521        return; /* no slot */
522
523    if(opts->seed == opts->endseed)
524        return; /* job finished */
525
526    if(opts->maxcrashes && opts->crashes >= opts->maxcrashes)
527        return; /* all jobs crashed */
528
529    if(opts->delay > 0 && opts->lastlaunch + opts->delay > now)
530        return; /* too early */
531
532    /* Find the empty slot */
533    for(i = 0; i < opts->maxchild; i++)
534        if(opts->child[i].status == STATUS_FREE)
535            break;
536
537    /* Prepare communication pipe */
538    for(j = 0; j < 3; j++)
539    {
540        int ret;
541#if defined HAVE_PIPE
542        ret = pipe(fd[j]);
543#elif defined HAVE__PIPE
544        ret = _pipe(fd[j], 256, _O_BINARY);
545#endif
546        if(ret < 0)
547        {
548            perror("pipe");
549            return;
550        }
551    }
552
553#if defined HAVE_FORK
554    /* Fork and launch child */
555    pid = fork();
556    if(pid < -1)
557    {
558        perror("fork");
559        return;
560    }
561#else
562    pid = 0;
563#endif
564
565    if(pid == 0)
566    {
567#if defined HAVE_SETRLIMIT
568        if(opts->maxmem >= 0)
569        {
570            struct rlimit rlim;
571            rlim.rlim_cur = opts->maxmem * 1000000;
572            rlim.rlim_max = opts->maxmem * 1000000;
573            setrlimit(RLIMIT_AS, &rlim);
574        }
575#endif
576
577#if defined HAVE_FORK
578        /* We loop in reverse order so that files[0] is done last,
579         * just in case one of the other dup2()ed fds had the value */
580        for(j = 3; j--; )
581        {
582            close(fd[j][0]);
583            if(fd[j][1] != files[j])
584            {
585                dup2(fd[j][1], files[j]);
586                close(fd[j][1]);
587            }
588        }
589#endif
590
591        /* Set environment variables */
592        sprintf(buf, "%i", opts->seed);
593        setenv("ZZUF_SEED", buf, 1);
594        sprintf(buf, "%g", opts->minratio);
595        setenv("ZZUF_MINRATIO", buf, 1);
596        sprintf(buf, "%g", opts->maxratio);
597        setenv("ZZUF_MAXRATIO", buf, 1);
598
599#if defined HAVE_FORK
600        if(run_process(opts->oldargv[0], opts->newargv) < 0)
601            exit(EXIT_FAILURE);
602        exit(EXIT_SUCCESS);
603#else
604        if(run_process(opts->oldargv[0], opts->newargv) < 0)
605            return;
606#endif
607    }
608
609    /* We’re the parent, acknowledge spawn */
610    opts->child[i].date = now;
611    opts->child[i].pid = pid;
612    for(j = 0; j < 3; j++)
613    {
614        close(fd[j][1]);
615        opts->child[i].fd[j] = fd[j][0];
616    }
617    opts->child[i].bytes = 0;
618    opts->child[i].seed = opts->seed;
619    opts->child[i].ratio = _zz_getratio();
620    opts->child[i].status = STATUS_RUNNING;
621    if(opts->md5)
622        opts->child[i].ctx = _zz_md5_init();
623
624    if(opts->verbose)
625    {
626        finfo(stderr, opts, opts->child[i].seed);
627        fprintf(stderr, "launched %s\n", opts->newargv[0]);
628    }
629
630    opts->lastlaunch = now;
631    opts->nchild++;
632    opts->seed++;
633
634    _zz_setseed(opts->seed);
635}
636
637static void clean_children(struct opts *opts)
638{
639#if defined HAVE_KILL
640    int64_t now = _zz_time();
641#endif
642    int i, j;
643
644#if defined HAVE_KILL
645    /* Terminate children if necessary */
646    for(i = 0; i < opts->maxchild; i++)
647    {
648        if(opts->child[i].status == STATUS_RUNNING
649            && opts->maxbytes >= 0
650            && opts->child[i].bytes > opts->maxbytes)
651        {
652            if(opts->verbose)
653            {
654                finfo(stderr, opts, opts->child[i].seed);
655                fprintf(stderr, "data output exceeded, sending SIGTERM\n");
656            }
657            kill(opts->child[i].pid, SIGTERM);
658            opts->child[i].date = now;
659            opts->child[i].status = STATUS_SIGTERM;
660        }
661
662        if(opts->child[i].status == STATUS_RUNNING
663            && opts->maxtime >= 0
664            && now > opts->child[i].date + opts->maxtime)
665        {
666            if(opts->verbose)
667            {
668                finfo(stderr, opts, opts->child[i].seed);
669                fprintf(stderr, "running time exceeded, sending SIGTERM\n");
670            }
671            kill(opts->child[i].pid, SIGTERM);
672            opts->child[i].date = now;
673            opts->child[i].status = STATUS_SIGTERM;
674        }
675    }
676
677    /* Kill children if necessary (still there after 2 seconds) */
678    for(i = 0; i < opts->maxchild; i++)
679    {
680        if(opts->child[i].status == STATUS_SIGTERM
681            && now > opts->child[i].date + 2000000)
682        {
683            if(opts->verbose)
684            {
685                finfo(stderr, opts, opts->child[i].seed);
686                fprintf(stderr, "not responding, sending SIGKILL\n");
687            }
688            kill(opts->child[i].pid, SIGKILL);
689            opts->child[i].status = STATUS_SIGKILL;
690        }
691    }
692#endif
693
694    /* Collect dead children */
695    for(i = 0; i < opts->maxchild; i++)
696    {
697        uint8_t md5sum[16];
698#if defined HAVE_WAITPID
699        int status;
700        pid_t pid;
701#endif
702
703        if(opts->child[i].status != STATUS_SIGKILL
704            && opts->child[i].status != STATUS_SIGTERM
705            && opts->child[i].status != STATUS_EOF)
706            continue;
707
708#if defined HAVE_WAITPID
709        pid = waitpid(opts->child[i].pid, &status, WNOHANG);
710        if(pid <= 0)
711            continue;
712
713        if(opts->checkexit && WIFEXITED(status) && WEXITSTATUS(status))
714        {
715            finfo(stderr, opts, opts->child[i].seed);
716            fprintf(stderr, "exit %i\n", WEXITSTATUS(status));
717            opts->crashes++;
718        }
719        else if(WIFSIGNALED(status)
720                 && !(WTERMSIG(status) == SIGTERM
721                       && opts->child[i].status == STATUS_SIGTERM))
722        {
723            finfo(stderr, opts, opts->child[i].seed);
724            fprintf(stderr, "signal %i%s%s\n",
725                    WTERMSIG(status), sig2str(WTERMSIG(status)),
726                      (WTERMSIG(status) == SIGKILL && opts->maxmem >= 0) ?
727                      " (memory exceeded?)" : "");
728            opts->crashes++;
729        }
730#endif
731
732        for(j = 0; j < 3; j++)
733            if(opts->child[i].fd[j] >= 0)
734                close(opts->child[i].fd[j]);
735
736        if(opts->md5)
737        {
738            _zz_md5_fini(md5sum, opts->child[i].ctx);
739            finfo(stdout, opts, opts->child[i].seed);
740            fprintf(stdout, "%.02x%.02x%.02x%.02x%.02x%.02x%.02x%.02x%.02x"
741                    "%.02x%.02x%.02x%.02x%.02x%.02x%.02x\n", md5sum[0],
742                    md5sum[1], md5sum[2], md5sum[3], md5sum[4], md5sum[5],
743                    md5sum[6], md5sum[7], md5sum[8], md5sum[9], md5sum[10],
744                    md5sum[11], md5sum[12], md5sum[13], md5sum[14], md5sum[15]);
745            fflush(stdout);
746        }
747        opts->child[i].status = STATUS_FREE;
748        opts->nchild--;
749    }
750}
751
752static void read_children(struct opts *opts)
753{
754    struct timeval tv;
755    fd_set fdset;
756    int i, j, ret, maxfd = 0;
757
758    /* Read data from all sockets */
759    FD_ZERO(&fdset);
760    for(i = 0; i < opts->maxchild; i++)
761    {
762        if(opts->child[i].status != STATUS_RUNNING)
763            continue;
764
765        for(j = 0; j < 3; j++)
766            ZZUF_FD_SET(opts->child[i].fd[j], &fdset, maxfd);
767    }
768    tv.tv_sec = 0;
769    tv.tv_usec = 1000;
770
771    ret = select(maxfd + 1, &fdset, NULL, NULL, &tv);
772    if(ret < 0 && errno)
773        perror("select");
774    if(ret <= 0)
775        return;
776
777    /* XXX: cute (i, j) iterating hack */
778    for(i = 0, j = 0; i < opts->maxchild; i += (j == 2), j = (j + 1) % 3)
779    {
780        uint8_t buf[BUFSIZ];
781
782        if(opts->child[i].status != STATUS_RUNNING)
783            continue;
784
785        if(!ZZUF_FD_ISSET(opts->child[i].fd[j], &fdset))
786            continue;
787
788        ret = read(opts->child[i].fd[j], buf, BUFSIZ - 1);
789        if(ret > 0)
790        {
791            /* We got data */
792            if(j != 0)
793                opts->child[i].bytes += ret;
794
795            if(opts->md5 && j == 2)
796                _zz_md5_add(opts->child[i].ctx, buf, ret);
797            else if(!opts->quiet || j == 0)
798                write((j < 2) ? STDERR_FILENO : STDOUT_FILENO, buf, ret);
799        }
800        else if(ret == 0)
801        {
802            /* End of file reached */
803            close(opts->child[i].fd[j]);
804            opts->child[i].fd[j] = -1;
805
806            if(opts->child[i].fd[0] == -1
807                && opts->child[i].fd[1] == -1
808                && opts->child[i].fd[2] == -1)
809                opts->child[i].status = STATUS_EOF;
810        }
811    }
812}
813
814#if !defined HAVE_SETENV
815static void setenv(char const *name, char const *value, int overwrite)
816{
817    char *str;
818
819    if(!overwrite && getenv(name))
820        return;
821
822    str = malloc(strlen(name) + 1 + strlen(value) + 1);
823    sprintf(str, "%s=%s", name, value);
824    putenv(str);
825}
826#endif
827
828#if defined HAVE_WAITPID
829static char const *sig2str(int signum)
830{
831    switch(signum)
832    {
833        case SIGABRT:  return " (SIGABRT)";
834        case SIGFPE:   return " (SIGFPE)";
835        case SIGILL:   return " (SIGILL)";
836#ifdef SIGQUIT
837        case SIGQUIT:  return " (SIGQUIT)";
838#endif
839        case SIGSEGV:  return " (SIGSEGV)";
840#ifdef SIGTRAP
841        case SIGTRAP:  return " (SIGTRAP)";
842#endif
843#ifdef SIGSYS
844        case SIGSYS:   return " (SIGSYS)";
845#endif
846#ifdef SIGEMT
847        case SIGEMT:   return " (SIGEMT)";
848#endif
849#ifdef SIGBUS
850        case SIGBUS:   return " (SIGBUS)";
851#endif
852#ifdef SIGXCPU
853        case SIGXCPU:  return " (SIGXCPU)";
854#endif
855#ifdef SIGXFSZ
856        case SIGXFSZ:  return " (SIGXFSZ)";
857#endif
858    }
859
860    return "";
861}
862#endif
863
864static int run_process(char const *zzuf_exe, char *argv[])
865{
866#if defined HAVE_FORK
867    char *libpath, *tmp;
868    int ret, len = strlen(zzuf_exe);
869#   if defined __APPLE__
870#       define FILENAME "libzzuf.dylib"
871#       define EXTRAINFO ""
872#       define PRELOAD "DYLD_INSERT_LIBRARIES"
873    setenv("DYLD_FORCE_FLAT_NAMESPACE", "1", 1);
874#   elif defined __osf__
875#       define FILENAME "libzzuf.so"
876#       define EXTRAINFO ":DEFAULT"
877#       define PRELOAD "_RLD_LIST"
878#   else
879#       define FILENAME "libzzuf.so"
880#       define EXTRAINFO ""
881#       define PRELOAD "LD_PRELOAD"
882#   endif
883
884    libpath = malloc(len + strlen("/.libs/" FILENAME EXTRAINFO) + 1);
885    strcpy(libpath, zzuf_exe);
886
887    tmp = strrchr(libpath, '/');
888    strcpy(tmp ? tmp + 1 : libpath, ".libs/" FILENAME);
889    ret = access(libpath, R_OK);
890
891    strcpy(tmp ? tmp + 1 : libpath, ".libs/" FILENAME EXTRAINFO);
892    if(ret == 0)
893        setenv(PRELOAD, libpath, 1);
894    else
895        setenv(PRELOAD, LIBDIR "/" FILENAME EXTRAINFO, 1);
896    free(libpath);
897
898    if(execvp(argv[0], argv))
899    {
900        perror(argv[0]);
901        return -1;
902    }
903
904    return 0;
905#elif HAVE_WINDOWS_H
906    PROCESS_INFORMATION pinfo;
907    STARTUPINFO sinfo;
908    void *epaddr;
909    int ret;
910
911    /* Get entry point */
912    epaddr = get_entry(argv[0]);
913    if(!epaddr)
914        return -1;
915   
916    memset(&sinfo, 0, sizeof(sinfo));
917    sinfo.cb = sizeof(sinfo);
918    ret = CreateProcess(NULL, argv[0], NULL, NULL, FALSE,
919                        CREATE_SUSPENDED, NULL, NULL, &sinfo, &pinfo);
920    if(!ret)
921        return -1;
922
923    /* Insert the replacement code */
924    ret = dll_inject(pinfo.hProcess, epaddr);
925    if(ret < 0)
926    {
927        TerminateProcess(pinfo.hProcess, -1);
928        return -1;
929    }
930
931    ret = ResumeThread(pinfo.hThread);
932    if(ret < 0)
933    {
934        TerminateProcess(pinfo.hProcess, -1);
935        return -1;
936    }
937
938    return 0;
939#else
940    return -1;
941#endif
942}
943
944#if defined HAVE_WINDOWS_H
945static int dll_inject(void *process, void *epaddr)
946{
947    uint8_t old_ep[7];
948    uint8_t new_ep[] = "\xb8<01>\xff\xe0";
949    uint8_t loader[] = "libzzuf.dll\0<0000c>\xb8<14>\x50\xb8<1a>\xff\xd0"
950                       "\xb8\0\0\0\0\x50\xb8\x07\x00\x00\x00\x50\xb8<2d>"
951                       "\x50\xb8<33>\x50\xb8<39>\xff\xd0\x50\xb8<41>\xff"
952                       "\xd0\xb8<48>\xff\xe0";
953    void *lib;
954    uint8_t *loaderaddr;
955    DWORD tmp;
956
957    /* Save the old entry-point code */
958    ReadProcessMemory(process, epaddr, old_ep, 7, &tmp);
959    if(tmp != 7)
960        return -1;
961
962    loaderaddr = VirtualAllocEx(process, NULL, 78, MEM_COMMIT,
963                                PAGE_EXECUTE_READWRITE);
964    if(!loaderaddr)
965        return -1;
966
967    addcpy(new_ep + 0x01, loaderaddr + 0x0c + 7);
968    WriteProcessMemory(process, epaddr, new_ep, 7, &tmp);
969    if(tmp != 7)
970        return -1;
971
972    lib = LoadLibrary("kernel32.dll");
973    if(!lib)
974        return -1;
975
976    memcpy(loader + 0x0c, old_ep, 7);
977    addcpy(loader + 0x14, loaderaddr + 0x00); /* offset for dll string */
978    addcpy(loader + 0x1a, GetProcAddress(lib, "LoadLibraryA"));
979    addcpy(loader + 0x2d, loaderaddr + 0x0c);
980    addcpy(loader + 0x33, epaddr);
981    addcpy(loader + 0x39, GetProcAddress(lib, "GetCurrentProcess"));
982    addcpy(loader + 0x41, GetProcAddress(lib, "WriteProcessMemory"));
983    addcpy(loader + 0x48, epaddr);
984    FreeLibrary(lib);
985
986    WriteProcessMemory(process, loaderaddr, loader, 78, &tmp);
987    if(tmp != 78)
988        return -1;
989
990    return 0;
991}
992
993static void *get_entry(char const *name)
994{
995    PIMAGE_DOS_HEADER dos;
996    PIMAGE_NT_HEADERS nt;
997    void *file, *map, *base;
998
999    file = CreateFile(name, GENERIC_READ, FILE_SHARE_READ,
1000                      NULL, OPEN_EXISTING, 0, NULL);
1001    if(file == INVALID_HANDLE_VALUE)
1002        return NULL;
1003
1004    map = CreateFileMapping(file, NULL, PAGE_READONLY, 0, 0, NULL);
1005    if(!map)
1006    {
1007        CloseHandle(file);
1008        return NULL;
1009    }
1010
1011    base = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
1012    if(!base)
1013    {
1014        CloseHandle(map);
1015        CloseHandle(file);
1016        return NULL;
1017    }
1018
1019    /* Sanity checks */
1020    dos = (PIMAGE_DOS_HEADER)base;
1021    nt = (PIMAGE_NT_HEADERS)((char *)base + dos->e_lfanew);
1022    if(dos->e_magic != IMAGE_DOS_SIGNATURE
1023      || nt->Signature != IMAGE_NT_SIGNATURE
1024      || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_I386
1025      || nt->OptionalHeader.Magic != 0x10b /* IMAGE_NT_OPTIONAL_HDR32_MAGIC */)
1026    {
1027        UnmapViewOfFile(base);
1028        CloseHandle(map);
1029        CloseHandle(file);
1030        return NULL;
1031    }
1032
1033    return (char *)nt->OptionalHeader.ImageBase +
1034                           nt->OptionalHeader.AddressOfEntryPoint;
1035}
1036#endif
1037
1038static void version(void)
1039{
1040    printf("zzuf %s\n", VERSION);
1041    printf("Copyright (C) 2002, 2007 Sam Hocevar <sam@zoy.org>\n");
1042    printf("This is free software.  You may redistribute copies of it under the\n");
1043    printf("terms of the Do What The Fuck You Want To Public License, Version 2\n");
1044    printf("<http://sam.zoy.org/wtfpl/>.\n");
1045    printf("There is NO WARRANTY, to the extent permitted by law.\n");
1046    printf("\n");
1047    printf("Written by Sam Hocevar. Report bugs to <sam@zoy.org>.\n");
1048}
1049
1050#if defined HAVE_GETOPT_H
1051static void usage(void)
1052{
1053#if defined HAVE_REGEX_H
1054    printf("Usage: zzuf [-AcdimnqSvx] [-s seed|-s start:stop] [-r ratio|-r min:max]\n");
1055#else
1056    printf("Usage: zzuf [-AdimnqSvx] [-s seed|-s start:stop] [-r ratio|-r min:max]\n");
1057#endif
1058    printf("              [-f fuzzing] [-D delay] [-F forks] [-C crashes] [-B bytes]\n");
1059    printf("              [-T seconds] [-M bytes] [-b ranges] [-P protect] [-R refuse]\n");
1060#if defined HAVE_REGEX_H
1061    printf("              [-I include] [-E exclude] [PROGRAM [--] [ARGS]...]\n");
1062#else
1063    printf("              [PROGRAM [--] [ARGS]...]\n");
1064#endif
1065#   if defined HAVE_GETOPT_LONG
1066    printf("       zzuf -h | --help\n");
1067    printf("       zzuf -V | --version\n");
1068#   else
1069    printf("       zzuf -h\n");
1070    printf("       zzuf -V\n");
1071#   endif
1072    printf("Run PROGRAM with optional arguments ARGS and fuzz its input.\n");
1073    printf("\n");
1074    printf("Mandatory arguments to long options are mandatory for short options too.\n");
1075#   if defined HAVE_GETOPT_LONG
1076    printf("  -A, --autoinc             increment seed each time a new file is opened\n");
1077    printf("  -b, --bytes <ranges>      only fuzz bytes at offsets within <ranges>\n");
1078    printf("  -B, --max-bytes <n>       kill children that output more than <n> bytes\n");
1079#if defined HAVE_REGEX_H
1080    printf("  -c, --cmdline             only fuzz files specified in the command line\n");
1081#endif
1082    printf("  -C, --max-crashes <n>     stop after <n> children have crashed (default 1)\n");
1083    printf("  -d, --debug               print debug messages\n");
1084    printf("  -D, --delay               delay between forks\n");
1085#if defined HAVE_REGEX_H
1086    printf("  -E, --exclude <regex>     do not fuzz files matching <regex>\n");
1087#endif
1088    printf("  -f, --fuzzing <mode>      use fuzzing mode <mode> ([xor] set unset)\n");
1089    printf("  -F, --max-forks <n>       number of concurrent children (default 1)\n");
1090    printf("  -i, --stdin               fuzz standard input\n");
1091#if defined HAVE_REGEX_H
1092    printf("  -I, --include <regex>     only fuzz files matching <regex>\n");
1093#endif
1094    printf("  -m, --md5                 compute the output's MD5 hash\n");
1095#if defined HAVE_SETRLIMIT
1096    printf("  -M, --max-memory <n>      maximum child virtual memory size in MB\n");
1097#endif
1098    printf("  -n, --network             fuzz network input\n");
1099    printf("  -P, --protect <list>      protect bytes and characters in <list>\n");
1100    printf("  -q, --quiet               do not print children's messages\n");
1101    printf("  -r, --ratio <ratio>       bit fuzzing ratio (default %g)\n", DEFAULT_RATIO);
1102    printf("      --ratio <start:stop>  specify a ratio range\n");
1103    printf("  -R, --refuse <list>       refuse bytes and characters in <list>\n");
1104    printf("  -s, --seed <seed>         random seed (default %i)\n", DEFAULT_SEED);
1105    printf("      --seed <start:stop>   specify a seed range\n");
1106    printf("  -S, --signal              prevent children from diverting crashing signals\n");
1107    printf("  -T, --max-time <n>        kill children that run for more than <n> seconds\n");
1108    printf("  -v, --verbose             print information during the run\n");
1109    printf("  -x, --check-exit          report processes that exit with a non-zero status\n");
1110    printf("  -h, --help                display this help and exit\n");
1111    printf("  -V, --version             output version information and exit\n");
1112#   else
1113    printf("  -A               increment seed each time a new file is opened\n");
1114    printf("  -b <ranges>      only fuzz bytes at offsets within <ranges>\n");
1115    printf("  -B <n>           kill children that output more than <n> bytes\n");
1116#if defined HAVE_REGEX_H
1117    printf("  -c               only fuzz files specified in the command line\n");
1118#endif
1119    printf("  -C <n>           stop after <n> children have crashed (default 1)\n");
1120    printf("  -d               print debug messages\n");
1121    printf("  -D               delay between forks\n");
1122#if defined HAVE_REGEX_H
1123    printf("  -E <regex>       do not fuzz files matching <regex>\n");
1124#endif
1125    printf("  -f <mode>        use fuzzing mode <mode>\n");
1126    printf("  -F <n>           number of concurrent forks (default 1)\n");
1127    printf("  -i               fuzz standard input\n");
1128#if defined HAVE_REGEX_H
1129    printf("  -I <regex>       only fuzz files matching <regex>\n");
1130#endif
1131    printf("  -m               compute the output's MD5 hash\n");
1132#if defined HAVE_SETRLIMIT
1133    printf("  -M               maximum child virtual memory size in MB\n");
1134#endif
1135    printf("  -n               fuzz network input\n");
1136    printf("  -P <list>        protect bytes and characters in <list>\n");
1137    printf("  -q               do not print the fuzzed application's messages\n");
1138    printf("  -r <ratio>       bit fuzzing ratio (default %g)\n", DEFAULT_RATIO);
1139    printf("     <start:stop>  specify a ratio range\n");
1140    printf("  -R <list>        refuse bytes and characters in <list>\n");
1141    printf("  -s <seed>        random seed (default %i)\n", DEFAULT_SEED);
1142    printf("     <start:stop>  specify a seed range\n");
1143    printf("  -S               prevent children from diverting crashing signals\n");
1144    printf("  -T <n>           kill children that run for more than <n> seconds\n");
1145    printf("  -v               print information during the run\n");
1146    printf("  -x               report processes that exit with a non-zero status\n");
1147    printf("  -h               display this help and exit\n");
1148    printf("  -V               output version information and exit\n");
1149#   endif
1150    printf("\n");
1151    printf("Written by Sam Hocevar. Report bugs to <sam@zoy.org>.\n");
1152}
1153#endif
1154
Note: See TracBrowser for help on using the repository browser.