Linux Kernel n-day exploit development
# Introduction
In the previous article (Hunting for Linux kernel public vulnerabilities) I described how I identified a good candidate vulnerability using public resources to practise some exploitation techiques. In this blog post I will detail the exploitation phase of a race condition that leads to an Use-After-Free in Linux kernel 4.9.223.
# TL;DR
The vulnerability is a Race Condition that causes a write Use-After-Free. The race window has been extended using the userfaultd technique handling page faults from user-space and using msg_msg to leak a kernel address and I/O vectors to obtain a write primitive. With the write primitive, the modprobe_path global variable has been overwritten and a root shell popped.
# RAWMIDI interface
Before facing the vulnerability, let’s see few important things needed to follow this write-up. The vulnerable driver is exposed as a character device in /dev/snd/midiC0D* (or similar name based on the platform) and depends on
CONFIG_SND_RAWMIDI. It exposes the following file operations:
| |
The ones we are interesed into are open, write and unlocked_ioctl.
# open
The open (
snd_rawmidi_open) operation allocates everything needed to interact with the device, but what is just necessary to know for us is the first allocation of snd_rawmidi_runtime->buffer as GFP_KERNEL with a size of 4096 (PAGE_SIZE) bytes. This is the
snd_rawmidi_runtime struct:
| |
# write
After having allocated everything from the open operation, we can write into the file descriptor like write(fd, &buf, 10). In that way, it will fill 10 bytes into the snd_rawmidi_runtime->buffer and using snd_rawmidi_runtime->appl_ptr it will remember the offset to start writing again later.
In order to write into that buffer, the driver does the following calls:
snd_rawmidi_write =>
snd_rawmidi_kernel_write1 => copy_from_user
# ioctl
The
snd_rawmidi_ioctl is responsible to handle IOCTL commands and the one we are interested in is SNDRV_RAWMIDI_IOCTL_PARAMS that calls
snd_rawmidi_output_params with user-controllable parameter:
| |
This IOCTL is crucial for this vulnerability. With this command it’s possible to re-size the internal buffer with an arbitrary value reallocating it[1] and later replace that buffer with the older one [2], that will be freed[3].
# Vulnerability Analysis
The vulnerability has been patched by the commit “c13f1463d84b86bedb664e509838bef37e6ea317” that introduced a reference counter on the targeted vulnerable buffer. In order to understand where the vulnerbility lived it’s a good thing to see its patch:
| |
Two functions were added:
snd_rawmidi_buffer_ref and
snd_rawmidi_buffer_unref. They are respectively used to take and remove a reference to the buffer using snd_rawmidi_runtime->buffer_ref when it is copying (
snd_rawmidi_kernel_read1) or writing (
snd_rawmidi_kernel_write1) into that buffer. But why this was needed? Because read and write operations handled by
snd_rawmidi_kernel_write1 and
snd_rawmidi_kernel_read1 temporarly unlock the runtime lock during the copying from/to userspace using spin_unlock_irqrestore[1]/spin_lock_irqrestore[2] giving a small race window where the object can be modified during the copy_from_user call:
| |
If a concurrent thread re-allocate the runtime->buffer using the SNDRV_RAWMIDI_IOCTL_PARAMS ioctl, that thread can lock the object from spin_lock_irq [1] (that has been left unlocked in the small race window given by snd_rawmidi_kernel_write1) and free that buffer[2], making possible to re-allocate an arbitrary object and write on that. Also, the kmalloc[3] in snd_rawmidi_output_params is called with params->buffer_size that is totally user controllable.
| |
What happen if, while a thread is writing into the buffer with copy_from_user, another thread frees that buffer using the SNDRV_RAWMIDI_IOCTL_PARAMS ioctl and reallocates a new arbitrary one? The object is replaced with an new one and the copy_from_user will continue writing into another object (the “victim object”) corrupting its values => User-After-Free (Write).
The really good part about this vulnerability is the “freedom” you can have:
- It’s possible to call
kmallocwith an arbitrary size (and this will be the freed object that we are going to replace to cause a UAF) which means that we can target our favourite slab cache (based on what we need, ofc) - We can write as much as we want in the buffer with the
writesyscall
# Extend the Race Time Window
We know we have a small race window with few instructions while copying data from userland to kernel as explained before, but the great news is that we have a copy_from_user that can be suspended arbitrarly handling page fault in user-space ! Since I was exploiting the vulnerability in a 4.9 kernel (4.9.223) and hence userfaultd is still not unprivileged as in >5.11, we can still use it to extend our race window and have the necessary time to re-allocate a buffer!
# Exploitation Plan
We stated that we are going to use the userfaultd technique to extend the time window. If you are new to this technique is well explained
here, in this
video (you can use substitles) and
here. To summarize: you can handle page faults from user-land, temporarly blocking kernel execution while handling the page fault. If we mmap a block of memory with MAP_ANONYMOUS flag, the memory will be demand-zero paged, meaning that it’s not yet allocated and we can allocate it via userfaultd.
The idea using this technique is:
- Initialize the
runtime->bufferwithopen=> This will allocate the buffer with 4096 size (that will land inkmalloc-4096) - Send
SNDRV_RAWMIDI_IOCTL_PARAMSioctl command in order to re-allocate the buffer with our desired size (e.g. 30 wil land inkmalloc-32) - Allocate with
mmapa demand-zero paged (MAP_ANON) and initializeuserfaultdto handle its page fault writeto the rawmidi file descriptor using our previously allocated mmaped memory => This will trigger the userland page fault incopy_from_user- While the kernel thread is suspended waiting for the userland page fault we can send again the
SNDRV_RAWMIDI_IOCTL_PARAMSin order to free the currentruntime->buffer - We allocate an object in, for example,
kmalloc-32and if we did some spray before on that cache it will take the place of the previous freedruntime->buffer - We release the page fault from userland and the
copy_from_userwill continue writing its data (totally in user control) to the new allocated object
With this primitive, we can forges arbitrary objects with arbitrary size (specified in the write syscall), arbitrary content, arbitrary offset (since we can trigger userfaultd between two pages as demostrated later on) and arbitrary cache (we can control the size allocation in the SNDRV_RAWMIDI_IOCTL_PARAMS ioctl).
As you can deduce, we have a really great and powerful primitive !
# Information Leak
# Victim Object
We are going to use what we previously explained in the “Exploitation Plan” section to leak an address that we will re-use to have an arbitrary write. Since we can choose which cache trigger the UAF on (and that’s gold from an exploitation point of view) I choose to leak the shm_file_data->ns pointer that points to init_ipc_ns in the kernel .data section and it lives in kmalloc-32 (I also used the same function to spray the kmalloc-32 cache):
| |
From that pointer, we will deduce the pointer of modprobe_path in order to use that technique later to elevate our privileges.
# msg_msg
| |
In order to leak that address, however, we have to compromise some other object in kmalloc-32, maybe a length field that would read after its own object. For that case, msg_msg is our perfect match because it has a length field specified in its msg_msg->m_ts and it can be allocated in almost any cache starting from kmalloc-32 to kmalloc-4096, with just one downside: The minimun allocation for the msg_msg struct is 48 (sizeof(struct msg_msg)) and it can lands minimun at kmalloc-64.
If you want to read more about this structure you can checkout
Fire of Salvation Writeup,
Wall Of Perdition and the
kernel source code.
However, when a message is sent using msgsnd with size more than
DATALEN_MSG (((size_t)PAGE_SIZE-sizeof(struct msg_msg))) that is 4096-48, a segment (or multiple segments if needed) is allocated, and the message is splitted between the msg_msg (the payload is just after the struct headers) and the msg_msgseg, with the total size of the message specified in msg_msg->m_ts.
In order to allocate our target object in kmalloc-32 we have to send a message with size: ( ( 4096 - 48 ) + 10 ).
- The
msg_msgstructure will be allocated inkmalloc-4096and the first (4096 - 48) bytes will be written in themsg_msgstructure. - To allocate the remaining 10 bytes, a segment
msg_msgsegwill be allocated inkmalloc-32
With these conditions, we can forge the msg_msg structure in kmalloc-4096 overwriting its m_ts value with our UAF and with msgrcv we can receive a message that will contains values past our segment allocated in kmalloc-32 (including our targeted init_ipc_ns pointer).
# Dealing with offsets
However, we want to overwrite the m_ts value without overwriting anything else in the msg_msg structure, how we can do that?
If you remember, I said we can overwrite chunks with arbitrary size, content and offset. If we create a mmap memory with size PAGE_SIZE * 2 (two pages) and we handle the page fault only for the second page, we can start writing into the original runtime->buffer and trigger the page fault when it receives the msg_msg->m_ts offset (0x18). Now that the kernel thread is blocked, it’s possible to replace the object with msg_msg and when the copy_from_user resumes, it will starts writing exactly at the msg_msg->m_ts value the remaining bytes. The size we are writing into the file descriptor is (0x18 + 0x2) since the first 0x18 bytes will be used to land at the exact offset and the 2 remaining bytes will write 0xffff in msg_msg->m_ts. The concept is also explained in the following picture:

Now from the received message from msgrcv we can retrieve the init_ipc_ns pointer from shm_file_data and we can deduce the modprobe_path address calculating its offset and proceed with the arbitrary write phase.
# Arbitrary Write
In order to write at arbitrary locations we are using the same userfault technique described above but instead of targeting msg_msg we will use the Vectored I/O (pipe + iovec) primitive. This primitive has been fixed in kernel 4.13 with
copyin and
copyout wrappers, with an access_ok addition. This technique has been widely used exploiting the Android Binder CVE-2019-2215 and is well detailed
here and
here.
The idea is to trigger the UAF once again but targeting the iovec struct:
| |
The
minimun allocation for iovec occurs with sizeof(struct iovec) * 9 or 16 * 9 (144) that will land at kmalloc-192 (otherwise it is stored in the stack). However I choose to allocate 13 vectors using readv to make the object land in kmalloc-256.
| |
The readv is a blocking call that stays (does not free) the object in the kernel so that we can corrupt it using our UAF and re-use it later with our arbitrary modified content. If we corrupt the iov_base of an iovec structure we can write at arbitrary kernel addresses with a write syscall since it is uses the unsafe
__copy_from_user (same as copy_from_user but without checks).

Our idea is:
- Resize the
runtime->bufferwithSNDRV_RAWMIDI_IOCTL_PARAMSin order to lands intokmalloc-256with a size greater than 192 writeinto the file descriptor specifycing a demanded-zero paged memory (MAP_ANON) so thatcopy_from_userwill stop its execution waiting for our user-land page fault handler- While the kernel thread is waiting, free the buffer using again the re-size ioctl command
SNDRV_RAWMIDI_IOCTL_PARAMS - Allocate the
iovecstruct usingreadvthat will replace the previously allocatedruntime->buffer - Resume the kernel execution releasing the page fault handler. Now the
copy_from_userwill start to write into theiovecstructure and we will overwriteiov[1].iov_basewith themodprobe_pathaddress.
Now, in order to overwrite the modprobe_path value we just have to write our arbitrary content using the write syscall into pipe[0]. In the released exploit I overwrote the second iov entry (iov[1]) using the same technique described before with adjacent pages. However, it’s also possible to directly overwrite the first iov[0].iov_base.
Nice ! Now we have overwritten modprobe_path with /tmp/x and .. it’s time to pop a shell !
# modprobe_path & uid=0
If you are not familiar with modprobe_path I suggest you to check out
Exploiting timerfd_ctx Objects In The Linux Kernel and the
man page.
To summarize, modprobe_path is a global variable with a default value of /sbin/modprobe used by call_usermodehelper_exec to execute a user-space program in case a program with an unkown header is executed.
Since we have overwritten modprobe_path with /tmp/x, when a file with an unknown header is executed, our controllable script is executed as root.
These are the exploit functions that prepares and later executes a suid shell:
| |
What the exploit does is simply create the /tmp/x binary that will suid as root a file dropped in /tmp/suid and create a file with an unknown header (/tmp/nnn) that will trigger the executon as root of /tmp/x from call_usermodehelper_exec. After that, the /tmp/suid gives root privileges and spawns a root shell.
POC:
| |
# Conclusion
That was my journey into exploiting a known vulnerability in the 4.9.223 kernel. You can find the whole exploit on github:
https://github.com/kiks7/CVE-2020-27786-Kernel-Exploit.
# References
- https://1day.dev/2022-06/1day-devel-part-1.html
- https://elixir.bootlin.com/linux/v4.9.223/source/
- https://lwn.net/Articles/819834/
- https://www.youtube.com/watch?v=6dFmH_JEF4s
- https://blog.lizzie.io/using-userfaultfd.html
- https://www.willsroot.io/2021/08/corctf-2021-fire-of-salvation-writeup.html
- https://syst3mfailure.io/wall-of-perdition
- https://googleprojectzero.blogspot.com/2019/11/bad-binder-android-in-wild-exploit.html
- https://cloudfuzz.github.io/android-kernel-exploitation/chapters/exploitation.html#leaking-task-struct-pointer
- https://syst3mfailure.io/hotrod
- https://man7.org/linux/man-pages/man2/userfaultfd.2.html
- https://github.com/kiks7/CVE-2020-27786-Kernel-Exploit