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

Last change on this file since 4664 was 4664, checked in by Sam Hocevar, 11 years ago

Inherit stdin/stdout/stderr in the child process under Win32.

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