source: zzuf/trunk/src/myfork.c @ 4674

Last change on this file since 4674 was 4674, checked in by Sam Hocevar, 10 years ago

Fix missing ZZUF_DEBUGFD passing and debug function availability.

  • Property svn:keywords set to Id
File size: 15.8 KB
Line 
1/*
2 *  zzuf - general purpose fuzzer
3 *  Copyright (c) 2002-2010 Sam Hocevar <sam@hocevar.net>
4 *                All Rights Reserved
5 *
6 *  This program is free software. It comes without any warranty, to
7 *  the extent permitted by applicable law. You can redistribute it
8 *  and/or modify it under the terms of the Do What The Fuck You Want
9 *  To Public License, Version 2, as published by Sam Hocevar. See
10 *  http://sam.zoy.org/wtfpl/COPYING for more details.
11 */
12
13/*
14 *  myfork.c: launcher
15 */
16
17#include "config.h"
18
19#define _INCLUDE_POSIX_SOURCE /* for STDERR_FILENO on HP-UX */
20
21#if defined HAVE_STDINT_H
22#   include <stdint.h>
23#elif defined HAVE_INTTYPES_H
24#   include <inttypes.h>
25#endif
26#include <stdio.h>
27#include <stdlib.h>
28#if defined HAVE_UNISTD_H
29#   include <unistd.h>
30#endif
31#if defined HAVE_WINDOWS_H
32#   include <windows.h>
33#   include <imagehlp.h>
34#   include <tlhelp32.h>
35#endif
36#if defined HAVE_IO_H
37#   include <io.h>
38#endif
39#include <string.h>
40#include <fcntl.h> /* for O_BINARY */
41#if defined HAVE_SYS_RESOURCE_H
42#   include <sys/resource.h> /* for RLIMIT_AS */
43#endif
44
45#include "common.h"
46#include "opts.h"
47#include "random.h"
48#include "fd.h"
49#include "fuzz.h"
50#include "myfork.h"
51#include "md5.h"
52#include "timer.h"
53
54/* Handle old libtool versions */
55#if !defined LT_OBJDIR
56#   define LT_OBJDIR ".libs/"
57#endif
58
59#if defined RLIMIT_AS
60#   define ZZUF_RLIMIT_MEM RLIMIT_AS
61#elif defined RLIMIT_VMEM
62#   define ZZUF_RLIMIT_MEM RLIMIT_VMEM
63#elif defined RLIMIT_DATA
64#   define ZZUF_RLIMIT_MEM RLIMIT_DATA
65#else
66#   undef ZZUF_RLIMIT_MEM
67#endif
68
69#if defined RLIMIT_CPU
70#   define ZZUF_RLIMIT_CPU RLIMIT_CPU
71#else
72#   undef ZZUF_RLIMIT_CPU
73#endif
74
75static int run_process(struct child *child, struct opts *, int[][2]);
76
77#if defined HAVE_WINDOWS_H
78static void rep32(uint8_t *buf, void *addr);
79static int dll_inject(PROCESS_INFORMATION *, char const *);
80static intptr_t get_proc_address(void *, DWORD, char const *);
81#endif
82
83int myfork(struct child *child, struct opts *opts)
84{
85    int pipes[3][2];
86    pid_t pid;
87    int i;
88
89    /* Prepare communication pipe */
90    for(i = 0; i < 3; i++)
91    {
92        int ret;
93#if defined HAVE_PIPE
94        ret = pipe(pipes[i]);
95#elif defined HAVE__PIPE
96        int tmp;
97        /* The pipe is created with NOINHERIT otherwise both parts are
98         * inherited. We then duplicate the part we want. */
99        ret = _pipe(pipes[i], 512, _O_BINARY | O_NOINHERIT);
100        tmp = _dup(pipes[i][1]);
101        close(pipes[i][1]);
102        pipes[i][1] = tmp;
103#endif
104        if(ret < 0)
105        {
106            perror("pipe");
107            return -1;
108        }
109    }
110
111    pid = run_process(child, opts, pipes);
112    if(pid < 0)
113    {
114        /* FIXME: close pipes */
115        fprintf(stderr, "error launching `%s'\n", child->newargv[0]);
116        return -1;
117    }
118
119    child->pid = pid;
120    for(i = 0; i < 3; i++)
121    {
122        close(pipes[i][1]);
123        child->fd[i] = pipes[i][0];
124    }
125
126    return 0;
127}
128
129#if !defined HAVE_SETENV
130static void setenv(char const *name, char const *value, int overwrite)
131{
132    char *str;
133
134    if(!overwrite && getenv(name))
135        return;
136
137    str = malloc(strlen(name) + 1 + strlen(value) + 1);
138    sprintf(str, "%s=%s", name, value);
139    putenv(str);
140}
141#endif
142
143static int run_process(struct child *child, struct opts *opts, int pipes[][2])
144{
145    char buf[64];
146#if defined HAVE_FORK
147    static int const files[] = { DEBUG_FILENO, STDERR_FILENO, STDOUT_FILENO };
148    char *libpath, *tmp;
149    int pid, j, len = strlen(opts->oldargv[0]);
150#   if defined __APPLE__
151#       define EXTRAINFO ""
152#       define PRELOAD "DYLD_INSERT_LIBRARIES"
153    setenv("DYLD_FORCE_FLAT_NAMESPACE", "1", 1);
154#   elif defined __osf__
155#       define EXTRAINFO ":DEFAULT"
156#       define PRELOAD "_RLD_LIST"
157#   elif defined __sun && defined __i386
158#       define EXTRAINFO ""
159#       define PRELOAD "LD_PRELOAD_32"
160#   else
161#       define EXTRAINFO ""
162#       define PRELOAD "LD_PRELOAD"
163#   endif
164#elif HAVE_WINDOWS_H
165    PROCESS_INFORMATION pinfo;
166    STARTUPINFO sinfo;
167    HANDLE pid;
168    char *cmdline;
169    int i, ret, len;
170#endif
171
172#if defined HAVE_FORK
173    /* Fork and launch child */
174    pid = fork();
175    if(pid < 0)
176        perror("fork");
177    if(pid != 0)
178        return pid;
179
180    /* We loop in reverse order so that files[0] is done last,
181     * just in case one of the other dup2()ed fds had the value */
182    for(j = 3; j--; )
183    {
184        close(pipes[j][0]);
185        if(pipes[j][1] != files[j])
186        {
187            dup2(pipes[j][1], files[j]);
188            close(pipes[j][1]);
189        }
190    }
191#endif
192
193#if defined HAVE_SETRLIMIT && defined ZZUF_RLIMIT_MEM
194    if(opts->maxmem >= 0)
195    {
196        struct rlimit rlim;
197        rlim.rlim_cur = opts->maxmem * 1048576;
198        rlim.rlim_max = opts->maxmem * 1048576;
199        setrlimit(ZZUF_RLIMIT_MEM, &rlim);
200    }
201#endif
202
203#if defined HAVE_SETRLIMIT && defined ZZUF_RLIMIT_CPU
204    if(opts->maxcpu >= 0)
205    {
206        struct rlimit rlim;
207        rlim.rlim_cur = opts->maxcpu;
208        rlim.rlim_max = opts->maxcpu + 5;
209        setrlimit(ZZUF_RLIMIT_CPU, &rlim);
210    }
211#endif
212
213    /* Set environment variables */
214#if defined _WIN32
215    sprintf(buf, "%i", _get_osfhandle(pipes[0][1]));
216#else
217    sprintf(buf, "%i", pipes[0][1]);
218#endif
219    setenv("ZZUF_DEBUGFD", buf, 1);
220    sprintf(buf, "%i", opts->seed);
221    setenv("ZZUF_SEED", buf, 1);
222    sprintf(buf, "%g", opts->minratio);
223    setenv("ZZUF_MINRATIO", buf, 1);
224    sprintf(buf, "%g", opts->maxratio);
225    setenv("ZZUF_MAXRATIO", buf, 1);
226
227#if defined HAVE_FORK
228    /* Make sure there is space for everything we might do. */
229    libpath = malloc(len + strlen(LIBDIR "/" LT_OBJDIR SONAME EXTRAINFO) + 1);
230    strcpy(libpath, opts->oldargv[0]);
231
232    /* If the binary name contains a '/', we look for a libzzuf in the
233     * same directory. Otherwise, we only look into the system directory
234     * to avoid shared library attacks. Write the result in libpath. */
235    tmp = strrchr(libpath, '/');
236    if(tmp)
237    {
238        strcpy(tmp + 1, LT_OBJDIR SONAME);
239        if(access(libpath, R_OK) < 0)
240            strcpy(libpath, LIBDIR "/" SONAME);
241    }
242    else
243        strcpy(libpath, LIBDIR "/" SONAME);
244
245    /* OSF1 only */
246    strcat(libpath, EXTRAINFO);
247
248    /* Do not clobber previous LD_PRELOAD values */
249    tmp = getenv(PRELOAD);
250    if(tmp && *tmp)
251    {
252        char *bigbuf = malloc(strlen(tmp) + strlen(libpath) + 2);
253        sprintf(bigbuf, "%s:%s", tmp, libpath);
254        free(libpath);
255        libpath = bigbuf;
256    }
257
258    /* Only preload the library in preload mode */
259    if (opts->opmode == OPMODE_PRELOAD)
260        setenv(PRELOAD, libpath, 1);
261    free(libpath);
262
263    if(execvp(child->newargv[0], child->newargv))
264    {
265        perror(child->newargv[0]);
266        exit(EXIT_FAILURE);
267    }
268
269    exit(EXIT_SUCCESS);
270    /* no return */
271    return 0;
272#elif HAVE_WINDOWS_H
273    pid = GetCurrentProcess();
274
275    /* Inherit standard handles */
276    memset(&sinfo, 0, sizeof(sinfo));
277    sinfo.cb = sizeof(sinfo);
278    sinfo.hStdInput = INVALID_HANDLE_VALUE;
279    sinfo.hStdOutput = (HANDLE)_get_osfhandle(pipes[2][1]);
280    sinfo.hStdError = (HANDLE)_get_osfhandle(pipes[1][1]);
281    sinfo.dwFlags = STARTF_USESTDHANDLES;
282
283    /* Build the commandline */
284    for (i = 0, len = 0; child->newargv[i]; i++)
285        len += strlen(child->newargv[i]) + 1;
286    cmdline = malloc(len);
287    for (i = 0, len = 0; child->newargv[i]; i++)
288    {
289        strcpy(cmdline + len, child->newargv[i]);
290        len += strlen(child->newargv[i]) + 1;
291        cmdline[len - 1] = ' ';
292    }
293    cmdline[len - 1] = '\0';
294
295    /* Create the process in suspended state */
296    ret = CreateProcess(child->newargv[0], cmdline, NULL, NULL, TRUE,
297                        CREATE_SUSPENDED, NULL, NULL, &sinfo, &pinfo);
298    free(cmdline);
299
300    if (!ret)
301        return -1;
302
303    /* Insert the replacement code */
304    ret = dll_inject(&pinfo, SONAME);
305    if(ret < 0)
306    {
307        TerminateProcess(pinfo.hProcess, -1);
308        return -1;
309    }
310
311    ret = ResumeThread(pinfo.hThread);
312    if(ret < 0)
313    {
314        TerminateProcess(pinfo.hProcess, -1);
315        return -1;
316    }
317
318    return (long int)pinfo.hProcess;
319#endif
320}
321
322#if defined HAVE_WINDOWS_H
323static void rep32(uint8_t *buf, void *addr)
324{
325    while(buf++)
326        if (memcmp(buf, "____", 4) == 0)
327        {
328            memcpy(buf, &addr, 4);
329            return;
330        }
331}
332
333static int dll_inject(PROCESS_INFORMATION *pinfo, char const *lib)
334{
335    static uint8_t const loader[] =
336        /* Load the injected DLL into memory */
337        "\xb8____"       /* mov %eax, <library_name_address> */
338        "\x50"           /* push %eax */
339        "\xb8____"       /* mov %eax, <LoadLibraryA> */
340        "\xff\xd0"       /* call %eax */
341        /* Restore the clobbered entry point code using our backup */
342        "\xb8\0\0\0\0"   /* mov %eax,0 */
343        "\x50"           /* push %eax */
344        "\xb8____"       /* mov %eax, <jumper_length> */
345        "\x50"           /* push %eax */
346        "\xb8____"       /* mov %eax, <backuped_entry_point_address> */
347        "\x50"           /* push %eax */
348        "\xb8____"       /* mov %eax, <original_entry_point_address> */
349        "\x50"           /* push %eax */
350        "\xb8____"       /* mov %eax, <GetCurrentProcess> */
351        "\xff\xd0"       /* call %eax */
352        "\x50"           /* push %eax */
353        "\xb8____"       /* mov %eax, <WriteProcessMemory> */
354        "\xff\xd0"       /* call %eax */
355        /* Jump to the original entry point */
356        "\xb8____"       /* mov %eax, <original_entry_point_address> */
357        "\xff\xe0";      /* jmp %eax */
358
359    static uint8_t const waiter[] =
360        "\xeb\xfe";      /* jmp <current> */
361
362    static uint8_t const jumper[] =
363        /* Jump to the injected loader */
364        "\xb8____"       /* mov eax, <loader_address> */
365        "\xff\xe0";      /* jmp eax */
366
367    CONTEXT ctx;
368    void *process = pinfo->hProcess;
369    void *thread = pinfo->hThread;
370    void *epaddr;
371    DWORD pid = pinfo->dwProcessId;
372
373    /* code:
374     * +---------------+--------------------+--------------+-------------+
375     * |     loader    | entry point backup | library name |   jumper    |
376     * |  len(loader)  |    len(jumper)     |   len(lib)   | len(jumper) |
377     * +---------------+--------------------+--------------+-------------+ */
378    uint8_t code[1024];
379
380    uint8_t *loaderaddr;
381    size_t liblen, loaderlen, waiterlen, jumperlen;
382    DWORD tmp;
383
384    liblen = strlen(lib) + 1;
385    loaderlen = sizeof(loader) - 1;
386    waiterlen = sizeof(waiter) - 1;
387    jumperlen = sizeof(jumper) - 1;
388    if (loaderlen + jumperlen + liblen > 1024)
389        return -1;
390
391    /* Allocate memory in the child for our injected code */
392    loaderaddr = VirtualAllocEx(process, NULL, loaderlen + jumperlen + liblen,
393                                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
394    if(!loaderaddr)
395        return -1;
396
397    /* Create the first shellcode (jumper).
398     *
399     * The jumper's job is simply to jump at the second shellcode's location.
400     * It is written at the original entry point's location, which will in
401     * turn be restored by the second shellcode.
402     */
403    memcpy(code + loaderlen + jumperlen + liblen, jumper, jumperlen);
404    rep32(code + loaderlen + jumperlen + liblen, loaderaddr);
405
406    /* Create the second shellcode (loader, backuped entry point, and library
407     * name).
408     *
409     * The loader's job is to load the library by calling LoadLibraryA(),
410     * restore the original entry point using the backup copy, and jump
411     * back to the original entry point as if the process had just started.
412     *
413     * The second shellcode is written at a freshly allocated memory location.
414     */
415    memcpy(code, loader, loaderlen);
416    memcpy(code + loaderlen + jumperlen, lib, liblen);
417
418    /* Find the entry point address. It's simply in EAX. */
419    ctx.ContextFlags = CONTEXT_FULL;
420    GetThreadContext(thread, &ctx);
421    epaddr = (void *)(uintptr_t)ctx.Eax;
422
423    /* Backup the old entry point code */
424    ReadProcessMemory(process, epaddr, code + loaderlen, jumperlen, &tmp);
425    if(tmp != jumperlen)
426        return -1;
427
428    /* Replace the entry point code with a short jump to self, then resume
429     * the thread. This is necessary for CreateToolhelp32Snapshot() to
430     * work. */
431    WriteProcessMemory(process, epaddr, waiter, waiterlen, &tmp);
432    if(tmp != waiterlen)
433        return -1;
434    FlushInstructionCache(process, epaddr, waiterlen);
435    ResumeThread(thread);
436
437    /* Wait until the entry point is reached */
438    for (tmp = 0; tmp < 100; tmp++)
439    {
440        CONTEXT ctx;
441        ctx.ContextFlags = CONTEXT_FULL;
442        GetThreadContext(thread, &ctx);
443        if ((uintptr_t)ctx.Eip == (uintptr_t)epaddr)
444            break;
445        Sleep(10);
446    }
447    SuspendThread(thread);
448    if (tmp == 100)
449        return -1;
450
451    /* Remotely parse the target process's module list to get the addresses
452     * of the functions we need. This can only be done because we advanced
453     * the target's execution to the entry point. */
454    rep32(code, loaderaddr + loaderlen + jumperlen);
455    rep32(code, (void *)get_proc_address(process, pid, "LoadLibraryA"));
456    rep32(code, (void *)(uintptr_t)jumperlen);
457    rep32(code, loaderaddr + loaderlen);
458    rep32(code, epaddr);
459    rep32(code, (void *)get_proc_address(process, pid, "GetCurrentProcess"));
460    rep32(code, (void *)get_proc_address(process, pid, "WriteProcessMemory"));
461    rep32(code, epaddr);
462
463    /* Write our shellcodes into the target process */
464    WriteProcessMemory(process, epaddr, code + loaderlen + jumperlen + liblen,
465                       jumperlen, &tmp);
466    if(tmp != jumperlen)
467        return -1;
468    FlushInstructionCache(process, epaddr, waiterlen);
469
470    WriteProcessMemory(process, loaderaddr, code,
471                       loaderlen + jumperlen + liblen, &tmp);
472    if(tmp != loaderlen + jumperlen + liblen)
473        return -1;
474
475    return 0;
476}
477
478static intptr_t get_proc_address(void *process, DWORD pid, const char *func)
479{
480    char buf[1024];
481    size_t buflen = strlen(func) + 1;
482
483    MODULEENTRY32 entry;
484    intptr_t ret = 0;
485    DWORD tmp;
486    void *list;
487    int i, k;
488
489    list = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
490    entry.dwSize = sizeof(entry);
491    for(k = Module32First(list, &entry); k; k = Module32Next(list, &entry))
492    {
493        IMAGE_DOS_HEADER dos;
494        IMAGE_NT_HEADERS nt;
495        IMAGE_EXPORT_DIRECTORY expdir;
496
497        uint32_t exportaddr;
498        uint8_t const *base = entry.modBaseAddr;
499
500        if (strcmp("kernel32.dll", entry.szModule))
501            continue;
502
503        ReadProcessMemory(process, base, &dos, sizeof(dos), &tmp);
504        ReadProcessMemory(process, base + dos.e_lfanew, &nt, sizeof(nt), &tmp);
505
506        exportaddr = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
507        if (!exportaddr)
508            continue;
509
510        ReadProcessMemory(process, base + exportaddr, &expdir, sizeof(expdir), &tmp);
511
512        for (i = 0; i < (int)expdir.NumberOfNames; i++)
513        {
514            uint32_t nameaddr, funcaddr;
515            uint16_t j;
516
517            /* Look for our function name in the list of names */
518            ReadProcessMemory(process, base + expdir.AddressOfNames
519                                            + i * sizeof(DWORD),
520                              &nameaddr, sizeof(nameaddr), &tmp);
521            ReadProcessMemory(process, base + nameaddr, buf, buflen, &tmp);
522
523            if (strcmp(buf, func))
524                continue;
525
526            /* If we found a function with this name, return its address */
527            ReadProcessMemory(process, base + expdir.AddressOfNameOrdinals
528                                            + i * sizeof(WORD),
529                                &j, sizeof(j), &tmp);
530            ReadProcessMemory(process, base + expdir.AddressOfFunctions
531                                            + j * sizeof(DWORD),
532                                &funcaddr, sizeof(funcaddr), &tmp);
533
534            ret = (intptr_t)base + funcaddr;
535            goto _finished;
536        }
537    }
538
539_finished:
540    CloseHandle(list);
541    return ret;
542}
543
544#endif
Note: See TracBrowser for help on using the repository browser.