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

Last change on this file since 4668 was 4668, checked in by Sam Hocevar, 9 years ago

Remove useless PARENT_FD/CHILD_FD hack.

  • Property svn:keywords set to Id
File size: 15.7 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    sprintf(buf, "%i", DEBUG_FILENO);
215    setenv("ZZUF_DEBUGFD", buf, 1);
216    sprintf(buf, "%i", opts->seed);
217    setenv("ZZUF_SEED", buf, 1);
218    sprintf(buf, "%g", opts->minratio);
219    setenv("ZZUF_MINRATIO", buf, 1);
220    sprintf(buf, "%g", opts->maxratio);
221    setenv("ZZUF_MAXRATIO", buf, 1);
222
223#if defined HAVE_FORK
224    /* Make sure there is space for everything we might do. */
225    libpath = malloc(len + strlen(LIBDIR "/" LT_OBJDIR SONAME EXTRAINFO) + 1);
226    strcpy(libpath, opts->oldargv[0]);
227
228    /* If the binary name contains a '/', we look for a libzzuf in the
229     * same directory. Otherwise, we only look into the system directory
230     * to avoid shared library attacks. Write the result in libpath. */
231    tmp = strrchr(libpath, '/');
232    if(tmp)
233    {
234        strcpy(tmp + 1, LT_OBJDIR SONAME);
235        if(access(libpath, R_OK) < 0)
236            strcpy(libpath, LIBDIR "/" SONAME);
237    }
238    else
239        strcpy(libpath, LIBDIR "/" SONAME);
240
241    /* OSF1 only */
242    strcat(libpath, EXTRAINFO);
243
244    /* Do not clobber previous LD_PRELOAD values */
245    tmp = getenv(PRELOAD);
246    if(tmp && *tmp)
247    {
248        char *bigbuf = malloc(strlen(tmp) + strlen(libpath) + 2);
249        sprintf(bigbuf, "%s:%s", tmp, libpath);
250        free(libpath);
251        libpath = bigbuf;
252    }
253
254    /* Only preload the library in preload mode */
255    if (opts->opmode == OPMODE_PRELOAD)
256        setenv(PRELOAD, libpath, 1);
257    free(libpath);
258
259    if(execvp(child->newargv[0], child->newargv))
260    {
261        perror(child->newargv[0]);
262        exit(EXIT_FAILURE);
263    }
264
265    exit(EXIT_SUCCESS);
266    /* no return */
267    return 0;
268#elif HAVE_WINDOWS_H
269    pid = GetCurrentProcess();
270
271    /* Inherit standard handles */
272    memset(&sinfo, 0, sizeof(sinfo));
273    sinfo.cb = sizeof(sinfo);
274    sinfo.hStdInput = INVALID_HANDLE_VALUE;
275    sinfo.hStdOutput = (HANDLE)_get_osfhandle(pipes[2][1]);
276    sinfo.hStdError = (HANDLE)_get_osfhandle(pipes[1][1]);
277    sinfo.dwFlags = STARTF_USESTDHANDLES;
278
279    /* Build the commandline */
280    for (i = 0, len = 0; child->newargv[i]; i++)
281        len += strlen(child->newargv[i]) + 1;
282    cmdline = malloc(len);
283    for (i = 0, len = 0; child->newargv[i]; i++)
284    {
285        strcpy(cmdline + len, child->newargv[i]);
286        len += strlen(child->newargv[i]) + 1;
287        cmdline[len - 1] = ' ';
288    }
289    cmdline[len - 1] = '\0';
290
291    /* Create the process in suspended state */
292    ret = CreateProcess(child->newargv[0], cmdline, NULL, NULL, TRUE,
293                        CREATE_SUSPENDED, NULL, NULL, &sinfo, &pinfo);
294    free(cmdline);
295
296    if (!ret)
297        return -1;
298
299    /* Insert the replacement code */
300    ret = dll_inject(&pinfo, SONAME);
301    if(ret < 0)
302    {
303        TerminateProcess(pinfo.hProcess, -1);
304        return -1;
305    }
306
307    ret = ResumeThread(pinfo.hThread);
308    if(ret < 0)
309    {
310        TerminateProcess(pinfo.hProcess, -1);
311        return -1;
312    }
313
314    return (long int)pinfo.hProcess;
315#endif
316}
317
318#if defined HAVE_WINDOWS_H
319static void rep32(uint8_t *buf, void *addr)
320{
321    while(buf++)
322        if (memcmp(buf, "____", 4) == 0)
323        {
324            memcpy(buf, &addr, 4);
325            return;
326        }
327}
328
329static int dll_inject(PROCESS_INFORMATION *pinfo, char const *lib)
330{
331    static uint8_t const loader[] =
332        /* Load the injected DLL into memory */
333        "\xb8____"       /* mov %eax, <library_name_address> */
334        "\x50"           /* push %eax */
335        "\xb8____"       /* mov %eax, <LoadLibraryA> */
336        "\xff\xd0"       /* call %eax */
337        /* Restore the clobbered entry point code using our backup */
338        "\xb8\0\0\0\0"   /* mov %eax,0 */
339        "\x50"           /* push %eax */
340        "\xb8____"       /* mov %eax, <jumper_length> */
341        "\x50"           /* push %eax */
342        "\xb8____"       /* mov %eax, <backuped_entry_point_address> */
343        "\x50"           /* push %eax */
344        "\xb8____"       /* mov %eax, <original_entry_point_address> */
345        "\x50"           /* push %eax */
346        "\xb8____"       /* mov %eax, <GetCurrentProcess> */
347        "\xff\xd0"       /* call %eax */
348        "\x50"           /* push %eax */
349        "\xb8____"       /* mov %eax, <WriteProcessMemory> */
350        "\xff\xd0"       /* call %eax */
351        /* Jump to the original entry point */
352        "\xb8____"       /* mov %eax, <original_entry_point_address> */
353        "\xff\xe0";      /* jmp %eax */
354
355    static uint8_t const waiter[] =
356        "\xeb\xfe";      /* jmp <current> */
357
358    static uint8_t const jumper[] =
359        /* Jump to the injected loader */
360        "\xb8____"       /* mov eax, <loader_address> */
361        "\xff\xe0";      /* jmp eax */
362
363    CONTEXT ctx;
364    void *process = pinfo->hProcess;
365    void *thread = pinfo->hThread;
366    void *epaddr;
367    DWORD pid = pinfo->dwProcessId;
368
369    /* code:
370     * +---------------+--------------------+--------------+-------------+
371     * |     loader    | entry point backup | library name |   jumper    |
372     * |  len(loader)  |    len(jumper)     |   len(lib)   | len(jumper) |
373     * +---------------+--------------------+--------------+-------------+ */
374    uint8_t code[1024];
375
376    uint8_t *loaderaddr;
377    size_t liblen, loaderlen, waiterlen, jumperlen;
378    DWORD tmp;
379
380    liblen = strlen(lib) + 1;
381    loaderlen = sizeof(loader) - 1;
382    waiterlen = sizeof(waiter) - 1;
383    jumperlen = sizeof(jumper) - 1;
384    if (loaderlen + jumperlen + liblen > 1024)
385        return -1;
386
387    /* Allocate memory in the child for our injected code */
388    loaderaddr = VirtualAllocEx(process, NULL, loaderlen + jumperlen + liblen,
389                                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
390    if(!loaderaddr)
391        return -1;
392
393    /* Create the first shellcode (jumper).
394     *
395     * The jumper's job is simply to jump at the second shellcode's location.
396     * It is written at the original entry point's location, which will in
397     * turn be restored by the second shellcode.
398     */
399    memcpy(code + loaderlen + jumperlen + liblen, jumper, jumperlen);
400    rep32(code + loaderlen + jumperlen + liblen, loaderaddr);
401
402    /* Create the second shellcode (loader, backuped entry point, and library
403     * name).
404     *
405     * The loader's job is to load the library by calling LoadLibraryA(),
406     * restore the original entry point using the backup copy, and jump
407     * back to the original entry point as if the process had just started.
408     *
409     * The second shellcode is written at a freshly allocated memory location.
410     */
411    memcpy(code, loader, loaderlen);
412    memcpy(code + loaderlen + jumperlen, lib, liblen);
413
414    /* Find the entry point address. It's simply in EAX. */
415    ctx.ContextFlags = CONTEXT_FULL;
416    GetThreadContext(thread, &ctx);
417    epaddr = (void *)(uintptr_t)ctx.Eax;
418
419    /* Backup the old entry point code */
420    ReadProcessMemory(process, epaddr, code + loaderlen, jumperlen, &tmp);
421    if(tmp != jumperlen)
422        return -1;
423
424    /* Replace the entry point code with a short jump to self, then resume
425     * the thread. This is necessary for CreateToolhelp32Snapshot() to
426     * work. */
427    WriteProcessMemory(process, epaddr, waiter, waiterlen, &tmp);
428    if(tmp != waiterlen)
429        return -1;
430    FlushInstructionCache(process, epaddr, waiterlen);
431    ResumeThread(thread);
432
433    /* Wait until the entry point is reached */
434    for (tmp = 0; tmp < 100; tmp++)
435    {
436        CONTEXT ctx;
437        ctx.ContextFlags = CONTEXT_FULL;
438        GetThreadContext(thread, &ctx);
439        if ((uintptr_t)ctx.Eip == (uintptr_t)epaddr)
440            break;
441        Sleep(10);
442    }
443    SuspendThread(thread);
444    if (tmp == 100)
445        return -1;
446
447    /* Remotely parse the target process's module list to get the addresses
448     * of the functions we need. This can only be done because we advanced
449     * the target's execution to the entry point. */
450    rep32(code, loaderaddr + loaderlen + jumperlen);
451    rep32(code, (void *)get_proc_address(process, pid, "LoadLibraryA"));
452    rep32(code, (void *)(uintptr_t)jumperlen);
453    rep32(code, loaderaddr + loaderlen);
454    rep32(code, epaddr);
455    rep32(code, (void *)get_proc_address(process, pid, "GetCurrentProcess"));
456    rep32(code, (void *)get_proc_address(process, pid, "WriteProcessMemory"));
457    rep32(code, epaddr);
458
459    /* Write our shellcodes into the target process */
460    WriteProcessMemory(process, epaddr, code + loaderlen + jumperlen + liblen,
461                       jumperlen, &tmp);
462    if(tmp != jumperlen)
463        return -1;
464    FlushInstructionCache(process, epaddr, waiterlen);
465
466    WriteProcessMemory(process, loaderaddr, code,
467                       loaderlen + jumperlen + liblen, &tmp);
468    if(tmp != loaderlen + jumperlen + liblen)
469        return -1;
470
471    return 0;
472}
473
474static intptr_t get_proc_address(void *process, DWORD pid, const char *func)
475{
476    char buf[1024];
477    size_t buflen = strlen(func) + 1;
478
479    MODULEENTRY32 entry;
480    intptr_t ret = 0;
481    DWORD tmp;
482    void *list;
483    int i, k;
484
485    list = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
486    entry.dwSize = sizeof(entry);
487    for(k = Module32First(list, &entry); k; k = Module32Next(list, &entry))
488    {
489        IMAGE_DOS_HEADER dos;
490        IMAGE_NT_HEADERS nt;
491        IMAGE_EXPORT_DIRECTORY expdir;
492
493        uint32_t exportaddr;
494        uint8_t const *base = entry.modBaseAddr;
495
496        if (strcmp("kernel32.dll", entry.szModule))
497            continue;
498
499        ReadProcessMemory(process, base, &dos, sizeof(dos), &tmp);
500        ReadProcessMemory(process, base + dos.e_lfanew, &nt, sizeof(nt), &tmp);
501
502        exportaddr = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
503        if (!exportaddr)
504            continue;
505
506        ReadProcessMemory(process, base + exportaddr, &expdir, sizeof(expdir), &tmp);
507
508        for (i = 0; i < (int)expdir.NumberOfNames; i++)
509        {
510            uint32_t nameaddr, funcaddr;
511            uint16_t j;
512
513            /* Look for our function name in the list of names */
514            ReadProcessMemory(process, base + expdir.AddressOfNames
515                                            + i * sizeof(DWORD),
516                              &nameaddr, sizeof(nameaddr), &tmp);
517            ReadProcessMemory(process, base + nameaddr, buf, buflen, &tmp);
518
519            if (strcmp(buf, func))
520                continue;
521
522            /* If we found a function with this name, return its address */
523            ReadProcessMemory(process, base + expdir.AddressOfNameOrdinals
524                                            + i * sizeof(WORD),
525                                &j, sizeof(j), &tmp);
526            ReadProcessMemory(process, base + expdir.AddressOfFunctions
527                                            + j * sizeof(DWORD),
528                                &funcaddr, sizeof(funcaddr), &tmp);
529
530            ret = (intptr_t)base + funcaddr;
531            goto _finished;
532        }
533    }
534
535_finished:
536    CloseHandle(list);
537    return ret;
538}
539
540#endif
Note: See TracBrowser for help on using the repository browser.