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

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