Translated ['src/binary-exploitation/linux-kernel-exploitation/posix-cpu

This commit is contained in:
Translator 2025-09-30 00:43:03 +00:00
parent bffd374842
commit 73ade3bffd
3 changed files with 393 additions and 0 deletions

View File

@ -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)

View File

@ -0,0 +1,196 @@
# POSIX CPU Timers TOCTOU race (CVE-2025-38352)
{{#include ../../../banners/hacktricks-training.md}}
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.
- Etkilenen bileşen: kernel/time/posix-cpu-timers.c
- Primitive: expiry vs deletion race under task exit
- Konfigürasyona duyarlı: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
Kısa içyapı özeti (exploitation açısından ilgili)
- Zamanlayıcıların muhasebesini cpu_clock_sample() aracılığıyla yöneten üç CPU saati:
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: sadece utime
- CPUCLOCK_SCHED: task_sched_runtime()
- Timer creation wires a timer to a task/pid and initializes the timerqueue nodes:
```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, bir per-base timerqueue'ya ekleme yapar ve next-expiry cache'i güncelleyebilir:
```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;
}
```
- Hızlı yol, önbelleğe alınmış süresi dolma kayıtları olası tetiklemeyi göstermedikçe pahalı işlemden kaçınır:
```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, süresi dolan timer'ları toplar, onları 'firing' (tetikleniyor) olarak işaretler, kuyruğun dışına taşır; gerçek teslimat ertelenir:
```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;
}
```
İki sona erme işleme modu
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: sona erme hedef görevde task_work aracılığıyla ertelenir
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: sona erme doğrudan IRQ bağlamında işlenir
```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
```
IRQ-context yolunda, firing list sighand dışında işlenir.
```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);
}
}
```
Kök neden: IRQ-time sona ermesi ile görev çıkışı sırasında eşzamanlı silme arasında TOCTOU
Önkoşullar
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK devre dışı (IRQ path kullanılıyor)
- Hedef görev çıkışta ancak tamamen reaped değil
- Başka bir thread aynı timer için eşzamanlı olarak posix_cpu_timer_del() çağırıyor
Sıra
1) update_process_times() çıkışta olan görev için IRQ bağlamında run_posix_cpu_timers() tetikler.
2) collect_timerqueue() ctmr->firing = 1 olarak ayarlar ve timer'ı geçici firing listesine taşır.
3) handle_posix_cpu_timers() timer'ları kilit dışından teslim etmek için unlock_task_sighand() ile sighand'i bırakır.
4) Kilidin hemen ardından, çıkışta olan görev reaped edilebilir; kardeş bir thread posix_cpu_timer_del() çalıştırır.
5) Bu pencerede, posix_cpu_timer_del() cpu_timer_task_rcu()/lock_task_sighand() aracılığıyla state edinmeyi başaramayabilir ve bu nedenle timer->it.cpu.firing'i kontrol eden normal in-flight guard'ı atlayabilir. Silme, firing değilmiş gibi devam eder; expiry işlenirken state bozulur ve crash/UB ile sonuçlanır.
Neden TASK_WORK modu tasarım gereği güvenlidir
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y ile expiry task_work'a ertelenir; exit_task_work exit_notify'dan önce çalışır, bu nedenle IRQ-time ile reaping arasındaki çakışma oluşmaz.
- Yine de, görev zaten çıkışta ise task_work_add() başarısız olur; exit_state üzerinde gate koymak her iki modu tutarlı kılar.
Fix (Android common kernel) ve gerekçe
- current görev çıkışta ise tüm işlemleri engelleyen erken bir return ekleyin:
```c
// kernel/time/posix-cpu-timers.c (Android common kernel commit 157f357d50b5038e5eaad0b2b438f923ac40afeb)
if (tsk->exit_state)
return;
```
- Bu, çıkmakta olan görevler için handle_posix_cpu_timers()'e girilmeyi engeller ve posix_cpu_timer_del()'ın cpu.firing'i kaçırıp expiry processing ile yarışabileceği pencereyi ortadan kaldırır.
Impact
- Eşzamanlı süresi dolma/silme sırasında timer yapılarında oluşan kernel bellek bozulması, anında çöküşlere (DoS) yol açabilir ve keyfi kernel-durum manipülasyonu fırsatları nedeniyle ayrıcalık yükseltme yönünde güçlü bir primitive teşkil eder.
Triggering the bug (safe, reproducible conditions)
Build/config
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n olduğundan emin olun ve exit_state gating fix'i olmayan bir kernel kullanın.
Runtime strategy
- Çıkmak üzere olan bir iş parçacığını hedefleyin ve ona bir CPU timer iliştirin (per-thread veya process-wide clock):
- İş parçacığı başına: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- Süreç geneli için: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- IRQ-path girişlerini maksimize etmek için ilk expiration'ı çok kısa ve aralığı küçük olacak şekilde kurun:
```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");
}
```
- Bir kardeş iş parçacığından, hedef iş parçacığı çıkış yaparken aynı timer'ı eşzamanlı olarak sil:
```c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
```
- Yarış koşulunu artıran etkenler: yüksek zamanlayıcı tick hızı, CPU yükü, tekrar eden iş parçacığı çıkış/yeniden oluşturma döngüleri. Çökme genellikle posix_cpu_timer_del()'in unlock_task_sighand()'den hemen sonra görev arama/lock işleminin başarısız olması nedeniyle firing'i fark etmeyi atladığı durumda görülür.
Tespit ve sertleştirme
- Azaltma: exit_state guard'ını uygula; mümkünse CONFIG_POSIX_CPU_TIMERS_TASK_WORK'ı etkinleştirmeyi tercih et.
- Gözlemlenebilirlik: unlock_task_sighand()/posix_cpu_timer_del() etrafına tracepoints/WARN_ONCE ekle; it.cpu.firing==1'in cpu_timer_task_rcu()/lock_task_sighand() başarısızlığıyla birlikte gözlendiğinde uyarı oluştur; task çıkışı etrafında timerqueue tutarsızlıklarını izle.
Denetim sıcak noktaları (inceleyiciler için)
- 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
İstismar araştırması notları
- Açıklanan davranış güvenilir bir kernel crash primitive'idir; bunu privilege escalation'a dönüştürmek tipik olarak bu özetin kapsamı dışında ek bir kontrollü overlap (object lifetime veya write-what-where etkisi) gerektirir. Herhangi bir PoC'yi potansiyel olarak kararsızlaştırıcı olarak değerlendirin ve yalnızca emülatörlerde/VM'lerde çalıştırın.
## Referanslar
- [Race Against Time in the Kernels 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}}

View File

@ -0,0 +1,195 @@
# POSIX CPU Timers TOCTOU race (CVE-2025-38352)
{{#include ../../../banners/hacktricks-training.md}}
Bu sayfa, Linux/Android POSIX CPU timers'daki bir TOCTOU yarış durumunu belgeler; bu durum timer durumunu bozabilir ve kernel'in çökmesine neden olabilir ve bazı durumlarda privilege escalation yönünde kullanılabilir.
- Etkilenen bileşen: kernel/time/posix-cpu-timers.c
- İlkel: expiry vs deletion race under task exit
- Yapılandırmaya duyarlı: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
Kısa iç yapı özeti (exploitation için ilgili)
- Timerların muhasebesini cpu_clock_sample() aracılığıyla yöneten üç CPU saati:
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: sadece utime
- CPUCLOCK_SCHED: task_sched_runtime()
- Timer oluşturma, bir timer'ı bir task/pid'ye bağlar ve timerqueue düğümlerini başlatır:
```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, per-base timerqueue'ye ekleme yapar ve next-expiry cache'i güncelleyebilir:
```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;
}
```
- Hızlı yol, önbelleğe alınmış sona erme bilgileri olası tetiklemeyi gösterdiği durumlar dışında pahalı işlemlerden kaçınır:
```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, süresi dolmuş zamanlayıcıları toplar, bunları tetiklenmiş olarak işaretler, kuyruğun dışına taşır; gerçek teslimat ertelenir:
```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;
}
```
İki zaman aşımı işleme modu
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: sona erme hedef görevde task_work aracılığıyla ertelenir
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: sona erme doğrudan IRQ bağlamında işlenir
```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
```
IRQ-context path'te, firing list sighand dışında işlenir.
```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;
```
- Bu, çıkmakta olan görevler için handle_posix_cpu_timers()'e girilmesini engeller; böylece posix_cpu_timer_del()'in it.cpu.firing'i kaçırabileceği ve expiry işleme ile yarışabileceği pencere ortadan kalkar.
Impact
- Eşzamanlı sona erme/silme sırasında timer yapılarının kernel belleğinin bozulması, anında çöküşlere (DoS) yol açabilir ve keyfi kernel-durumu manipülasyonu fırsatları nedeniyle yetki yükseltmeye yönelik güçlü bir primitive sağlar.
Triggering the bug (safe, reproducible conditions)
Build/config
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n olduğundan emin olun ve exit_state gating fix'i içermeyen bir kernel kullanın.
Runtime strategy
- Çıkmak üzere olan bir iş parçacığını hedefleyin ve ona bir CPU timer iliştirin (per-thread veya process-wide clock):
- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- Çok kısa bir ilk expiration ve küçük bir interval ile silahlandırın; böylece IRQ-path girişlerini maksimize edin:
```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");
}
```
- Bir kardeş thread'ten, hedef thread çıkarken aynı timer'ı eşzamanlı olarak silin:
```c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
```
- Race artırıcıları: yüksek scheduler tick hızı, CPU yükü, tekrarlayan thread çıkış/yeniden oluşturma döngüleri. Çökme tipik olarak, unlock_task_sighand()'den hemen sonra task lookup/locking başarısız olduğunda posix_cpu_timer_del() firing'i kaçırdığında ortaya çıkar.
Tespit ve sertleştirme
- Önlem: exit_state guard'ını uygulayın; mümkünse CONFIG_POSIX_CPU_TIMERS_TASK_WORK'u etkinleştirmeyi tercih edin.
- Gözlemlenebilirlik: unlock_task_sighand()/posix_cpu_timer_del() etrafına tracepoints/WARN_ONCE ekleyin; it.cpu.firing==1 gözlemlendiğinde ve aynı zamanda cpu_timer_task_rcu()/lock_task_sighand() başarısız olduğunda uyarı verin; task çıkışı çevresinde timerqueue tutarsızlıklarını izleyin.
Denetim sıcak noktaları (inceleyenler için)
- update_process_times() → run_posix_cpu_timers() (IRQ)
- __run_posix_cpu_timers() selection (TASK_WORK vs IRQ path)
- collect_timerqueue(): ctmr->firing'i ayarlar ve düğümleri taşır
- handle_posix_cpu_timers(): firing döngüsünden önce sighand'i düşürür
- posix_cpu_timer_del(): it.cpu.firing'e dayanarak uçuşta olan timeout'ı tespit eder; task lookup/lock exit/reap sırasında başarısız olduğunda bu kontrol atlanır
Sömürme araştırması notları
- Açıklanan davranış güvenilir bir kernel çökme primitive'idir; bunu privilege escalation'a dönüştürmek genellikle bu özetin kapsamı dışında kalan ek bir kontrol edilebilir çakışma (object lifetime veya write-what-where etkisi) gerektirir. Herhangi bir PoC'yi potansiyel olarak kararsızlaştırıcı kabul edin ve yalnızca emulators/VMs üzerinde çalıştırın.
## Referanslar
- [Race Against Time in the Kernels 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}}