[CVE-2022-1786] A Journey To The Dawn
A race condition in the Linux kernel's io_uring subsystem causes a type confusion when a thread exits while reissuing I/O requests, leading to an invalid free of a pointer inside an io_uring_task object. An attacker could exploit this to achieve privilege escalation and container escape.
Back in April, I found a 0-day vulnerability in the Linux kernel and exploited it on Google’s kCTF platform. I reported the bug to Linux kernel security team and helped them fix the vulnerability.
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 is a write-up of CVE-2022-1786, a Linux kernel vulnerability in the io_uring subsystem, found, analysed, exploited and reported by kylebot (@ky1ebot). The exploit was submitted to Google's kCTF platform and, according to the author, was granted the first full bounty in kCTF's history at $91,337. The bug was reported to the Linux kernel security team, and the author helped them fix the vulnerability.
The affected code is io_uring, a Linux subsystem designed to speed up IO operations. Traditionally, performing many IO operations in a short time requires many privilege transitions through system calls, which is time-consuming, especially with KPTI enabled because of the constant TLB flushes. io_uring lets a program submit a series of IO operations (or IO-related actions such as timeouts) to the kernel directly, and the kernel performs them in parallel in different task contexts without a privilege transition. The author notes this design gives much faster IO performance than the older aio implementation, so it is growing in popularity and developing rapidly. Rapid development means more bugs: the author cites several severe io_uring privilege-escalation bugs from the previous two years, including CVE-2021-41073 (exploited by @chompie1337) and CVE-2022-29582 (exploited by @Awarau and @pql).
The bug specifically concerns Linux kernel v5.10, "because of its unique identity model". The write-up is deliberately not a tutorial on the correct way to exploit the bug; it documents the seven days the author spent developing the exploit, including the dead ends.
Setup
The target environment is Google's kCTF platform, which runs Container-Optimized OS (COS). The author also reproduced work on a VM on Google Cloud with the same kernel, and later tested a proof of concept on a Pixel 6 running Android.
Relevant kernel configuration and environment facts stated in the report:
CONFIG_HARDENED_USERCOPYis enabled in most vendor kernels and is enabled in COS, the kernel used in kCTF and Google Cloud.CONFIG_SLAB_FREELIST_HARDENEDis enabled in the target kernel.- The target cache is
kmalloc-256, and eachkmalloc-256slab has 16 slots. - On kCTF the access is inside a Docker container whose filesystem base is overlayfs.
- The only writeable region on kCTF's platform is tmpfs.
- If the kCTF VM crashes, it takes about 5 minutes to reboot.
The author had previously pwned kCTF twice (CVE-2021-4154 and CVE-2022-29581).
Finding it
The vulnerability is a false assumption about which task the function __io_req_init_async can run in. The vulnerable code assumes the request (req, the IO operation request) is submitted by itself (current), so it assigns its own identity to the request's work.
That assumption is wrong. If two tasks (threads) submit IO requests to the same io_uring at the same time, the two requests may be submitted into one work queue and associated with different request tasks, which is by design and expected. If one of the threads is trying to exit (for example, by calling execve) when IORING_SETUP_IOPOLL is enabled, that specific thread tries to reap all the IO events in the work queue to make sure they finish.
If IO events are not finished, io_uring attempts to reissue the request and tries its best to finish it (the io_iopoll_complete call). This time the new request is initialised in io_req_init_async, invoked in a deep call chain from io_iopoll_complete, in the thread that is trying to exit, which may differ from the threads that issued the original requests.
As a result, in io_req_init_async, current->io_uring (the exiting thread's io_uring context) may not be req->task->io_uring (the request submitter's io_uring context), and a wrong identity is assigned to req->work.identity.
Later, when the kernel finishes the IO event and destroys the io_uring related objects, it uses io_put_identify(req->task->io_uring, req), which uses the submitter's io_uring context (req->task->io_uring). Because tctx->identity is &tctx->__identity (the identity field is a pointer to __identity, the identity struct embedded in struct io_uring_task), req->work.identity != &tctx->__identity. The kernel therefore thinks req->work.identity is a heap object and tries to free it, while in reality it is a pointer to the middle of the exiting thread's struct io_uring_task. This is a type confusion that triggers an invalid free.
Exploitation
Primitive analysis
The symptom is an invalid free in struct io_uring_task, an object in kmalloc-256. The freed pointer is &io_uring_task->__identify, at offset 0x90 inside an io_uring_task object. An invalid slot is added to the slab's freelist.
The diagram illustrates the invalid slot being added to the slab's freelist.
The obvious plan, allocating victim objects at the upper and lower slots and using a heap spray object to occupy the invalid slot, runs into CONFIG_HARDENED_USERCOPY. That protection does not allow copy_from_user to copy user data across a slot boundary. If a heap spray object such as msg_msg occupies the invalid slot, the copy_from_user call is detected and the kernel panics. The author checked all known heap spray objects at the time and none bypassed the protection.
Two methods to spray user data without copy_from_user were known to the author:
- The
copy_msglogic inmsg_msg, where user data is copied into the newmsg_msgobject usingmemcpy. This spray is transient: it allocates themsg_msg, writes the data, and frees themsg_msg. The author considers this bad for reliability because it does not hold the memory, and never tried it. simple_xattr, which also usesmemcpyto save user data. The author knew about it from the previous year (starlabs published a write-up in June) but did not use it because he wanted to keep the technique for this exploit, since kCTF awards more bounty to exploits with new techniques. He notes that valis had already used this technique in unrevealed submissions to kCTF at the time.
Given these constraints, the author chose a different route: allocate the victim object in the invalid slot and use the upper and lower slots to overwrite the victim object.
Day 1-2: freelist analysis and object selection
Investigating the freelist, the author found that the invalid slot is freed inside the execve call from the exiting thread, and the upper slot (the io_uring_task itself) is freed in a kernel thread. Since execve is the call that triggers the vulnerability, the freelist looks like upper_slot => invalid_slot => .... The lower slot is not involved in the vulnerability itself; it is just a random slot that overlaps with the invalid slot. The author stresses that keeping the freelist in mind proves very important later.
For kmalloc-256, the author found only three interesting objects: struct timerfd_ctx, struct shmid_kernel, and struct msg_queue. Further investigation concluded that only struct timerfd_ctx can be used for leaking KASLR in kCTF's kernel (if the exploit is not run inside a container, shmid_kernel can do it as well). Since struct timerfd_ctx can also be used for obtaining PC control, it was chosen to occupy the invalid slot. Other objects were used for heap fengshui.
Heap fengshui
The goal is to occupy the invalid slot with a struct timerfd_ctx, ideally with both upper and lower slots controlled. If they are not controlled, allocating the struct timerfd_ctx may accidentally overwrite something unexpected and cause a kernel panic. Because the start of the lower slot will be overwritten, the lower slot must be something without headers such as pointers. The author chose msg_msgseg for this purpose.
msg_msgseg is described as a data structure almost full of user data whose content can be read from userspace without freeing the data structure. The only constraint is that the first 8 bytes of msg_msgseg need to be a pointer, and luckily it is NULL when struct timerfd_ctx overwrites into it.
The plan is to use heap grooming to craft a layout where both upper and lower slots are occupied by msg_msgseg and the invalid slot is occupied by a struct timerfd_ctx.
The diagram illustrates the intended heap layout.
The author describes two grooming strategies, for which he is not aware of existing names, so he calls them "digging" and "fencing". The "digging" strategy allocates many payload objects and frees one from the middle so the freed slot is surrounded by payload objects. The "fencing" strategy was mostly used when CONFIG_SLAB_FREELIST_RANDOM was not enabled: freshly created slabs had a linear layout, so allocating many payload objects and freeing every other one surrounds every freed slot with payload objects, creating many "good" freed slots resilient to unexpected heap usage from other kernel components.
The chosen approach combines both. Each kmalloc-256 slab has 16 slots. The author repetitively sprayed 16 msg_msgseg objects to occupy a whole page and dug one hole to ensure one hole in that page, repeating this 64 times. Ideally this creates 64 "good" slots surrounded by msg_msgseg objects, increasing resiliency against unexpected heap usage. Then a struct io_uring_task is allocated in one of the 64 slots, which has a msg_msgseg as its adjacent object, ensuring the lower slot is a msg_msgseg.
Ensuring the upper slot is also controlled is harder. The freelist is upper_slot => invalid_slot. Spraying struct timerfd_ctx means the one in the upper slot is corrupted by the one in the invalid slot. Spraying user-controlled objects like msg_msg causes a kernel panic when it lands on invalid_slot because of CONFIG_HARDENED_USERCOPY.
The approach taken abuses the partial overlap: allocate a struct timerfd_ctx and check whether any msg_msgseg object's content changes. If yes, a timerfd landed on the invalid slot and that specific msg_msgseg is at the lower slot. If not, free the timer just allocated and replace it with a msg_msgseg. This way, when the invalid slot is occupied by struct timerfd_ctx, the upper slot will be a msg_msgseg.
Info leak
With the upper and lower slots both msg_msgseg objects and the invalid slot a struct timerfd_ctx, leaking both the heap address and KASLR is easy.
Leak heap address: struct timerfd_ctx contains a few embedded linked list structs. When those list structs are empty, they contain pointers pointing back to themselves, so the location of the timerfd object in the kernel heap is known.
Bypass KASLR: the author learnt from @FizzBuzz101 that arming the timer (calling timerfd_settime with CLOCK_REALTIME on a timerfd) sets timerfd_ctx->tmr->function to timerfd_tmrproc(), which is a kernel .text pointer.
Let's ROP
With the leaks, there are two choices:
- Overwrite
timerfd_ctx->tmr.function, giving PC control when the timer is triggered. - Free the timerfd and hijack the freelist in the lower slot.
Approach 1 easily reached ROP, but the function is called in interrupt contexts, so the kernel's execution is not associated with any task and cannot directly return to userspace. Worse, there is no known way to end the execution gracefully. The author tried do_task_dead to end the execution, but since it is not a task, the kernel triggers a BUG() and crashes. Two earlier blogs tackle this situation. FuzzBuzz101's approach crashes the kernel shortly after returning to userspace because it is in an interrupt context, which is not supposed to get to userspace. D3v17's approach could not be made to work on the target kernel: the author saw a message like BUG: scheduling while atomic and the kernel crashed.
Stuck, the author went for approach 2. Hijacking the slab freelist is possible because when the invalid slot is freed again, its forward pointer is stored inside the lower slot. In modern Linux, forward pointers are stored in the middle of objects; in kmalloc-256 the offset is 0x80. So the address of the invalid slot's forward pointer is invalid_slot_addr + 0x80 = upper_slot_addr + 0x90 + 0x80 = upper_slot_addr + 0x110 = lower_slot + 0x10.
The target kernel has CONFIG_SLAB_FREELIST_HARDENED enabled, so the freelist is encoded. kileak demonstrated that if ptr_addr (the address the forward pointer is stored at), ptr (the forward pointer itself), and the encoded value are known, then s->random can be calculated and any encoded value forged, hijacking the slab freelist and obtaining arbitrary write. In the current setup only ptr_addr is known and ptr cannot be controlled. But by filling up the whole slab and then freeing the timerfd at the invalid slot, ptr is forced to be NULL (it is the only free slot in the slab), and s->random can be leaked for hijacking the freelist. Using the freelist hijacking primitive, arbitrary write is possible.
binfmt to privilege escalation
With leaks and arbitrary write, if container escape were not needed, overwriting modprobe_path would give root easily. But container escape is needed, so PC control, ROP and escape from the container are required. (The author notes this was true back then, but that he and @BillyQAQ found something interesting a few months afterwards.)
The solution was to overwrite binfmt and then ROP. The author believes this is a new technique (novel technique No.1). Linux loads executables by going through a list of binfmt called formats, using each binfmt's load_binary handler to see whether the executable is recognisable by any format. If not recognisable by any format, it tries to load corresponding kernel modules, which enables the modprobe_path exploitation technique. The logic exists in search_binary_handler. Most importantly, these binfmt structures are writable.
So the arbitrary write primitive overwrites one of the binfmt's load_binary callback functions to get PC control and then ROP. The author chose misc_format because it is after elf_format in the formats list, so PC control is obtained by trying to execute an invalid executable while still being able to execute ELF. ROP starts from there and uses the normal privilege escalation payload to get root. It worked locally.
Day 3-4: Panic No.1
On kCTF, nothing happened: the kernel did not even crash. The author had pwned kCTF twice and had never seen that. A VM on Google Cloud with the same kernel did not crash either. Investigation showed the trigger did not work with tmpfs. The bug can be triggered only if IORING_SETUP_IOPOLL is enabled, and that option can only be enabled if a file can be opened with the O_DIRECT flag. tmpfs does not support O_DIRECT, so writing a huge amount of data to a tmpfs file did not work on kCTF's environment. Writing the data to a non-tmpfs file crashed the VM on Google Cloud.
Panic No.2
The author started reading the kernel source and thinking about other ways to trigger the vulnerability. The root cause is the kernel trying to reissue unfinished IO actions when a thread is exiting. The IO actions do not have to be writes; they can be long reads, so they will not finish before the thread calling exit. A quick proof-of-concept crasher attempted to read a whole library in one go and then sprayed msg_msgseg so that, if the vulnerability is triggered, the kernel crashes by being detected by CONFIG_HARDENED_USERCOPY. It crashed the VM on Google Cloud but still not kCTF's platform.
Panic No.3
Trying to trigger the vulnerability on many large files (libc and other libraries) manually gave the same result: it crashed the cloud VM but not kCTF's kernel. The reason is that the access on kCTF is inside a Docker container whose filesystem base is overlayfs, which does not support O_DIRECT. The author hedges that this may not be true: some files could be opened with O_DIRECT but could not be used to crash the kernel for unknown reasons.
The author scanned the whole filesystem, trying to open every readable file with the O_DIRECT flag, and got a handful. Trying to trigger the vulnerability against each file that could be opened with O_DIRECT, /etc/resolv.conf crashed the kernel. The author later told zplin (@Markak_) about this trick, hopefully assisting him in exploiting CVE-2022-20409, a variant of CVE-2022-1786.
Winning the race
/etc/resolv.conf is too small, just a little bit larger than 100 bytes, so the vulnerability cannot be triggered reliably: the exploit has to race to exit one thread before it finishes reading the file. The answer was to try again and again and side-channel whether the vulnerability is triggered.
The diagram illustrates the side-channel described below.
If the vulnerability is triggered, its freelist forward pointer is written into the lower slot. Since the lower slot is a msg_msgseg object, checking all msg_msgseg objects for changed content infers whether the vulnerability is triggered. This also identifies which msg_msgseg is at the lower slot, which is important for later exploitation such as hijacking the freelist.
The steps are:
- do heap grooming
- try to trigger the vulnerability using a read action (
OP_READ) - check whether it is triggered using the side-channel
- if triggered, go to step 5; if not, rinse and repeat
- hijack the freelist and use binfmt for LPE
A new version implementing this logic achieved a near 100% success rate locally.
Day 5-6: the freelist is wrong
On kCTF the exploit consistently crashed at the same place: when the exploit tried to free the timerfd in the invalid slot. That did not make sense, because the freelist should be upper_slot => invalid_slot, and even with freed slots in between the search algorithm should handle them gracefully, or at least succeed sometimes. On kCTF a VM crash takes about 5 minutes to reboot, and the platform was experiencing bugs at the time: VMs would not reboot after a few crashes, so the author had to keep pinging @sirdarckat to reboot the servers for remote debugging.
Debugging showed nothing wrong with the lower slot: it was a msg_msgseg overlapped with the invalid slot, and the output showed the overlapped region belonged to a timerfd. So the issue had to be the upper slot. Hours of staring at the code and thinking about when the search algorithm might fail consistently gave nothing, and the author went to bed at 3am.
The next morning he wrote down all possible states the upper slot might be in when the timerfd is allocated, no matter how ridiculous, and how to confirm each case. The notes are linked in the original. Testing the hypotheses one by one, the remaining answer, although it did not make sense, was that on kCTF's platform, after the bug is triggered, the freelist is not upper_slot => invalid_slot but invalid_slot => upper_slot. This does not make sense because the invalid slot is freed by the execve system call, which triggers the bug in the first place, and should be freed first no matter what. To this day the author does not know why, but blames Kubernetes for no clear reason, perhaps its cgroup magic making it prioritise the kernel thread that frees the upper slot.
To fix it, the search algorithm was changed: allocate timerfd one by one and check whether the content in the msg_msgseg at the lower slot changes. Once there is a hit, spray a lot of msg_msg. This way:
- locally, where the freelist is
upper_slot => invalid_slot, when the invalid slot is taken, the upper slot will be a timerfd as well (corrupted, but that does not matter as long as it is not used) - on kCTF, where the freelist is
invalid_slot => upper_slot, when the invalid slot is taken by a timerfd, the upper slot is still empty; the sprayedmsg_msgensures the slot is taken by the exploit while not corrupting the timerfd at the invalid slot
This converges the two situations, at least for the invalid and lower slots.
Freelist, what's wrong with you? Again?!
With the heap layout figured out, the exploit got further: it could leak all the information but crashed at the arbitrary write to binfmt. This crash is expected because the arbitrary write corrupts the freelist. Assuming the freelist is initially A => NULL, after hijacking it becomes A => binfmt => corrupted_pointer, and the corrupted pointer cannot be avoided because the freelist is encoded and binfmt is not controlled. After the write on binfmt, one more allocation in kmalloc-256 panics the kernel.
An attempt to fix the corrupted freelist: after the write on binfmt, the freelist has only corrupted_pointer left. Free A again so it becomes A => corrupted_pointer, hijack the freelist again and restore it to A => NULL. This worked fantastically locally but not remotely. The conclusion was that kmalloc-256 is heavily used by many kernel components, so the freelist hijacking method would not work on such a busy server.
The dark before the dawn
After giving up freelist hijacking, the author returned to using timerfd_ctx to ROP, for which a decent amount of work had been done, needing only a way to end the ROP chain gracefully. Once the kernel reaches the msleep call in interrupt context, it starts spamming warning messages in a busy loop. Initially the author thought the kernel was trapped in an infinite loop and did not investigate further. Later, for reasons he no longer remembers, he discovered the kernel was actually fine calling msleep in an interrupt context: the warning messages flooding the console were just warnings, nothing harmful was done. Using dmesg -n 1 to suppress the messages allowed debugging again.
The plan became:
- use the ROP chain to overwrite binfmt
- end the ROP chain "gracefully" with
msleep - in userspace, use the overwritten binfmt to ROP in task context and perform LPE
This version worked locally but not remotely. The kernel crashed when executing the KPTI trampoline, and most weirdly the crash only happened in kCTF; the exploit worked fine locally. Copy-pasting payloads proven to work (basically all the public kCTF exploits at the time) still resulted in kernel panic when trying to return to userspace using the KPTI trampoline. The author even attempted to replicate what Andy Nguyen did in CVE-2021-22555: instead of using the KPTI trampoline, carefully not clobbering rbp in the ROP chain and resuming execution on the original stack instead of the heap. Still the kernel panicked. At 5am the author decided to investigate further the next morning.
Day 7: telefork
The next morning, tired and not wanting to continue, the author decided to burn one more novel technique on this exploit, named telefork (novel technique No.3). He came up with it while developing the exploit for CVE-2022-29581 for kCTF.
The image was generated using ideogram.
The issue is that returning to userspace is not easy; the author suspects the msleep in interrupt context corrupts something in the current task. So he decided not to return to the original task context. The idea of telefork is simple: instead of handling the CPU privilege ring stuff, let the kernel do the work by simply calling fork and then msleep. fork extracts the userspace return address of the current syscall and assigns the value to the newly created task (equivalent to how it works but not exactly; interested readers can look up ret_from_fork). The old task then sleeps forever because of the msleep call, and the newly created task directly starts execution from the extracted return address in userspace. Since privilege escalation is finished before calling fork, the newly created task also has root privilege. Although much happens in kernel space, userspace does not observe it: it thinks it just returned from the execve call (used to trigger the ROP payload in binfmt) with root privilege. It is like the execution teleports from kernel space back to userspace. This time the exploit worked remotely and got the flag on kCTF's platform.
Putting it together
The final working exploit:
- heap grooming to prepare a heap layout
- race with reading
/etc/resolv.confto trigger the vulnerability - use a side-channel in the lower slot (
msg_msgseg) to indicate whether the vulnerability gets triggered - leak KASLR and heap address in the lower slot
- hijack a function pointer in
timerfd_ctx(in the invalid slot) to ROP - overwrite binfmt and then
msleepto "gracefully" end the ROP in interrupt contexts - use the overwritten binfmt to launch a ROP chain in task context and perform LPE
- return to userspace using telefork successfully
Android
@chompie1337 pointed out that io_uring was accessible by unprivileged users in Android back in 2021. Knowing the bug existed in Android as well, the author bought a Pixel 6 and tested it, crashing the freshly bought phone with the proof of concept. After upgrading the phone to the latest version, the proof of concept stopped working: io_uring had been added to the seccomp list in Android, so it is no longer accessible by unprivileged users such as normal apps, but is still accessible by privileged users such as system apps or adb. The author stopped the journey there because of research work.
Root cause
The mistake is the assumption in __io_req_init_async that the request is submitted by current, so current->io_uring is used to assign the request's identity. When a thread exits with IORING_SETUP_IOPOLL enabled, it reaps and reissues unfinished IO events, and the reissued request is initialised in the exiting thread, which may differ from the submitter. The wrong identity is stored in req->work.identity. Later, io_put_identify(req->task->io_uring, req) uses the submitter's context, and because tctx->identity is &tctx->__identity, the comparison req->work.identity != &tctx->__identity holds, so the kernel treats the pointer as a heap object and frees it. The pointer is actually into the middle of the exiting thread's struct io_uring_task, at offset 0x90, producing an invalid free and a type confusion.
Existing defences did not stop the bug itself. CONFIG_HARDENED_USERCOPY did stop the simplest exploitation route, because it does not allow copy_from_user to copy user data across a slot boundary, so a msg_msg spray landing on the invalid slot panics the kernel. CONFIG_SLAB_FREELIST_HARDENED encodes the freelist, but the author shows that knowing ptr_addr, ptr and the encoded value allows calculating s->random and forging encoded values. The report does not say which patch was applied; it only states that the vulnerability was reported to the Linux kernel security team and patched.
Impact
The vulnerability is a memory corruption bug in the Linux kernel io_uring subsystem that the author exploited for local privilege escalation on kCTF. On kCTF, the exploit got the flag and won the first full bounty in kCTF's history at $91,337. The bug existed in Android as well, but on the tested Pixel 6, after an upgrade, io_uring was added to the seccomp list, so it is no longer accessible by unprivileged users such as normal apps, only by privileged users such as system apps or adb. Triggering requires IORING_SETUP_IOPOLL, which requires a file that can be opened with O_DIRECT; on kCTF the only writeable region is tmpfs, which does not support O_DIRECT, and the filesystem base is overlayfs, so the author had to find a readable file that supports O_DIRECT (/etc/resolv.conf). The author also notes that freelist hijacking may be unreliable, or even not feasible, if the target cache is too busy, and says he is not 100% convinced by that conclusion himself.
Fix
The report states that the vulnerability was reported to the Linux kernel security team and patched, but it does not describe the patch itself.
Variants to test
- Other
io_uringoperations that can be reissued on thread exit withIORING_SETUP_IOPOLLenabled, such as long reads instead of writes. A positive result is a crash detected byCONFIG_HARDENED_USERCOPYwhen amsg_msgsegspray is used, or a changedmsg_msgsegcontent indicating the freelist forward pointer was written into the lower slot. - Files that can be opened with
O_DIRECTon a target where the writeable region is tmpfs or overlayfs. A positive result is a kernel crash when the file is read in one go while a thread exits. - The same identity confusion pattern in other kernel subsystems that cache a per-task context pointer and later free it based on a different task's context. A positive result is an invalid free at an offset inside a slab object, visible as a corrupted freelist or a crash under
CONFIG_HARDENED_USERCOPY. - The binfmt
load_binaryoverwrite technique on other kernels whereformatsis writable. A positive result is PC control when executing an invalid executable while ELF execution still works, for example by choosing a format afterelf_formatsuch asmisc_format. - The telefork technique for ending a ROP chain in interrupt context: call
forkand thenmsleep, and check whether the newly created task starts execution from the extracted userspace return address with the escalated privileges. A positive result is a root shell in userspace without a KPTI trampoline crash. - The
msleepin interrupt context withdmesg -n 1to suppress warnings. A positive result is that the kernel keeps running and the warning messages are only warnings, not a fatal condition. - The side-channel search over
msg_msgsegobjects to detect whether the vulnerability was triggered and which object is at the lower slot. A positive result is a changedmsg_msgsegcontent after a trigger attempt. - The freelist hijacking with
CONFIG_SLAB_FREELIST_HARDENEDby forcingptrto NULL through filling the slab and freeing the timerfd. A positive result is a calculateds->randomand a successful arbitrary write, though the author warns this may be unreliable on a busy cache such askmalloc-256.
What happened, in plain words
A security researcher, kylebot (@ky1ebot), found a bug in the Linux kernel, the core program that sits between applications and the computer's hardware. The bug was in a part of the kernel called io_uring, which is a feature that lets programs ask the kernel to do many input/output (IO) operations quickly, without constantly switching back and forth between the program and the kernel. That switching is called a privilege transition, and it is slow.
The bug made the kernel free a piece of memory that it should not free, in a way that could be abused to take control of the machine. This kind of bug is called an invalid free, and here it also involves a type confusion. The researcher worked out how to turn that bug into a full exploit: a program that takes over the kernel and gives the attacker root (administrator) privileges, and even escapes a container (a lightweight isolated environment).
He submitted the exploit to Google's kCTF platform. According to the write-up, his exploit received the first full bounty in kCTF's history, $91,337. He also reported the bug to the Linux kernel security team and helped them fix it.
The write-up is not a step-by-step tutorial on the "correct" way to exploit the bug. Instead, it tells the story of the seven days he spent developing the exploit, including the dead ends, the crashes, and the moments of frustration. This beginner's version explains every technical term and step in plain language, following the same order as the original.
Context
This is a write-up of CVE-2022-1786, a vulnerability in the Linux kernel's io_uring subsystem. CVE stands for Common Vulnerabilities and Exposures: it is a unique identifier for a publicly known security flaw, like a catalogue number. The researcher found, analysed, exploited, and reported it. The exploit was submitted to Google's kCTF platform and, according to the author, was granted the first full bounty in kCTF's history at $91,337. The bug was reported to the Linux kernel security team and patched.
What is io_uring? Normally, when a program wants to read a file or send data over the network, it asks the kernel to do it using a system call. Each system call switches the CPU from user mode (where normal programs run) to kernel mode (where the operating system runs) and back. That switch is called a privilege transition, and it costs time. If a program needs to do thousands of small IO operations, all those switches add up.
io_uring is a Linux subsystem designed to speed this up. A program can put a whole list of IO requests into a shared queue in memory, and the kernel picks them up and performs them, potentially in parallel, without a privilege transition for each one. The author notes this design gives much faster IO performance than the older aio implementation, so it is growing in popularity and developing rapidly.
Rapid development means more bugs. The author cites several severe io_uring privilege-escalation bugs from the previous two years, including CVE-2021-41073 (exploited by @chompie1337) and CVE-2022-29582 (exploited by @Awarau and @pql). Privilege escalation means going from a normal user to an administrator (root) on the machine.
The bug specifically concerns Linux kernel v5.10, "because of its unique identity model". The write-up is deliberately not a tutorial on the correct way to exploit the bug; it documents the seven days the author spent developing the exploit, including the dead ends.
Setup
The target environment is Google's kCTF platform, which runs Container-Optimized OS (COS). COS is a Linux-based operating system made by Google for running containers. The author also reproduced work on a VM (virtual machine) on Google Cloud with the same kernel, and later tested a proof of concept on a Pixel 6 running Android.
A proof of concept (PoC) is a small program that demonstrates that a bug exists, often by crashing the system, without necessarily exploiting it fully.
Relevant kernel configuration and environment facts stated in the report:
CONFIG_HARDENED_USERCOPYis enabled in most vendor kernels and is enabled in COS, the kernel used in kCTF and Google Cloud. This is a kernel defence that checks data copied from user space to kernel space.CONFIG_SLAB_FREELIST_HARDENEDis enabled in the target kernel. This defence encodes the list of free memory slots so that attackers cannot easily forge pointers.- The target cache is
kmalloc-256, and eachkmalloc-256slab has 16 slots. A cache here is a pool of memory blocks of a certain size;kmalloc-256holds blocks of 256 bytes. A slab is a page of memory divided into slots of that size. - On kCTF the access is inside a Docker container whose filesystem base is overlayfs. Docker is a container platform; overlayfs is a layered filesystem often used by containers.
- The only writeable region on kCTF's platform is tmpfs. tmpfs is a filesystem that lives in memory, not on disk.
- If the kCTF VM crashes, it takes about 5 minutes to reboot.
The author had previously pwned kCTF twice (CVE-2021-4154 and CVE-2022-29581). "Pwned" here means successfully exploited the challenge. The exploit was submitted in May and the response came in August.
Finding it
The vulnerability is a false assumption about which task the function __io_req_init_async can run in. A task in Linux is a running program or thread; the kernel keeps track of which task is currently running with a variable called current. The vulnerable code assumes the request (req, the IO operation request) is submitted by itself (current), so it assigns its own identity to the request's work. An identity here is a small structure that records which task owns a request.
That assumption is wrong. If two tasks (threads) submit IO requests to the same io_uring at the same time, the two requests may be submitted into one work queue and associated with different request tasks, which is by design and expected. If one of the threads is trying to exit (for example, by calling execve) when IORING_SETUP_IOPOLL is enabled, that specific thread tries to reap all the IO events in the work queue to make sure they finish. execve is the system call that replaces the current program with a new one. IORING_SETUP_IOPOLL is a mode of io_uring that uses polling for IO completion.
If IO events are not finished, io_uring attempts to reissue the request and tries its best to finish it (the io_iopoll_complete call). This time the new request is initialised in io_req_init_async, invoked in a deep call chain from io_iopoll_complete, in the thread that is trying to exit, which may differ from the threads that issued the original requests.
As a result, in io_req_init_async, current->io_uring (the exiting thread's io_uring context) may not be req->task->io_uring (the request submitter's io_uring context), and a wrong identity is assigned to req->work.identity.
Later, when the kernel finishes the IO event and destroys the io_uring related objects, it uses io_put_identify(req->task->io_uring, req), which uses the submitter's io_uring context (req->task->io_uring). Because tctx->identity is &tctx->__identity (the identity field is a pointer to __identity, the identity struct embedded in struct io_uring_task), req->work.identity != &tctx->__identity. The kernel therefore thinks req->work.identity is a heap object and tries to free it, while in reality it is a pointer to the middle of the exiting thread's struct io_uring_task. This is a type confusion that triggers an invalid free.
In plain terms: the kernel mixes up two different tasks' bookkeeping. It stores a pointer to one task's identity inside a request, then later, using a different task's context, it decides that pointer must point to a separate heap object and frees it. But the pointer actually points into the middle of a larger structure, so the free is invalid. Freeing memory that was not allocated as a separate object can corrupt the kernel's memory management, which is the seed of the exploit.
Exploitation
Primitive analysis
The symptom is an invalid free in struct io_uring_task, an object in kmalloc-256. The freed pointer is &io_uring_task->__identify, at offset 0x90 inside an io_uring_task object. An invalid slot is added to the slab's freelist.
A freelist is the list the kernel keeps of free slots in a slab, so it knows which slots are available for allocation. Adding an invalid slot means the kernel now believes a slot is free when it is actually in the middle of a live object.
The diagram illustrates the invalid slot being added to the slab's freelist.
The obvious plan, allocating victim objects at the upper and lower slots and using a heap spray object to occupy the invalid slot, runs into CONFIG_HARDENED_USERCOPY. That protection does not allow copy_from_user to copy user data across a slot boundary. If a heap spray object such as msg_msg occupies the invalid slot, the copy_from_user call is detected and the kernel panics. The author checked all known heap spray objects at the time and none bypassed the protection.
Heap spraying is a technique where the attacker allocates many objects of the same size to fill up memory, hoping one lands in a useful place. copy_from_user is the kernel function that copies data from a user program's memory into kernel memory. CONFIG_HARDENED_USERCOPY checks that such a copy does not cross the boundary of a single allocated slot; if it does, it aborts the kernel (a panic).
Two methods to spray user data without copy_from_user were known to the author:
- The
copy_msglogic inmsg_msg, where user data is copied into the newmsg_msgobject usingmemcpy. This spray is transient: it allocates themsg_msg, writes the data, and frees themsg_msg. The author considers this bad for reliability because it does not hold the memory, and never tried it. simple_xattr, which also usesmemcpyto save user data. The author knew about it from the previous year (starlabs published a write-up in June) but did not use it because he wanted to keep the technique for this exploit, since kCTF awards more bounty to exploits with new techniques. He notes that valis had already used this technique in unrevealed submissions to kCTF at the time.
memcpy is a basic memory copy function that does not perform the same boundary checks as copy_from_user. msg_msg is a kernel structure used for message queues. simple_xattr is a structure used for extended attributes on files.
Given these constraints, the author chose a different route: allocate the victim object in the invalid slot and use the upper and lower slots to overwrite the victim object.
Day 1-2: freelist analysis and object selection
Investigating the freelist, the author found that the invalid slot is freed inside the execve call from the exiting thread, and the upper slot (the io_uring_task itself) is freed in a kernel thread. Since execve is the call that triggers the vulnerability, the freelist looks like upper_slot => invalid_slot => .... The lower slot is not involved in the vulnerability itself; it is just a random slot that overlaps with the invalid slot. The author stresses that keeping the freelist in mind proves very important later.
For kmalloc-256, the author found only three interesting objects: struct timerfd_ctx, struct shmid_kernel, and struct msg_queue. Further investigation concluded that only struct timerfd_ctx can be used for leaking KASLR in kCTF's kernel (if the exploit is not run inside a container, shmid_kernel can do it as well). Since struct timerfd_ctx can also be used for obtaining PC control, it was chosen to occupy the invalid slot. Other objects were used for heap fengshui.
KASLR stands for Kernel Address Space Layout Randomisation: it randomises where the kernel's code and data are placed in memory, so an attacker cannot hardcode addresses. Leaking KASLR means finding out those addresses. PC control means control over the program counter, the CPU register that says which instruction to execute next; if an attacker controls it, they can redirect execution. Heap fengshui is the art of arranging kernel heap memory in a favourable layout by allocating and freeing objects in a careful order.
Heap fengshui
The goal is to occupy the invalid slot with a struct timerfd_ctx, ideally with both upper and lower slots controlled. If they are not controlled, allocating the struct timerfd_ctx may accidentally overwrite something unexpected and cause a kernel panic. Because the start of the lower slot will be overwritten, the lower slot must be something without headers such as pointers. The author chose msg_msgseg for this purpose.
msg_msgseg is described as a data structure almost full of user data whose content can be read from userspace without freeing the data structure. The only constraint is that the first 8 bytes of msg_msgseg need to be a pointer, and luckily it is NULL when struct timerfd_ctx overwrites into it.
The plan is to use heap grooming to craft a layout where both upper and lower slots are occupied by msg_msgseg and the invalid slot is occupied by a struct timerfd_ctx.
The diagram illustrates the intended heap layout.
The author describes two grooming strategies, for which he is not aware of existing names, so he calls them "digging" and "fencing". The "digging" strategy allocates many payload objects and frees one from the middle so the freed slot is surrounded by payload objects. The "fencing" strategy was mostly used when CONFIG_SLAB_FREELIST_RANDOM was not enabled: freshly created slabs had a linear layout, so allocating many payload objects and freeing every other one surrounds every freed slot with payload objects, creating many "good" freed slots resilient to unexpected heap usage from other kernel components.
CONFIG_SLAB_FREELIST_RANDOM is a defence that randomises the order of free slots in a slab, making the fencing strategy less predictable.
The chosen approach combines both. Each kmalloc-256 slab has 16 slots. The author repetitively sprayed 16 msg_msgseg objects to occupy a whole page and dug one hole to ensure one hole in that page, repeating this 64 times. Ideally this creates 64 "good" slots surrounded by msg_msgseg objects, increasing resiliency against unexpected heap usage. Then a struct io_uring_task is allocated in one of the 64 slots, which has a msg_msgseg as its adjacent object, ensuring the lower slot is a msg_msgseg.
Ensuring the upper slot is also controlled is harder. The freelist is upper_slot => invalid_slot. Spraying struct timerfd_ctx means the one in the upper slot is corrupted by the one in the invalid slot. Spraying user-controlled objects like msg_msg causes a kernel panic when it lands on invalid_slot because of CONFIG_HARDENED_USERCOPY.
The approach taken abuses the partial overlap: allocate a struct timerfd_ctx and check whether any msg_msgseg object's content changes. If yes, a timerfd landed on the invalid slot and that specific msg_msgseg is at the lower slot. If not, free the timer just allocated and replace it with a msg_msgseg. This way, when the invalid slot is occupied by struct timerfd_ctx, the upper slot will be a msg_msgseg.
Info leak
With the upper and lower slots both msg_msgseg objects and the invalid slot a struct timerfd_ctx, leaking both the heap address and KASLR is easy.
Leak heap address: struct timerfd_ctx contains a few embedded linked list structs. When those list structs are empty, they contain pointers pointing back to themselves, so the location of the timerfd object in the kernel heap is known.
A linked list is a common data structure where each element contains a pointer to the next (and sometimes previous) element. An empty list often points to itself as a marker.
Bypass KASLR: the author learnt from @FizzBuzz101 that arming the timer (calling timerfd_settime with CLOCK_REALTIME on a timerfd) sets timerfd_ctx->tmr->function to timerfd_tmrproc(), which is a kernel .text pointer.
timerfd_settime is a system call that sets a timer on a timerfd file descriptor. CLOCK_REALTIME is a clock that follows the real time of day. .text is the section of a program that contains executable code; a pointer into it reveals where the kernel's code is loaded.
Let's ROP
With the leaks, there are two choices:
- Overwrite
timerfd_ctx->tmr.function, giving PC control when the timer is triggered. - Free the timerfd and hijack the freelist in the lower slot.
ROP stands for Return-Oriented Programming: a technique where an attacker chains together small pieces of existing code (called gadgets) by manipulating return addresses, to perform actions without injecting new code.
Approach 1 easily reached ROP, but the function is called in interrupt contexts, so the kernel's execution is not associated with any task and cannot directly return to userspace. Worse, there is no known way to end the execution gracefully. The author tried do_task_dead to end the execution, but since it is not a task, the kernel triggers a BUG() and crashes. Two earlier blogs tackle this situation. FuzzBuzz101's approach crashes the kernel shortly after returning to userspace because it is in an interrupt context, which is not supposed to get to userspace. D3v17's approach could not be made to work on the target kernel: the author saw a message like BUG: scheduling while atomic and the kernel crashed.
An interrupt context is a state where the CPU is handling an interrupt (a signal from hardware or a timer) and is not running on behalf of any particular task. Returning to userspace from an interrupt context is not normal and often crashes.
Stuck, the author went for approach 2. Hijacking the slab freelist is possible because when the invalid slot is freed again, its forward pointer is stored inside the lower slot. In modern Linux, forward pointers are stored in the middle of objects; in kmalloc-256 the offset is 0x80. So the address of the invalid slot's forward pointer is invalid_slot_addr + 0x80 = upper_slot_addr + 0x90 + 0x80 = upper_slot_addr + 0x110 = lower_slot + 0x10.
The target kernel has CONFIG_SLAB_FREELIST_HARDENED enabled, so the freelist is encoded. kileak demonstrated that if ptr_addr (the address the forward pointer is stored at), ptr (the forward pointer itself), and the encoded value are known, then s->random can be calculated and any encoded value forged, hijacking the slab freelist and obtaining arbitrary write. In the current setup only ptr_addr is known and ptr cannot be controlled. But by filling up the whole slab and then freeing the timerfd at the invalid slot, ptr is forced to be NULL (it is the only free slot in the slab), and s->random can be leaked for hijacking the freelist. Using the freelist hijacking primitive, arbitrary write is possible.
Arbitrary write means the ability to write a controlled value to a controlled address in kernel memory, which is a very powerful primitive for exploitation.
binfmt to privilege escalation
With leaks and arbitrary write, if container escape were not needed, overwriting modprobe_path would give root easily. But container escape is needed, so PC control, ROP and escape from the container are required. (The author notes this was true back then, but that he and @BillyQAQ found something interesting a few months afterwards.)
modprobe_path is a kernel variable that holds the path to a program the kernel runs when it needs to load a module; overwriting it is a classic privilege escalation trick.
The solution was to overwrite binfmt and then ROP. The author believes this is a new technique (novel technique No.1). Linux loads executables by going through a list of binfmt called formats, using each binfmt's load_binary handler to see whether the executable is recognisable by any format. If not recognisable by any format, it tries to load corresponding kernel modules, which enables the modprobe_path exploitation technique. The logic exists in search_binary_handler. Most importantly, these binfmt structures are writable.
binfmt is the kernel subsystem that knows how to load different executable formats (ELF, scripts, etc.). formats is the list of registered binary format handlers. load_binary is the function each handler provides to load an executable.
So the arbitrary write primitive overwrites one of the binfmt's load_binary callback functions to get PC control and then ROP. The author chose misc_format because it is after elf_format in the formats list, so PC control is obtained by trying to execute an invalid executable while still being able to execute ELF. ROP starts from there and uses the normal privilege escalation payload to get root. It worked locally.
Day 3-4: Panic No.1
On kCTF, nothing happened: the kernel did not even crash. The author had pwned kCTF twice and had never seen that. A VM on Google Cloud with the same kernel did not crash either. Investigation showed the trigger did not work with tmpfs. The bug can be triggered only if IORING_SETUP_IOPOLL is enabled, and that option can only be enabled if a file can be opened with the O_DIRECT flag. tmpfs does not support O_DIRECT, so writing a huge amount of data to a tmpfs file did not work on kCTF's environment. Writing the data to a non-tmpfs file crashed the VM on Google Cloud.
O_DIRECT is a flag that tells the kernel to bypass the page cache and do IO directly to the storage device.
Panic No.2
The only writeable region on kCTF's platform is tmpfs. The author started reading the kernel source and thinking about other ways to trigger the vulnerability. The root cause is the kernel trying to reissue unfinished IO actions when a thread is exiting. The IO actions do not have to be writes; they can be long reads, so they will not finish before the thread calling exit. A quick proof-of-concept crasher attempted to read a whole library in one go and then sprayed msg_msgseg so that, if the vulnerability is triggered, the kernel crashes by being detected by CONFIG_HARDENED_USERCOPY. It crashed the VM on Google Cloud but still not kCTF's platform.
Panic No.3
Trying to trigger the vulnerability on many large files (libc and other libraries) manually gave the same result: it crashed the cloud VM but not kCTF's kernel. The reason is that the access on kCTF is inside a Docker container whose filesystem base is overlayfs, which does not support O_DIRECT. The author hedges that this may not be true: some files could be opened with O_DIRECT but could not be used to crash the kernel for unknown reasons.
The author scanned the whole filesystem, trying to open every readable file with the O_DIRECT flag, and got a handful. Trying to trigger the vulnerability against each file that could be opened with O_DIRECT, /etc/resolv.conf crashed the kernel. The author later told zplin (@Markak_) about this trick, hopefully assisting him in exploiting CVE-2022-20409, a variant of CVE-2022-1786.
Winning the race
/etc/resolv.conf is too small, just a little bit larger than 100 bytes, so the vulnerability cannot be triggered reliably: the exploit has to race to exit one thread before it finishes reading the file. The answer was to try again and again and side-channel whether the vulnerability is triggered.
A side-channel here means an indirect way to observe whether something happened, by looking at a side effect rather than a direct signal.
The diagram illustrates the side-channel described below.
If the vulnerability is triggered, its freelist forward pointer is written into the lower slot. Since the lower slot is a msg_msgseg object, checking all msg_msgseg objects for changed content infers whether the vulnerability is triggered. This also identifies which msg_msgseg is at the lower slot, which is important for later exploitation such as hijacking the freelist.
The steps are:
- do heap grooming
- try to trigger the vulnerability using a read action (
OP_READ) - check whether it is triggered using the side-channel
- if triggered, go to step 5; if not, rinse and repeat
- hijack the freelist and use binfmt for LPE
LPE stands for Local Privilege Escalation: going from a normal user to root on the same machine.
A new version implementing this logic achieved a near 100% success rate locally.
Day 5-6: the freelist is wrong
On kCTF the exploit consistently crashed at the same place: when the exploit tried to free the timerfd in the invalid slot. That did not make sense, because the freelist should be upper_slot => invalid_slot, and even with freed slots in between the search algorithm should handle them gracefully, or at least succeed sometimes. On kCTF a VM crash takes about 5 minutes to reboot, and the platform was experiencing bugs at the time: VMs would not reboot after a few crashes, so the author had to keep pinging @sirdarckat to reboot the servers for remote debugging.
Debugging showed nothing wrong with the lower slot: it was a msg_msgseg overlapped with the invalid slot, and the output showed the overlapped region belonged to a timerfd. So the issue had to be the upper slot. Hours of staring at the code and thinking about when the search algorithm might fail consistently gave nothing, and the author went to bed at 3am.
The next morning he wrote down all possible states the upper slot might be in when the timerfd is allocated, no matter how ridiculous, and how to confirm each case. The notes are linked in the original. Testing the hypotheses one by one, the remaining answer, although it did not make sense, was that on kCTF's platform, after the bug is triggered, the freelist is not upper_slot => invalid_slot but invalid_slot => upper_slot. This does not make sense because the invalid slot is freed by the execve system call, which triggers the bug in the first place, and should be freed first no matter what. To this day the author does not know why, but blames Kubernetes for no clear reason, perhaps its cgroup magic making it prioritise the kernel thread that frees the upper slot.
Kubernetes is a system for managing containers across many machines. A cgroup (control group) is a Linux feature to limit and prioritise resources for groups of processes.
To fix it, the search algorithm was changed: allocate timerfd one by one and check whether the content in the msg_msgseg at the lower slot changes. Once there is a hit, spray a lot of msg_msg. This way:
- locally, where the freelist is
upper_slot => invalid_slot, when the invalid slot is taken, the upper slot will be a timerfd as well (corrupted, but that does not matter as long as it is not used) - on kCTF, where the freelist is
invalid_slot => upper_slot, when the invalid slot is taken by a timerfd, the upper slot is still empty; the sprayedmsg_msgensures the slot is taken by the exploit while not corrupting the timerfd at the invalid slot
This converges the two situations, at least for the invalid and lower slots.
Freelist, what's wrong with you? Again?!
With the heap layout figured out, the exploit got further: it could leak all the information but crashed at the arbitrary write to binfmt. This crash is expected because the arbitrary write corrupts the freelist. Assuming the freelist is initially A => NULL, after hijacking it becomes A => binfmt => corrupted_pointer, and the corrupted pointer cannot be avoided because the freelist is encoded and binfmt is not controlled. After the write on binfmt, one more allocation in kmalloc-256 panics the kernel.
An attempt to fix the corrupted freelist: after the write on binfmt, the freelist has only corrupted_pointer left. Free A again so it becomes A => corrupted_pointer, hijack the freelist again and restore it to A => NULL. This worked fantastically locally but not remotely. The conclusion was that kmalloc-256 is heavily used by many kernel components, so the freelist hijacking method would not work on such a busy server.
The dark before the dawn
After giving up freelist hijacking, the author returned to using timerfd_ctx to ROP, for which a decent amount of work had been done, needing only a way to end the ROP chain gracefully. Once the kernel reaches the msleep call in interrupt context, it starts spamming warning messages in a busy loop. Initially the author thought the kernel was trapped in an infinite loop and did not investigate further. Later, for reasons he no longer remembers, he discovered the kernel was actually fine calling msleep in an interrupt context: the warning messages flooding the console were just warnings, nothing harmful was done. Using dmesg -n 1 to suppress the messages allowed debugging again.
msleep is a kernel function that puts the current execution to sleep for a number of milliseconds. dmesg is a command that shows kernel messages; dmesg -n 1 sets the console log level so that only the most severe messages are printed.
The plan became:
- use the ROP chain to overwrite binfmt
- end the ROP chain "gracefully" with
msleep - in userspace, use the overwritten binfmt to ROP in task context and perform LPE
This version worked locally but not remotely. The kernel crashed when executing the KPTI trampoline, and most weirdly the crash only happened in kCTF; the exploit worked fine locally. Copy-pasting payloads proven to work (basically all the public kCTF exploits at the time) still resulted in kernel panic when trying to return to userspace using the KPTI trampoline. The author even attempted to replicate what Andy Nguyen did in CVE-2021-22555: instead of using the KPTI trampoline, carefully not clobbering rbp in the ROP chain and resuming execution on the original stack instead of the heap. Still the kernel panicked. At 5am the author decided to investigate further the next morning.
KPTI stands for Kernel Page Table Isolation: a defence that separates the kernel's memory mappings from user space to mitigate certain CPU bugs. The KPTI trampoline is the small piece of code that handles the transition between user and kernel page tables when returning to userspace. rbp is a CPU register often used as a frame pointer.
Day 7: telefork
The next morning, tired and not wanting to continue, the author decided to burn one more novel technique on this exploit, named telefork (novel technique No.3). He came up with it while developing the exploit for CVE-2022-29581 for kCTF.
The image was generated using ideogram.
The issue is that returning to userspace is not easy; the author suspects the msleep in interrupt context corrupts something in the current task. So he decided not to return to the original task context. The idea of telefork is simple: instead of handling the CPU privilege ring stuff, let the kernel do the work by simply calling fork and then msleep. fork extracts the userspace return address of the current syscall and assigns the value to the newly created task (equivalent to how it works but not exactly; interested readers can look up ret_from_fork). The old task then sleeps forever because of the msleep call, and the newly created task directly starts execution from the extracted return address in userspace. Since privilege escalation is finished before calling fork, the newly created task also has root privilege. Although much happens in kernel space, userspace does not observe it: it thinks it just returned from the execve call (used to trigger the ROP payload in binfmt) with root privilege. It is like the execution teleports from kernel space back to userspace. This time the exploit worked remotely and got the flag on kCTF's platform.
Putting it together
The final working exploit:
- heap grooming to prepare a heap layout
- race with reading
/etc/resolv.confto trigger the vulnerability - use a side-channel in the lower slot (
msg_msgseg) to indicate whether the vulnerability gets triggered - leak KASLR and heap address in the lower slot
- hijack a function pointer in
timerfd_ctx(in the invalid slot) to ROP - overwrite binfmt and then
msleepto "gracefully" end the ROP in interrupt contexts - use the overwritten binfmt to launch a ROP chain in task context and perform LPE
- return to userspace using telefork successfully
Android
@chompie1337 pointed out that io_uring was accessible by unprivileged users in Android back in 2021. Knowing the bug existed in Android as well, the author bought a Pixel 6 and tested it, crashing the freshly bought phone with the proof of concept. After upgrading the phone to the latest version, the proof of concept stopped working: io_uring had been added to the seccomp list in Android, so it is no longer accessible by unprivileged users such as normal apps, but is still accessible by privileged users such as system apps or adb. The author stopped the journey there because of research work.
seccomp is a Linux feature that restricts which system calls a process can make. adb is the Android Debug Bridge, a tool for developers to interact with an Android device.
Root cause
The mistake is the assumption in __io_req_init_async that the request is submitted by current, so current->io_uring is used to assign the request's identity. When a thread exits with IORING_SETUP_IOPOLL enabled, it reaps and reissues unfinished IO events, and the reissued request is initialised in the exiting thread, which may differ from the submitter. The wrong identity is stored in req->work.identity. Later, io_put_identify(req->task->io_uring, req) uses the submitter's context, and because tctx->identity is &tctx->__identity, the comparison req->work.identity != &tctx->__identity holds, so the kernel treats the pointer as a heap object and frees it. The pointer is actually into the middle of the exiting thread's struct io_uring_task, at offset 0x90, producing an invalid free and a type confusion.
Existing defences did not stop the bug itself. CONFIG_HARDENED_USERCOPY did stop the simplest exploitation route, because it does not allow copy_from_user to copy user data across a slot boundary, so a msg_msg spray landing on the invalid slot panics the kernel. CONFIG_SLAB_FREELIST_HARDENED encodes the freelist, but the author shows that knowing ptr_addr, ptr and the encoded value allows calculating s->random and forging encoded values. The report does not say which patch was applied; it only states that the vulnerability was reported to the Linux kernel security team and patched.
Impact
The vulnerability is a memory corruption bug in the Linux kernel io_uring subsystem that the author exploited for local privilege escalation on kCTF. On kCTF, the exploit got the flag and won the first full bounty in kCTF's history at $91,337. The bug existed in Android as well, but on the tested Pixel 6, after an upgrade, io_uring was added to the seccomp list, so it is no longer accessible by unprivileged users such as normal apps, only by privileged users such as system apps or adb. Triggering requires IORING_SETUP_IOPOLL, which requires a file that can be opened with O_DIRECT; on kCTF the only writeable region is tmpfs, which does not support O_DIRECT, and the filesystem base is overlayfs, so the author had to find a readable file that supports O_DIRECT (/etc/resolv.conf). The author also notes that freelist hijacking may be unreliable, or even not feasible, if the target cache is too busy, and says he is not 100% convinced by that conclusion himself.
Fix
The report states that the vulnerability was reported to the Linux kernel security team and patched, but it does not describe the patch itself.
Variants to test
- Other
io_uringoperations that can be reissued on thread exit withIORING_SETUP_IOPOLLenabled, such as long reads instead of writes. A positive result is a crash detected byCONFIG_HARDENED_USERCOPYwhen amsg_msgsegspray is used, or a changedmsg_msgsegcontent indicating the freelist forward pointer was written into the lower slot. - Files that can be opened with
O_DIRECTon a target where the writeable region is tmpfs or overlayfs. A positive result is a kernel crash when the file is read in one go while a thread exits. - The same identity confusion pattern in other kernel subsystems that cache a per-task context pointer and later free it based on a different task's context. A positive result is an invalid free at an offset inside a slab object, visible as a corrupted freelist or a crash under
CONFIG_HARDENED_USERCOPY. - The binfmt
load_binaryoverwrite technique on other kernels whereformatsis writable. A positive result is PC control when executing an invalid executable while ELF execution still works, for example by choosing a format afterelf_formatsuch asmisc_format. - The telefork technique for ending a ROP chain in interrupt context: call
forkand thenmsleep, and check whether the newly created task starts execution from the extracted userspace return address with the escalated privileges. A positive result is a root shell in userspace without a KPTI trampoline crash. - The
msleepin interrupt context withdmesg -n 1to suppress warnings. A positive result is that the kernel keeps running and the warning messages are only warnings, not a fatal condition. - The side-channel search over
msg_msgsegobjects to detect whether the vulnerability was triggered and which object is at the lower slot. A positive result is a changedmsg_msgsegcontent after a trigger attempt. - The freelist hijacking with
CONFIG_SLAB_FREELIST_HARDENEDby forcingptrto NULL through filling the slab and freeing the timerfd. A positive result is a calculateds->randomand a successful arbitrary write, though the author warns this may be unreliable on a busy cache such askmalloc-256.
Glossary
- CVE: Common Vulnerabilities and Exposures, a unique identifier for a publicly known security flaw.
- io_uring: A Linux kernel subsystem that lets programs submit many IO operations to the kernel efficiently, without a privilege transition for each one.
- Privilege transition: The CPU switching between user mode and kernel mode, which costs time.
- System call: A request from a user program to the kernel to perform a privileged operation.
- Kernel: The core part of an operating system that manages hardware and provides services to programs.
- Root: The administrator account on Unix-like systems, with full privileges.
- Privilege escalation: Gaining higher privileges than intended, often from a normal user to root.
- Container: A lightweight isolated environment that shares the host kernel but has its own filesystem and processes.
- Container escape: Breaking out of a container to access the host system.
- kCTF: Google's kernel Capture The Flag platform, where researchers exploit kernel bugs in a VM to read a flag.
- Bounty: A reward paid for finding and reporting a security bug.
- VM: Virtual machine, a software emulation of a computer.
- COS: Container-Optimized OS, a Linux-based operating system by Google for running containers.
- Docker: A platform for building and running containers.
- overlayfs: A layered filesystem often used by containers.
- tmpfs: A filesystem that stores files in memory rather than on disk.
- Kernel configuration: Build-time options that enable or disable kernel features and defences.
- CONFIG_HARDENED_USERCOPY: A kernel defence that checks copies from user space to kernel space do not cross allocation boundaries.
- CONFIG_SLAB_FREELIST_HARDENED: A kernel defence that encodes the freelist pointers to make them harder to forge.
- CONFIG_SLAB_FREELIST_RANDOM: A kernel defence that randomises the order of free slots in a slab.
- kmalloc-256: A kernel memory cache for allocations of 256 bytes.
- Slab: A contiguous page of memory divided into fixed-size slots for a cache.
- Slot: One fixed-size block within a slab.
- Freelist: The list of free slots in a slab.
- Heap: The area of memory used for dynamic allocation.
- Heap spray: Allocating many objects to fill memory and influence layout.
- Heap fengshui: Carefully arranging heap allocations and frees to achieve a desired layout.
- copy_from_user: A kernel function that copies data from user space to kernel space, with checks.
- memcpy: A basic memory copy function without user/kernel boundary checks.
- msg_msg: A kernel structure used for message queues.
- msg_msgseg: A segment of a message, almost entirely user data, readable from user space.
- simple_xattr: A kernel structure for extended attributes, which can hold user data.
- struct io_uring_task: A kernel structure that holds per-task io_uring state.
- struct timerfd_ctx: A kernel structure for a timer file descriptor.
- struct shmid_kernel: A kernel structure for System V shared memory.
- struct msg_queue: A kernel structure for a message queue.
- Identity: In this context, a small structure recording which task owns an io_uring request.
- Type confusion: A bug where the kernel treats an object of one type as another type.
- Invalid free: Freeing memory that was not allocated as a separate object, corrupting memory management.
- Use-after-free: Using memory after it has been freed.
- KASLR: Kernel Address Space Layout Randomisation, randomising kernel memory addresses.
- PC control: Control over the program counter, allowing redirection of execution.
- ROP: Return-Oriented Programming, chaining existing code gadgets via return addresses.
- Gadget: A short sequence of instructions ending in a return, used in ROP.
- Arbitrary write: The ability to write a controlled value to a controlled address.
- binfmt: The kernel subsystem that loads executable formats.
- formats: The list of registered binary format handlers.
- load_binary: The function a binfmt handler uses to load an executable.
- modprobe_path: A kernel variable holding the path to the module loader, often targeted for privilege escalation.
- O_DIRECT: A file open flag that bypasses the page cache for direct IO.
- IORING_SETUP_IOPOLL: An io_uring mode that uses polling for IO completion.
- execve: The system call that replaces the current program with a new one.
- OP_READ: An io_uring operation type for reading.
- Side-channel: An indirect way to observe a system's behaviour.
- KPTI: Kernel Page Table Isolation, a defence separating kernel and user page tables.
- KPTI trampoline: The code that handles the transition between page tables when returning to user space.
- msleep: A kernel function that sleeps for a number of milliseconds.
- dmesg: A command to view kernel messages.
- fork: A system call that creates a new process.
- ret_from_fork: The kernel code that starts a newly forked task in user space.
- seccomp: A Linux feature restricting which system calls a process can make.
- adb: Android Debug Bridge, a tool for interacting with Android devices.
- LPE: Local Privilege Escalation.
- PoC: Proof of Concept, a small program demonstrating a bug.
- Kubernetes: A system for managing containers across machines.
- cgroup: A Linux feature to limit and prioritise resources for groups of processes.
- rbp: A CPU register often used as a frame pointer.
- BUG(): A kernel macro that triggers a crash when an internal consistency check fails.