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

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