Translated ['src/linux-hardening/privilege-escalation/linux-kernel-explo

This commit is contained in:
Translator 2025-09-30 00:43:31 +00:00
parent 424ffac264
commit a802575624
3 changed files with 392 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,195 @@
# POSIX CPU Timers TOCTOU race (CVE-2025-38352)
{{#include ../../../banners/hacktricks-training.md}}
이 페이지는 Linux/Android POSIX CPU timers에서의 TOCTOU 레이스 조건을 문서화한다. 이 문제는 타이머 상태를 손상시키고 커널을 크래시시킬 수 있으며, 특정 상황에서는 권한 상승으로 유도될 수도 있다.
- 영향받는 컴포넌트: kernel/time/posix-cpu-timers.c
- 프리미티브: 작업 종료(task exit) 시 만료(expiry)와 삭제(deletion) 간의 레이스
- 설정 민감: 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;
}
```
- Arming은 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;
}
```
- 빠른 경로는 캐시된 만료 항목들이 발동 가능성을 나타내지 않는 한 비용이 많이 드는 처리를 피합니다:
```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;
}
```
- 만료는 만료된 타이머를 수집하고, firing으로 표시하며, 큐에서 제거합니다; 실제 전달은 연기됩니다:
```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를 통해 연기됨
- 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 경로에서는 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
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()이 그것을 놓치고 cpu.firing과 만료 처리와 경쟁하는 창을 제거합니다.
Impact
- 만료/삭제가 동시에 발생하는 동안 타이머 구조체에 대한 커널 메모리 손상은 즉시 충돌(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
- 종료하려는 스레드를 타깃으로 삼아 CPU 타이머를 연결합니다 (스레드별 또는 프로세스 전체 시계):
- 스레드별의 경우: timer_create(CLOCK_THREAD_CPUTIME_ID, ...)
- 프로세스 전체의 경우: timer_create(CLOCK_PROCESS_CPUTIME_ID, ...)
- 매우 짧은 초기 만료 시간과 짧은 간격으로 설정하여 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");
}
```
- 형제 스레드에서 대상 스레드가 종료되는 동안 동일한 timer를 동시에 삭제:
```c
void *deleter(void *arg) {
for (;;) (void)timer_delete(t); // hammer delete in a loop
}
```
- 레이스 증폭 요인: 높은 scheduler tick rate, CPU 부하, 반복적인 스레드 종료/재생성 주기. 크래시는 일반적으로 unlock_task_sighand() 직후 task lookup/locking이 실패하여 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(): 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.
## 참고자료
- [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}}
이 페이지는 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:
```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에 삽입하고 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;
}
```
- Fast path는 캐시된 만료(cached expiries)가 발동 가능성을 나타내지 않는 한 비용이 많이 드는 처리를 피합니다:
```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은 만료된 타이머들을 수집하고, firing 상태로 표시한 뒤 큐에서 제거한다; 실제 전달은 연기된다:
```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의 task_work를 통해 만료 처리가 연기됨
- 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 경로에서는 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)
- 대상 task가 종료 중이지만 아직 완전히 정리(reaped)되지 않음
- 다른 스레드가 동일한 타이머에 대해 posix_cpu_timer_del()을(를) 동시 호출함
시퀀스
1) update_process_times()가 종료 중인 task에 대해 IRQ 컨텍스트에서 run_posix_cpu_timers()를 트리거함.
2) collect_timerqueue()가 ctmr->firing = 1로 설정하고 타이머를 임시 firing 리스트로 이동함.
3) handle_posix_cpu_timers()가 unlock_task_sighand()로 sighand를 해제하여 락 밖에서 타이머를 전달함.
4) unlock 직후에 종료 중인 task가 reaped될 수 있으며, 형제 스레드가 posix_cpu_timer_del()을 실행함.
5) 이 창에서 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가 종료 중이면 조기 리턴을 추가하여 모든 처리를 게이팅함:
```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을 놓치고 만료 처리(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 진입을 최대화하세요:
```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
}
```
- 경쟁 증폭 요인: 높은 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 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}}