POSIX CPU Timers TOCTOU race (CVE-2025-38352)
Reading time: 7 minutes
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.
이 페이지는 Linux/Android POSIX CPU timers에서 발생하는 TOCTOU race condition을 문서화하며, 타이머 상태를 손상시키고 kernel을 충돌시킬 수 있고, 특정 상황에서는 privilege escalation으로 이어질 수 있다.
- 영향받는 구성요소: kernel/time/posix-cpu-timers.c
- Primitive: task exit 시 expiry vs deletion race
- 설정에 민감: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
내부 동작 빠른 요약 (exploitation에 관련됨)
- 세 가지 CPU 클럭이 cpu_clock_sample()을 통해 타이머의 계정(accounting)을 담당한다:
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: utime only
- CPUCLOCK_SCHED: task_sched_runtime()
- 타이머 생성은 타이머를 task/pid에 연결하고 timerqueue 노드를 초기화한다:
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에 항목을 삽입하고 next-expiry cache를 업데이트할 수 있습니다:
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;
}
- 빠른 경로는 캐시된 만료가 타이머 발동 가능성을 나타내지 않는 한 비용이 큰 처리를 피한다:
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은 만료된 타이머를 수집하고, 발동 상태로 표시하며, 큐에서 제거합니다; 실제 전달은 연기됩니다:
#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의 task_work를 통해 연기된다
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n: 만료는 IRQ 컨텍스트에서 직접 처리된다
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 경로에서는 firing list가 sighand 바깥에서 처리됩니다.
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: IRQ 시점의 만료와 태스크 종료 중 동시 삭제 간의 TOCTOU
Preconditions
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK is disabled (IRQ path in use)
- 대상 태스크가 종료 중이지만 완전히 회수(reaped)되지는 않음
- 동일한 타이머에 대해 다른 스레드가 동시에 posix_cpu_timer_del()을 호출함
Sequence
- update_process_times()가 종료 중인 태스크에 대해 IRQ 컨텍스트에서 run_posix_cpu_timers()를 트리거함.
- collect_timerqueue()가 ctmr->firing = 1로 설정하고 타이머를 임시 firing 리스트로 이동시킴.
- handle_posix_cpu_timers()는 unlock_task_sighand()를 통해 sighand를 해제하여 락 밖에서 타이머를 전달하게 함.
- unlock 직후 종료 중인 태스크가 reaped될 수 있으며, 형제 스레드가 posix_cpu_timer_del()을 실행함.
- 이 창에서 posix_cpu_timer_del()은 cpu_timer_task_rcu()/lock_task_sighand()를 통해 state 획득에 실패할 수 있고, 그 결과 timer->it.cpu.firing을 확인하는 일반적인 in-flight 가드를 건너뛸 수 있음. 삭제가 firing이 아닌 것처럼 진행되어 만료 처리 중 상태를 손상시키며, 이는 충돌/crashes나 UB로 이어짐.
Why TASK_WORK mode is safe by design
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y인 경우 만료는 task_work로 연기되고, exit_task_work가 exit_notify보다 먼저 실행되므로 IRQ 시점의 reaping과의 겹침이 발생하지 않음.
- 그럼에도 불구하고 태스크가 이미 종료 중이면 task_work_add()는 실패함; exit_state로 게이팅하면 두 모드가 일관되게 동작함.
Fix (Android common kernel) and rationale
- 현재 태스크가 종료 중이면 모든 처리를 게이팅하도록 조기 리턴을 추가함:
// 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
- 종료 직전인 스레드를 대상으로 하여 해당 스레드에 CPU 타이머를 연결합니다(스레드별 또는 프로세스 전체 시계):
- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- IRQ-path 진입을 최대화하기 위해 초기 만료 시간을 매우 짧게 하고 간격을 작게 설정:
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");
}
- 형제 스레드에서 대상 스레드가 종료되는 동안 동일한 타이머를 동시에 삭제:
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
- 경합 증폭 요인: 높은 scheduler tick rate, CPU 부하, 반복적인 thread 종료/재생성 사이클. 크래시는 일반적으로 unlock_task_sighand() 직후 task 조회/잠금에 실패하여 posix_cpu_timer_del()이 firing을 인지하지 못할 때 나타납니다.
Detection and hardening
- Mitigation: exit_state 가드를 적용; 가능하면 CONFIG_POSIX_CPU_TIMERS_TASK_WORK를 활성화하는 것을 권장합니다.
- Observability: unlock_task_sighand()/posix_cpu_timer_del() 주변에 tracepoints/WARN_ONCE를 추가; it.cpu.firing==1이 관측되면서 cpu_timer_task_rcu()/lock_task_sighand()가 실패할 때 알림을 설정; task 종료 주변의 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(): firing 루프 전에 sighand를 드롭함
- posix_cpu_timer_del(): in-flight expiry를 감지하기 위해 it.cpu.firing에 의존; exit/reap 도중 task lookup/lock이 실패하면 이 검사가 건너뛰어짐
Notes for exploitation research
- 공개된 동작은 신뢰할 수 있는 커널 크래시 프리미티브입니다; 이를 권한 상승으로 악용하려면 일반적으로 이 요약의 범위를 벗어나는 추가로 제어 가능한 중첩(객체 수명 또는 write-what-where 영향)이 필요합니다. 모든 PoC는 불안정화를 초래할 수 있으므로 에뮬레이터/VM에서만 실행하세요.
References
- Race Against Time in the Kernel’s Clockwork (StreyPaws)
- Android security bulletin – September 2025
- Android common kernel patch commit 157f357d50b5…
tip
AWS 해킹 배우기 및 연습하기:HackTricks Training AWS Red Team Expert (ARTE)
GCP 해킹 배우기 및 연습하기: HackTricks Training GCP Red Team Expert (GRTE)
Azure 해킹 배우기 및 연습하기:
HackTricks Training Azure Red Team Expert (AzRTE)
HackTricks 지원하기
- 구독 계획 확인하기!
- **💬 디스코드 그룹 또는 텔레그램 그룹에 참여하거나 트위터 🐦 @hacktricks_live를 팔로우하세요.
- HackTricks 및 HackTricks Cloud 깃허브 리포지토리에 PR을 제출하여 해킹 트릭을 공유하세요.