security-research
A heap out-of-bounds write in Linux Netfilter's compatibility mode allows an attacker with CAP_NET_ADMIN to corrupt kernel memory and achieve privilege escalation. The exploit bypasses modern mitigations and can escape a Kubernetes container to gain root on the host.
Published on google.github.io
CVE-2021-22555 is a 15 years old heap out-of-bounds write vulnerability in Linux Netfilter that is powerful enough to bypass all modern security mitigations and achieve kernel code execution. It was used to break the kubernetes pod isolation of the kCTF cluster and won 10000$ for charity (where Google will match and…
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
CVE-2021-22555 is a heap out-of-bounds write in Linux Netfilter that had been present for 15 years. The bug lives in the compatibility layer that converts 32-bit Netfilter structures to their 64-bit kernel counterparts. It is reachable through IPT_SO_SET_REPLACE or IP6T_SO_SET_REPLACE when called in compatibility mode. Those calls require the CAP_NET_ADMIN capability, but that capability can be obtained inside a user and network namespace, so an unprivileged local user can reach the buggy code.
The write-up was produced after the author, following earlier work on BleedingTooth, set out to find a Linux privilege escalation. The exploit was used to break the Kubernetes pod isolation of the kCTF cluster and won 10000 USD for charity, which Google matched and doubled to 20000 USD.

Setup
The starting point was reading old vulnerabilities, in particular CVE-2016-3134 and CVE-2016-4997, which inspired a search for memcpy() and memset() calls in the Netfilter code. That search led to the buggy code.
The author noticed that victim objects could not be reliably allocated around struct xt_table_info on kernel 5.4. The CAP_NET_ADMIN capability can be obtained in a user and network namespace, and the exploit relies on the msgsnd() message queue interface, unix sockets created with socketpair(), and pipes created with pipe(). The proof of concept is compiled as a 32-bit static binary.
Finding it
When IPT_SO_SET_REPLACE or IP6T_SO_SET_REPLACE is called in compatibility mode, structures have to be converted from user to kernel layout and from 32-bit to 64-bit layout before the native functions process them. The vulnerability is in xt_compat_target_from_user(), where memset() is called with an offset target->targetsize that was not accounted for during the allocation. The result is a few bytes written out of bounds:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/netfilter/x_tables.c
void xt_compat_target_from_user(struct xt_entry_target *t, void **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.kernel.target;
struct compat_xt_entry_target *ct = (struct compat_xt_entry_target *)t;
int pad, off = xt_compat_target_offset(target);
u_int16_t tsize = ct->u.user.target_size;
char name[sizeof(t->u.user.name)];
t = *dstptr;
memcpy(t, ct, sizeof(*ct));
if (target->compat_from_user)
target->compat_from_user(t->data, ct->data);
else
memcpy(t->data, ct->data, tsize - sizeof(*ct));
pad = XT_ALIGN(target->targetsize) - target->targetsize;
if (pad > 0)
memset(t->data + target->targetsize, 0, pad);
tsize += off;
t->u.user.target_size = tsize;
strlcpy(name, target->name, sizeof(name));
module_put(target->me);
strncpy(t->u.user.name, name, sizeof(t->u.user.name));
*size += off;
*dstptr += tsize;
}
The targetsize itself is not controllable by the user, but different targets with different structure sizes can be selected by name, such as TCPMSS, TTL or NFQUEUE. The bigger the targetsize, the more the offset can vary. The target size must not be 8-byte aligned for pad > 0 to hold. The biggest target found is NFLOG, which allows an offset of up to 0x4C bytes out of bounds. The offset can be influenced further by adding padding between struct xt_entry_match and struct xt_entry_target:
struct xt_nflog_info {
/* 'len' will be used iff you set XT_NFLOG_F_COPY_LEN in flags */
__u32 len;
__u16 group;
__u16 threshold;
__u16 flags;
__u16 pad;
char prefix[64];
};
The destination buffer is allocated with GFP_KERNEL_ACCOUNT and its size can also vary:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/netfilter/x_tables.c
struct xt_table_info *xt_alloc_table_info(unsigned int size)
{
struct xt_table_info *info = NULL;
size_t sz = sizeof(*info) + size;
if (sz < sizeof(*info) || sz >= XT_MAX_TABLE_SIZE)
return NULL;
info = kvmalloc(sz, GFP_KERNEL_ACCOUNT);
if (!info)
return NULL;
memset(info, 0, sizeof(*info));
info->size = size;
return info;
}
The minimum size is greater than 0x100, so the smallest slab this object can be allocated in is kmalloc-512. The practical consequence is that victims have to be found between kmalloc-512 and kmalloc-8192.
Exploitation
The primitive is limited to writing four bytes of zero up to 0x4C bytes out of bounds. The author considered the usual targets for such a primitive:
- Reference counter: no suitable object with a reference counter in the first 0x4C bytes could be found.
- Free list pointer: CVE-2016-6187 is cited as a good example of exploiting the free list pointer, but that was five years earlier and kernels now enable
CONFIG_SLAB_FREELIST_HARDENED, which among other things protects free list pointers. - Pointer in a struct: the most promising approach, but four bytes of zero is too much to write. A pointer such as 0xffff91a49cb7f000 could only be turned into 0xffff91a400000000 or 0x9cb7f000, both likely invalid. Writing at the very beginning of the adjacent block would allow fewer bytes, for example two, turning 0xffff91a49cb7f000 into 0xffff91a49cb70000.
While experimenting with victim objects, the author noticed that they could never be reliably allocated around struct xt_table_info on kernel 5.4. The cause was the GFP_KERNEL_ACCOUNT flag: other objects allocated with that flag did not have the problem. Jann Horn confirmed that before 5.9, separate slabs were used to implement accounting. Every heap primitive used in the exploit chain therefore has to use GFP_KERNEL_ACCOUNT as well.
The msgsnd() syscall is a well known heap spraying primitive that uses GFP_KERNEL_ACCOUNT, and it has been used in multiple public exploits, but its msg_msg structure had surprisingly never been abused. The write-up shows how that structure can be used to gain a use-after-free primitive, which in turn leaks addresses and fakes other objects. In parallel, in March 2021, Alexander Popov explored the same structure in his own write-up on CVE-2021-26708.
Exploring struct msg_msg
When data is sent with msgsnd(), the payload is split into multiple segments:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
static struct msg_msg *alloc_msg(size_t len)
{
struct msg_msg *msg;
struct msg_msgseg **pseg;
size_t alen;
alen = min(len, DATALEN_MSG);
msg = kmalloc(sizeof(*msg) + alen, GFP_KERNEL_ACCOUNT);
if (msg == NULL)
return NULL;
msg->next = NULL;
msg->security = NULL;
len -= alen;
pseg = &msg->next;
while (len > 0) {
struct msg_msgseg *seg;
cond_resched();
alen = min(len, DATALEN_SEG);
seg = kmalloc(sizeof(*seg) + alen, GFP_KERNEL_ACCOUNT);
if (seg == NULL)
goto out_err;
*pseg = seg;
seg->next = NULL;
pseg = &seg->next;
len -= alen;
}
return msg;
out_err:
free_msg(msg);
return NULL;
}
The headers for struct msg_msg and struct msg_msgseg are:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/msg.h
/* one msg_msg structure for each message */
struct msg_msg {
struct list_head m_list;
long m_type;
size_t m_ts; /* message text size */
struct msg_msgseg *next;
void *security;
/* the actual message follows immediately */
};
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/types.h
struct list_head {
struct list_head *next, *prev;
};
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
struct msg_msgseg {
struct msg_msgseg *next;
/* the next part of the message follows immediately */
};
The first member of struct msg_msg is the mlist.next pointer, which points to another message in the queue. This is different from next, which points to the next segment. That first pointer is the perfect candidate to corrupt.
Achieving use-after-free
- Initialise a lot of message queues, 4096 in this case, using
msgget(). - Send one message of size 4096, including the
struct msg_msgheader, for each of the message queues usingmsgsnd(). These are the primary messages. After a lot of messages, some of them are consecutive:

[Figure 1: A series of blocks of primary messages]
- Send a secondary message of size 1024 for each of the message queues using
msgsnd():

[Figure 2: A series of blocks of primary messages pointing to secondary messages]
- Create holes in the primary messages, every 1024th in this case, and trigger the vulnerable
setsockopt(IPT_SO_SET_REPLACE)option. In the best scenario, thestruct xt_table_infoobject is allocated in one of the holes:

[Figure 3: A xt_table_info allocated in between the blocks which corrupts the next pointer]
- Overwrite two bytes of the adjacent object with zeros. If the adjacent object is another primary message, the overwritten bytes are part of the pointer to the secondary message. Since the secondary messages are allocated with a size of 1024 bytes, the chance of redirecting the pointer is 1 - (1024 / 65536). The only failing case is when the two least significant bytes of the pointer are already zero.
The best outcome is that the manipulated pointer also points to a secondary message, because then two different primary messages point to the same secondary message, which leads to a use-after-free:

[Figure 4: Two primary messages pointing to the same secondary message due to the corrupted pointer]
To find which two primary messages point to the same secondary message, every primary and secondary message is tagged with the index of its message queue, in the range [0, 4096). After triggering the corruption, the exploit iterates through all message queues, peeks at all messages using msgrcv() with MSG_COPY, and checks whether they are the same. If the tag of the primary message differs from the tag of the secondary message, the pointer has been redirected. The tag of the primary message is then the index of the fake message queue, the one containing the wrong secondary message, and the tag of the wrong secondary message is the index of the real message queue. With those two indices, the use-after-free is trivial: fetch the secondary message from the real message queue using msgrcv(), which frees it:

[Figure 5: Freed secondary message with a stale reference]
A reference to the freed message remains in the fake message queue.
Bypassing SMAP
Unix sockets, easily set up with socketpair(), are now used to spray a lot of messages of size 1024 that imitate the struct msg_msg header. Ideally, this reclaims the address of the previously freed message:

[Figure 6: Fake struct msg_msg put in place of the freed secondary message]
In this fake header, mlist.next is 41414141 because no kernel addresses are known yet, and with SMAP enabled a user address cannot be specified. Not having a kernel address is crucial, because it prevents the block from being freed again, which is desired. During msgrcv(), the message is unlinked from the message queue, which is a circular list.
The situation is good for an information leak because of the interesting fields in struct msg_msg. The field m_ts determines how much data is returned to userland:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
struct msg_msg *copy_msg(struct msg_msg *src, struct msg_msg *dst)
{
struct msg_msgseg *dst_pseg, *src_pseg;
size_t len = src->m_ts;
size_t alen;
if (src->m_ts > dst->m_ts)
return ERR_PTR(-EINVAL);
alen = min(len, DATALEN_MSG);
memcpy(dst + 1, src + 1, alen);
...
return dst;
}
The original message size is only 1024-sizeof(struct msg_msg) bytes, and it can now be artificially increased to DATALEN_MSG=4096-sizeof(struct msg_msg). As a consequence, reading goes past the intended message size and leaks the struct msg_msg header of the adjacent message. Because the message queue is a circular list, mlist.next points back to the primary message.
Knowing the address of a primary message, the fake struct msg_msg can be re-crafted with that address as next, meaning it is the next segment. The content of the primary message is then leaked by reading more than DATALEN_MSG bytes. The leaked mlist.next pointer from the primary message reveals the address of the secondary message adjacent to the fake struct msg_msg. Subtracting 1024 from that address gives the address of the fake message.
Achieving a better use-after-free
The fake struct msg_msg object is rebuilt with the leaked address as mlist.next and mlist.prev, meaning it points to itself, which makes the fake message free-able with the fake message queue:

[Figure 7: Fake struct msg_msg with a valid next pointer pointing to itself]
When spraying with unix sockets, a struct sk_buff object points to the fake message. When the fake message is freed, a stale reference therefore remains:

[Figure 8: Freed fake message with a stale reference]
This stale struct sk_buff data buffer is a better use-after-free scenario, because it does not contain header information, so it can be used to free any kind of object on the slab. Freeing a struct msg_msg object, by comparison, is only possible if the first two members are writable pointers, which are needed to unlink the message.
Finding a victim object
The best victim has a function pointer in its structure, and it must also be allocated with GFP_KERNEL_ACCOUNT. Jann Horn suggested struct pipe_buffer, which is allocated in kmalloc-1024, which is why the secondary message is 1024 bytes. A struct pipe_buffer is easily allocated with pipe(), which has alloc_pipe_info() as a subroutine:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/pipe.c
struct pipe_inode_info *alloc_pipe_info(void)
{
...
unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
...
pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
if (pipe == NULL)
goto out_free_uid;
...
pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
GFP_KERNEL_ACCOUNT);
...
}
struct pipe_buffer does not contain a function pointer directly, but it contains a pointer to struct pipe_buf_operations, which does:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/pipe_fs_i.h
struct pipe_buffer {
struct page *page;
unsigned int offset, len;
const struct pipe_buf_operations *ops;
unsigned int flags;
unsigned long private;
};
struct pipe_buf_operations {
...
/*
* When the contents of this pipe buffer has been completely
* consumed by a reader, ->release() is called.
*/
void (*release)(struct pipe_inode_info *, struct pipe_buffer *);
...
};
Bypassing KASLR/SMEP
Writing to the pipes populates struct pipe_buffer. Most importantly, ops points to the static structure anon_pipe_buf_ops, which resides in the .data segment:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/pipe.c
static const struct pipe_buf_operations anon_pipe_buf_ops = {
.release = anon_pipe_buf_release,
.try_steal = anon_pipe_buf_try_steal,
.get = generic_pipe_buf_get,
};
Since the difference between the .data segment and the .text segment is always the same, having anon_pipe_buf_ops allows the kernel base address to be calculated.
A lot of struct pipe_buffer objects are sprayed to reclaim the location of the stale struct sk_buff data buffer:

[Figure 9: Freed fake message reclaimed with a struct pipe_buffer]
Because a reference from the struct sk_buff still exists, its data buffer can be read, leaking the content of struct pipe_buffer and revealing the address of anon_pipe_buf_ops:
[+] anon_pipe_buf_ops: ffffffffa1e78380
[+] kbase_addr: ffffffffa0e00000
With that information, JOP/ROP gadgets can be found. Reading from the unix socket also frees its buffer:

[Figure 10: Freed fake message reclaimed with a struct pipe_buffer]
Escalating privileges
The stale struct pipe_buffer is reclaimed with a fake one whose ops points to a fake struct pipe_buf_operations. The fake structure is planted at the same location, since its address is known, and it contains a malicious function pointer as release:

[Figure 11: Freed struct pipe_buffer reclaimed with a fake struct pipe_buffer]
The final stage closes all pipes to trigger the release, which kicks off the JOP chain. Finding JOP gadgets is hard, so the goal is to achieve a kernel stack pivot as soon as possible in order to execute a kernel ROP chain.
Kernel ROP chain
The value of RBP is saved at a scratchpad address in the kernel so that execution can be resumed later. Then commit_creds(prepare_kernel_cred(NULL)) is called to install kernel credentials, and switch_task_namespaces(find_task_by_vpid(1), init_nsproxy) is called to switch the namespace of process 1 to the one of the init process. After that, RBP is restored and execution returns, which immediately makes free_pipe_info() return.
Escaping the container and popping a root shell
Back in userland with root permissions, the mnt, pid and net namespaces are changed to escape the container and break out of the Kubernetes pod, and a root shell is popped:
setns(open("/proc/1/ns/mnt", O_RDONLY), 0);
setns(open("/proc/1/ns/pid", O_RDONLY), 0);
setns(open("/proc/1/ns/net", O_RDONLY), 0);
char *args[] = {"/bin/bash", "-i", NULL};
execve(args[0], args, NULL);
Proof-Of-Concept
The proof of concept is available at https://github.com/google/security-research/tree/master/pocs/linux/cve-2021-22555. Executing it on a vulnerable machine grants root:
theflow@theflow:~$ gcc -m32 -static -o exploit exploit.c
theflow@theflow:~$ ./exploit
[+] Linux Privilege Escalation by theflow@ - 2021
[+] STAGE 0: Initialization
[*] Setting up namespace sandbox...
[*] Initializing sockets and message queues...
[+] STAGE 1: Memory corruption
[*] Spraying primary messages...
[*] Spraying secondary messages...
[*] Creating holes in primary messages...
[*] Triggering out-of-bounds write...
[*] Searching for corrupted primary message...
[+] fake_idx: ffc
[+] real_idx: fc4
[+] STAGE 2: SMAP bypass
[*] Freeing real secondary message...
[*] Spraying fake secondary messages...
[*] Leaking adjacent secondary message...
[+] kheap_addr: ffff91a49cb7f000
[*] Freeing fake secondary messages...
[*] Spraying fake secondary messages...
[*] Leaking primary message...
[+] kheap_addr: ffff91a49c7a0000
[+] STAGE 3: KASLR bypass
[*] Freeing fake secondary messages...
[*] Spraying fake secondary messages...
[*] Freeing sk_buff data buffer...
[*] Spraying pipe_buffer objects...
[*] Leaking and freeing pipe_buffer object...
[+] anon_pipe_buf_ops: ffffffffa1e78380
[+] kbase_addr: ffffffffa0e00000
[+] STAGE 4: Kernel code execution
[*] Spraying fake pipe_buffer objects...
[*] Releasing pipe_buffer objects...
[*] Checking for root...
[+] Root privileges gained.
[+] STAGE 5: Post-exploitation
[*] Escaping container...
[*] Cleaning up...
[*] Popping root shell...
root@theflow:/# id
uid=0(root) gid=0(root) groups=0(root)
root@theflow:/#
Root cause
The allocation of the destination buffer does not account for the offset target->targetsize that xt_compat_target_from_user() later uses as the base of a memset() of pad zero bytes. The pad value is XT_ALIGN(target->targetsize) - target->targetsize, so it is non-zero whenever the target size is not 8-byte aligned, and the write lands past the end of the allocated object. The size of the write is small, at most a few bytes, and the offset is bounded by the chosen target, with NFLOG giving up to 0x4C bytes.
Existing mitigations did not stop the exploit. CONFIG_SLAB_FREELIST_HARDENED protects free list pointers, which rules out the classic free list pointer target. SMAP prevents the use of user addresses in kernel pointers, which is why the fake msg_msg initially carries 41414141 in mlist.next and why the leak stage is needed before a valid kernel pointer can be planted. KASLR and SMEP are bypassed by leaking anon_pipe_buf_ops from the .data segment and deriving the kernel base, then pivoting to a ROP chain. The GFP_KERNEL_ACCOUNT flag on the vulnerable allocation constrains which objects can be used as victims, because before 5.9 separate slabs were used for accounting.
Impact
An attacker who can obtain CAP_NET_ADMIN in a user and network namespace, which an unprivileged local user can do, can trigger the out-of-bounds write and, as demonstrated, escalate to kernel code execution. In the kCTF setting this was enough to break the Kubernetes pod isolation of the cluster. The exploit depends on the heap layout and on the victim objects being available in the relevant slabs.
Fix
The vulnerability was reported to [redacted] on 2021-04-06, a patch was merged upstream on 2021-04-13, and public disclosure followed on 2021-07-07. The write-up does not describe the contents of the patch.
Variants to test
- Other Netfilter targets with a non-8-byte-aligned
targetsize, such asTCPMSS,TTLorNFQUEUE, to vary the out-of-bounds offset. A positive result is apad > 0write landing past the allocatedxt_table_infoobject. - Adding padding between
struct xt_entry_matchandstruct xt_entry_targetto push the offset further, withNFLOGas the largest target found. A positive result is a controlled offset up to 0x4C bytes. - Other
GFP_KERNEL_ACCOUNTheap spraying primitives besidesmsgsnd(), to see which structures can be placed aroundstruct xt_table_infoon kernels before 5.9. A positive result is reliable adjacency between the sprayed object and the vulnerable allocation. - Other victim objects with a function pointer, allocated with
GFP_KERNEL_ACCOUNTin kmalloc-512 to kmalloc-8192, as alternatives tostruct pipe_buffer. A positive result is a reclaimable object whose function pointer can be redirected through the stalestruct sk_buffreference. - The same
msg_msgcorruption technique on other kernels and configurations, checking whetherm_tscan be enlarged to leak adjacent headers. A positive result is reading pastDATALEN_MSGand recovering a kernel pointer.
What happened, in plain words
A security researcher found a bug that had been sitting quietly inside Linux, the operating system kernel that runs on most servers in the world, for about 15 years. The bug let a local user who can create a user and network namespace, and so obtain CAP_NET_ADMIN, take full control of the machine. In computer security terms that is called a privilege escalation: you start as an ordinary user and end up as the administrator, the account that can do anything.
The researcher used this bug to break out of a Kubernetes pod. Kubernetes is software that runs many small, isolated containers on shared machines; a pod is one of those isolated boxes, and the whole point of the box is that a program inside it cannot touch the rest of the machine. The exploit was run against Google's kCTF cluster, a challenge environment where security researchers try to break out of such a pod. It worked, and it won 10000 USD for charity, which Google matched and doubled to 20000 USD.

The rest of this article walks through how the bug works and how the exploit is built, step by step, explaining each idea from scratch.
Introduction
After earlier work on BleedingTooth, a set of bugs in the Linux Bluetooth stack, the author wanted to find a privilege escalation vulnerability as well. The starting point was reading about old vulnerabilities, in particular CVE-2016-3134 and CVE-2016-4997. Those inspired a simple search: look through the Netfilter code for calls to memcpy() and memset().
Netfilter is the part of Linux that handles firewalls and packet filtering. memcpy() and memset() are two of the most basic functions in the C programming language: memcpy() copies a block of bytes from one place in memory to another, and memset() fills a block of memory with a repeated byte value. They are fast and simple, and that is exactly why they are dangerous: they do not check whether the destination is big enough. If a programmer gets the size wrong, these functions happily write past the end of the intended area. That kind of mistake is called a buffer overflow, and it is one of the oldest classes of security bug.
That search led to some buggy code.
Vulnerability
What the vulnerable feature does
When IPT_SO_SET_REPLACE or IP6T_SO_SET_REPLACE is called in compatibility mode, structures need to be converted from user to kernel as well as 32bit to 64bit in order to be processed by the native functions.
Let us unpack that sentence. A structure in C is a bundle of related values stored together in memory, like a form with several fields. The kernel and user programs exchange such structures when a program asks the kernel to do something, for example to install a firewall rule. IPT_SO_SET_REPLACE and IP6T_SO_SET_REPLACE are the names of two such requests: one for IPv4 firewall rules and one for IPv6 firewall rules.
Compatibility mode is a feature that lets a 32-bit program run on a 64-bit kernel. A 32-bit program lays out its structures with 32-bit values, while the kernel expects 64-bit values, so the kernel has to translate the structure before using it. Naturally, this is destined to be error prone: whenever you translate between two layouts, you have to get every size and every offset exactly right.
These calls require the CAP_NET_ADMIN capability. A capability is a specific permission bit in Linux; CAP_NET_ADMIN is the one that allows changing network configuration, such as firewall rules. Normally only the administrator has it. However, it can be obtained in a user and network namespace. A namespace is a way of giving a process its own private view of part of the system. Inside a user namespace, a process can be given capabilities that only apply within that namespace, and inside a network namespace it gets its own private network stack. So an ordinary user can create these namespaces, become "administrator" of the tiny private world inside them, and from there reach the buggy code. That is why this is a local privilege escalation: you need to be able to run a program on the machine, but nothing more.
The bug itself
Our vulnerability is in xt_compat_target_from_user() where memset() is called with an offset target->targetsize that is not accounted for during the allocation, leading to a few bytes written out-of-bounds:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/netfilter/x_tables.c
void xt_compat_target_from_user(struct xt_entry_target *t, void **dstptr,
unsigned int *size)
{
const struct xt_target *target = t->u.kernel.target;
struct compat_xt_entry_target *ct = (struct compat_xt_entry_target *)t;
int pad, off = xt_compat_target_offset(target);
u_int16_t tsize = ct->u.user.target_size;
char name[sizeof(t->u.user.name)];
t = *dstptr;
memcpy(t, ct, sizeof(*ct));
if (target->compat_from_user)
target->compat_from_user(t->data, ct->data);
else
memcpy(t->data, ct->data, tsize - sizeof(*ct));
pad = XT_ALIGN(target->targetsize) - target->targetsize;
if (pad > 0)
memset(t->data + target->targetsize, 0, pad);
tsize += off;
t->u.user.target_size = tsize;
strlcpy(name, target->name, sizeof(name));
module_put(target->me);
strncpy(t->u.user.name, name, sizeof(t->u.user.name));
*size += off;
*dstptr += tsize;
}
Line by line, in plain words:
- The function receives a pointer
tto a target structure coming from the user, a pointerdstptrto the place where the translated copy should be written, and a pointersizeto a running total of how much has been written. targetis looked up from the user-supplied structure: it is the kernel's description of this particular kind of firewall target.ctis justtviewed through the 32-bit compatibility layout, so the code can read the old-style fields.offis the difference in size between the 32-bit and 64-bit versions of the target header.tsizeis the size the user said the target is.t = *dstptr;movestto point at the destination buffer, the freshly allocated kernel memory.memcpy(t, ct, sizeof(*ct));copies the fixed-size header from the user structure into the destination.- If the target provides its own conversion function, it is called; otherwise the target's data is copied with
memcpy(t->data, ct->data, tsize - sizeof(*ct));. pad = XT_ALIGN(target->targetsize) - target->targetsize;computes how many bytes are needed to round the target size up to an 8-byte boundary.XT_ALIGNrounds a size up to a multiple of 8.if (pad > 0) memset(t->data + target->targetsize, 0, pad);is the bug. It starts writing att->dataplustarget->targetsizeand writespadzero bytes. If the destination buffer was allocated without leaving room for that offset, the zeros land past the end of the buffer. That is an out-of-bounds write: writing outside the area you were given.- The remaining lines fix up the size fields, copy the target name, release a reference to the kernel module, and advance the destination pointer and the running size.
The targetsize is not controllable by the user, but one can choose different targets with different structure sizes by name (like TCPMSS, TTL or NFQUEUE). The bigger targetsize is, the more we can vary in the offset. Though, the target size must not be 8 bytes aligned in order to fulfill pad > 0. The biggest possible I found is NFLOG for which we can choose an offset up to 0x4C bytes out-of-bounds (one can influence the offset by adding padding between struct xt_entry_match and struct xt_entry_target):
struct xt_nflog_info {
/* 'len' will be used iff you set XT_NFLOG_F_COPY_LEN in flags */
__u32 len;
__u16 group;
__u16 threshold;
__u16 flags;
__u16 pad;
char prefix[64];
};
This is the structure for the NFLOG target, which logs matching packets. It holds a length, a group number, a threshold, some flags, a padding field and a 64-byte text prefix. Its size is what makes it the most useful target here: it is large, and its size is not a multiple of 8, so pad is positive and the zero write happens.
Note that the destination of the buffer is allocated with GFP_KERNEL_ACCOUNT and can also vary in the size:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/net/netfilter/x_tables.c
struct xt_table_info *xt_alloc_table_info(unsigned int size)
{
struct xt_table_info *info = NULL;
size_t sz = sizeof(*info) + size;
if (sz < sizeof(*info) || sz >= XT_MAX_TABLE_SIZE)
return NULL;
info = kvmalloc(sz, GFP_KERNEL_ACCOUNT);
if (!info)
return NULL;
memset(info, 0, sizeof(*info));
info->size = size;
return info;
}
Line by line:
szis the size of the bookkeeping structure plus the size the caller asked for.- A sanity check rejects sizes that are too small or too large.
kvmalloc(sz, GFP_KERNEL_ACCOUNT)allocates the memory.GFP_KERNEL_ACCOUNTis a flag that tells the kernel to charge this allocation to the current user's memory accounting; we will see later why that flag matters a lot.- The bookkeeping structure is zeroed, its size field is set, and it is returned.
Though, the minimum size is > 0x100 which means that the smallest slab this object can be allocated in is kmalloc-512. In other words, we have to find victims which are allocated between kmalloc-512 and kmalloc-8192 to exploit.
A slab is the kernel's way of managing memory: it keeps pools of fixed-size chunks, called caches, and hands out chunks from the right pool. The pools are named after their chunk size, so kmalloc-512 hands out 512-byte chunks, kmalloc-1024 hands out 1024-byte chunks, and so on. Because the vulnerable object is always at least a bit bigger than 0x100 bytes, it lands in kmalloc-512 or larger. A victim is the object we want to place right next to the vulnerable one so that our out-of-bounds write damages it. Since the write only reaches a short distance past the end of our object, the victim must live in the same size class, between kmalloc-512 and kmalloc-8192.
Exploitation
Our primitive is limited to writing four bytes of zero up to 0x4C bytes out-of-bounds. A primitive, in exploit writing, means the small, reliable effect you have obtained from a bug: here, "I can write a few zero bytes just past the end of a chunk I control". The whole art of exploitation is turning a tiny primitive like that into something bigger.
With such a primitive, usual targets are:
-
Reference counter
- Unfortunately, I could not find any suitable objects with a reference counter in the first 0x4C bytes.
-
Free list pointer
- CVE-2016-6187: Exploiting Linux kernel heap off-by-one is a good example on how to exploit the free list pointer. However, this was already 5 years ago, and meanwhile, kernels have the
CONFIG_SLAB_FREELIST_HARDENEDoption enabled which among other things protects free list pointers.
- CVE-2016-6187: Exploiting Linux kernel heap off-by-one is a good example on how to exploit the free list pointer. However, this was already 5 years ago, and meanwhile, kernels have the
-
Pointer in a struct
- This is the most promising approach, however four bytes of zero is too much to write. For example, a pointer 0xffff91a49cb7f000 could only be turned to 0xffff91a400000000 or 0x9cb7f000, where both of them would likely be invalid pointers. On the other hand, if we used the primitive to write at the very beginning of the adjacent block, we could write less bytes, e.g. 2 bytes, and for example turn a pointer from 0xffff91a49cb7f000 to 0xffff91a49cb70000.
Let us explain those three ideas, because they are the classic ways to use a small overwrite.
A reference counter is a number stored inside an object that counts how many parts of the kernel are currently using it. When the count drops to zero, the object is freed. If you can zero the counter, the object may be freed while someone still holds a pointer to it, which is a use-after-free. The author could not find a suitable object with such a counter in the reachable range.
A free list pointer is the pointer the memory allocator stores inside a freed chunk to remember which chunk comes next in its list of free chunks. Corrupting it can make the allocator hand out the same memory twice. That trick is old, and modern kernels enable CONFIG_SLAB_FREELIST_HARDENED, a build option that among other things protects free list pointers, so it no longer works.
A pointer inside a structure is the most promising approach, but four bytes of zero is too much to write. A kernel pointer such as 0xffff91a49cb7f000, if you zero its top four bytes, becomes 0xffff91a400000000, and if you zero its bottom four bytes it becomes 0x9cb7f000; both would likely be invalid pointers. If instead the write landed at the very beginning of the adjacent block, fewer bytes would be needed, for example two, turning 0xffff91a49cb7f000 into 0xffff91a49cb70000, which is still a plausible address in the same region.
Playing around with some victim objects, I noticed that I could never reliably allocate them around struct xt_table_info on kernel 5.4. I realised that it had something to do with the GFP_KERNEL_ACCOUNT flag, as other objects allocated with GFP_KERNEL_ACCOUNT did not have this issue. Jann Horn confirmed that before 5.9, separate slabs were used to implement accounting. Therefore, every heap primitive we use in the exploit chain should also use GFP_KERNEL_ACCOUNT.
This is an important practical lesson. The kernel was keeping two separate sets of memory pools: one for ordinary allocations and one for allocations that are charged to a user's account. Before version 5.9, an object allocated without the accounting flag would never sit next to an object allocated with it, so the victim and the vulnerable object would never be neighbours. Every object used in the exploit chain therefore has to be allocated with GFP_KERNEL_ACCOUNT too.
The syscall msgsnd() is a well known primitive for heap spraying (which uses GFP_KERNEL_ACCOUNT) and has been utilized for multiple public exploits already. Though, its structure msg_msg has surprisingly never been abused. In this write-up, we will demonstrate how this data-structure can be abused to gain a use-after-free primitive which in turn can be used to leak addresses and fake other objects. Coincidentally, in parallel to my research in March 2021, Alexander Popov also explored the very same structure in Four Bytes of Power: exploiting CVE-2021-26708 in the Linux kernel.
A syscall is a request a program makes to the kernel, the way a customer places an order at a counter. msgsnd() is the syscall that sends a message to a message queue, one of the oldest inter-process communication features in Unix: one program puts a message in a queue, another program takes it out. Heap spraying means allocating many copies of the same kind of object, over and over, so that the memory allocator fills the gaps in its pools with them. It is like scattering hundreds of identical boxes on a shelf so that whichever slot you later need is likely to hold one of your boxes. Because msgsnd() allocates with GFP_KERNEL_ACCOUNT, it is a perfect spraying tool for this bug.
Exploring struct msg_msg
When sending data with msgsnd(), the payload is split into multiple segments:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
static struct msg_msg *alloc_msg(size_t len)
{
struct msg_msg *msg;
struct msg_msgseg **pseg;
size_t alen;
alen = min(len, DATALEN_MSG);
msg = kmalloc(sizeof(*msg) + alen, GFP_KERNEL_ACCOUNT);
if (msg == NULL)
return NULL;
msg->next = NULL;
msg->security = NULL;
len -= alen;
pseg = &msg->next;
while (len > 0) {
struct msg_msgseg *seg;
cond_resched();
alen = min(len, DATALEN_SEG);
seg = kmalloc(sizeof(*seg) + alen, GFP_KERNEL_ACCOUNT);
if (seg == NULL)
goto out_err;
*pseg = seg;
seg->next = NULL;
pseg = &seg->next;
len -= alen;
}
return msg;
out_err:
free_msg(msg);
return NULL;
}
Line by line:
alenis how much of the message fits in the first chunk: the smaller of the total length andDATALEN_MSG, the maximum data a single message header can carry.kmalloc(sizeof(*msg) + alen, GFP_KERNEL_ACCOUNT)allocates one chunk big enough for the header plus that first piece of data. This is the primary chunk.- The
nextandsecurityfields of the header are cleared. - The remaining length is reduced by the amount already stored, and
psegis set to the address of thenextfield, so the loop knows where to attach the next segment. - The
whileloop runs as long as data remains. Each iteration allocates one segment chunk of at mostDATALEN_SEGbytes, links it into the chain, and moves on.cond_resched()politely lets other tasks run during a long loop. - If any allocation fails, the whole message is freed and an error is returned.
So a long message is a chain: one header chunk followed by zero or more segment chunks, each pointing to the next.
where the headers for struct msg_msg and struct msg_msgseg are:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/msg.h
/* one msg_msg structure for each message */
struct msg_msg {
struct list_head m_list;
long m_type;
size_t m_ts; /* message text size */
struct msg_msgseg *next;
void *security;
/* the actual message follows immediately */
};
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/types.h
struct list_head {
struct list_head *next, *prev;
};
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
struct msg_msgseg {
struct msg_msgseg *next;
/* the next part of the message follows immediately */
};
Line by line:
struct msg_msgis the header of a message.m_listis a pair of pointers used to keep the message in a doubly linked list, which is how the queue is implemented.m_typeis the message type chosen by the sender.m_tsis the message text size, the number the kernel uses to decide how many bytes to copy back to a reader.nextpoints to the first segment chunk, if any.securityis used by security modules. The actual message data follows the header in the same chunk.struct list_headis simply two pointers,nextandprev, pointing to the neighbouring list entries. A circular list is one where the last entry points back to the first, so followingnextaround eventually returns to where you started.struct msg_msgsegis a segment header: a singlenextpointer, followed immediately by the segment's data.
The first member in struct msg_msg is the mlist.next pointer which is pointing to another message in the queue (which is different from next as this is a pointer to the next segment). This is a perfect candidate to corrupt as you will learn next.
Achieving use-after-free
First, we initialize a lot of message queues (in our case 4096) using msgget(). Then, we send one message of size 4096 (including the struct msg_msg header) for each of the message queues using msgsnd(), which we will call the primary message. Eventually, after a lot of messages, we have some that are consecutive:

[Figure 1: A series of blocks of primary messages]
msgget() creates a new message queue and returns an identifier for it. The exploit creates 4096 of them, then sends one 4096-byte message into each. Each of these primary messages is 4096 bytes including the header. Sending thousands of them fills the pool, and some of the chunks end up next to each other in memory, as the figure shows.
Next, we send a secondary message of size 1024 for each of the message queues using msgsnd():

[Figure 2: A series of blocks of primary messages pointing to secondary messages]
Each secondary message is 1024 bytes, so it lives in a kmalloc-1024 chunk. The primary message's next pointer now points to its secondary message. The point of this two-level arrangement is that the primary message is the object we will corrupt, and the secondary message is the object we will later free while a reference to it remains.
Finally, we create some holes (in our case every 1024th) in the primary messages, and trigger the vulnerable setsockopt(IPT_SO_SET_REPLACE) option, which, in the best scenario, will allocate the struct xt_table_info object in one of the holes:

[Figure 3: A xt_table_info allocated in between the blocks which corrupts the next pointer]
setsockopt() is the syscall a program uses to set options on a socket; here it is used to deliver the firewall rule that reaches the buggy conversion code. Freeing every 1024th primary message leaves regularly spaced empty slots in the kmalloc-4096 pool. When the vulnerable allocation happens, the allocator is likely to place the new struct xt_table_info object in one of those empty slots, right next to a primary message we still control. That adjacency is what makes the out-of-bounds write land on something useful.
We choose to overwrite two bytes of the adjacent object with zeros. Assume we are adjacent to another primary message, these bytes we overwrite are part of the pointer to the secondary message. Since we allocate them with a size of 1024 bytes, we therefore have a 1 - (1024 / 65536) chance to redirect the pointer (the only case we fail is when the two least significant bytes of the pointer are already zero).
Why those odds? The pointer to the secondary message is a 64-bit address. Zeroing its two lowest bytes changes it by an amount between 0 and 65535, and the secondary messages are spaced 1024 bytes apart. So the changed pointer lands on another secondary message unless the low two bytes were already zero, which happens with probability 1024/65536. The chance of success is therefore 1 minus that.
Now, the best scenario we can hope for is that the manipulated pointer also points to a secondary message, since the consequence will be two different primary messages pointing to the same secondary message, and this can lead to a use-after-free:

[Figure 4: Two primary messages pointing to the same secondary message due to the corrupted pointer]
A use-after-free is a bug where a program keeps a pointer to memory it has already given back, and then uses it. If the memory has been reused for something else in the meantime, the stale pointer now refers to that something else, and the program can be tricked into reading or writing it. Here, two primary messages point at the same secondary message: one of them is the real owner, the other is a fake reference created by the corruption.
However, how do we know which two primary messages are pointing to the same secondary message? In order to answer this question, we tag every (primary and secondary) message with the index of the message queue which is in [0, 4096). Then, after triggering the corruption, we iterate through all message queues, peek at all messages using msgrcv() with MSG_COPY and see if they are the same. If the tag of the primary message is different from the secondary message, it means that it has been redirected. In which case the tag of the primary message represents the index of the fake message queue, i.e. the one containing the wrong secondary message, and the tag of the wrong secondary message represents the index of the real message queue. Knowing these two indices, achieving a use-after-free is now trivial - we namely fetch the secondary message from the real message queue using msgrcv() and as such free it:

[Figure 5: Freed secondary message with a stale reference]
msgrcv() is the syscall that receives a message from a queue. With the MSG_COPY flag it copies the message out without removing it, which is exactly what a detective needs: look without disturbing. Each message carries a tag, the number of the queue it was sent to. If a primary message's tag says queue 5 but the secondary message it points to says queue 9, the pointer has been redirected. The primary message's tag names the fake queue, and the wrong secondary message's tag names the real queue. Receiving the secondary message from the real queue removes it and frees its memory, but the fake queue still holds a pointer to it. That is the use-after-free.
Note that we still have a reference to the freed message in the fake message queue.
Bypassing SMAP
Using unix sockets (which can be easily set up with socketpair()), we now spray a lot of messages of size 1024 and imitate the struct msg_msg header. Ideally, we are able to reclaim the address of the previously freed message:

[Figure 6: Fake struct msg_msg put in place of the freed secondary message]
A unix socket is a communication channel between two programs on the same machine, and socketpair() creates two connected ends of one in a single call. Sending data through a unix socket makes the kernel allocate a buffer for it, and the exploit sizes these to 1024 bytes. By sending many 1024-byte buffers whose contents look like a struct msg_msg header, the exploit tries to make one of them occupy the exact chunk that was just freed. If that works, the stale pointer in the fake queue now points at data we control.
Note that mlist.next is 41414141 as we do not yet know any kernel addresses (when SMAP is enabled, we cannot specify a user address). Not having a kernel address is crucial as it actually prevents us from freeing the block again (you will learn later why that is desired). The reason is that during msgrcv(), the message is unlinked from the message queue that is a circular list. Luckily, we are actually in a good position to achieve an information leak, as there are some interesting fields in struct msg_msg. Namely, the field m_ts is used to determine how much data to return to userland:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/ipc/msgutil.c
struct msg_msg *copy_msg(struct msg_msg *src, struct msg_msg *dst)
{
struct msg_msgseg *dst_pseg, *src_pseg;
size_t len = src->m_ts;
size_t alen;
if (src->m_ts > dst->m_ts)
return ERR_PTR(-EINVAL);
alen = min(len, DATALEN_MSG);
memcpy(dst + 1, src + 1, alen);
...
return dst;
}
Line by line:
lenis taken from the source message'sm_tsfield, the size the kernel believes the message has.- A check rejects the copy if the source claims to be bigger than the destination allows.
alenis capped atDATALEN_MSG, the maximum that fits in one chunk.memcpy(dst + 1, src + 1, alen)copiesalenbytes of message data from source to destination. The+ 1skips the header in each case.
The key point is that the amount copied is driven by m_ts, a field inside the message header. If we control the header, we control how much is copied.
SMAP, Supervisor Mode Access Prevention, is a processor feature that stops the kernel from reading or writing memory that belongs to user programs. Without it, an attacker could simply put a fake structure in their own program's memory and point the kernel at it. With SMAP enabled, a kernel pointer must point into kernel memory, so the fake header's mlist.next is filled with 41414141, a value that is obviously not a valid kernel address. That is deliberate: when the kernel later tries to unlink this fake message from the circular list, it will fail instead of freeing the block, and we want the block to stay allocated for the next stage.
The original size of the message is only 1024-sizeof(struct msg_msg) bytes which we can now artificially increase to DATALEN_MSG=4096-sizeof(struct msg_msg). As a consequence, we will now be able to read past the intended message size and leak the struct msg_msg header of the adjacent message. As said before, the message queue is implemented as a circular list, thus, mlist.next points back to the primary message.
An information leak means getting the kernel to reveal a value it should keep secret, typically an address. Kernel addresses are valuable because they tell you where things are, which is the first thing you need to hijack anything. By enlarging m_ts, the exploit makes the kernel copy more bytes back to the user than the message really contains, so the extra bytes are whatever sits next in memory: the header of the neighbouring message, including its pointers.
Knowing the address of a primary message, we can re-craft the fake struct msg_msg with that address as next (meaning that it is the next segment). The content of the primary message can then be leaked by reading more than DATALEN_MSG bytes. The leaked mlist.next pointer from the primary message reveals the address of the secondary message that is adjacent to our fake struct msg_msg. Subtracting 1024 from that address, we finally have the address of the fake message.
This is a chain of small deductions. The first leak gives us the address of a primary message. We put that address in the next field of our fake header, so the kernel treats the primary message as the next segment of our message and copies its contents out. Those contents include the primary message's mlist.next, which points to its secondary message. Since the secondary message sits right next to our fake message and chunks are 1024 bytes apart, subtracting 1024 gives the address of the fake message itself. We now know where our own fake object lives in kernel memory.
Achieving a better use-after-free
Now, we can rebuild the fake struct msg_msg object with the leaked address as mlist.next and mlist.prev (meaning that it is pointing to itself), making the fake message free-able with the fake message queue.

[Figure 7: Fake struct msg_msg with a valid next pointer pointing to itself]
A circular list with a single element points to itself in both directions. By setting both mlist.next and mlist.prev to the fake message's own address, the unlink operation becomes valid: the kernel removes the message from the list without crashing, and the chunk is freed. Now the fake queue can free the fake message on demand.
Note that when spraying using unix sockets, we actually have a struct sk_buff object which points to the fake message. Obviously, this means that when we free the fake message, we still have a stale reference:

[Figure 8: Freed fake message with a stale reference]
A struct sk_buff is the kernel's structure for a network packet or a piece of socket data; it holds a pointer to the data buffer. When the fake message is freed, the sk_buff still points at that memory, so we have a second, cleaner use-after-free.
This stale struct sk_buff data buffer is a better use-after-free scenario to exploit, because it does not contain header information, meaning that we can now use it to free any kind of object on the slab. In comparison, freeing a struct msg_msg object is only possible if the first two members are writable pointers (needed to unlink the message).
In other words, the message header imposes conditions: to free it, its first two fields must be valid pointers. A raw socket data buffer has no such conditions, so whatever object we place there can be freed freely. That flexibility is what lets us move on to a more powerful victim.
Finding a victim object
The best victim to attack is one that has a function pointer in its structure. Remember that the victim must also be allocated with GFP_KERNEL_ACCOUNT.
A function pointer is a value that says "when this operation happens, run the code at this address". If an attacker can overwrite a function pointer, the kernel will jump to an address of the attacker's choosing, which is the step from corrupting data to running code.
Talking to Jann Horn, he suggested the struct pipe_buffer object which is allocated in kmalloc-1024 (hence why the secondary message is 1024 bytes). The struct pipe_buffer can be easily allocated with pipe() that has alloc_pipe_info() as a subroutine:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/pipe.c
struct pipe_inode_info *alloc_pipe_info(void)
{
...
unsigned long pipe_bufs = PIPE_DEF_BUFFERS;
...
pipe = kzalloc(sizeof(struct pipe_inode_info), GFP_KERNEL_ACCOUNT);
if (pipe == NULL)
goto out_free_uid;
...
pipe->bufs = kcalloc(pipe_bufs, sizeof(struct pipe_buffer),
GFP_KERNEL_ACCOUNT);
...
}
Line by line:
pipe_bufsis set to the default number of buffers a pipe has.kzallocallocates and zeroes the pipe's bookkeeping structure, again withGFP_KERNEL_ACCOUNT.kcallocallocates an array ofstruct pipe_bufferobjects, one per buffer, also withGFP_KERNEL_ACCOUNT. This array is what lands in kmalloc-1024.
A pipe is a simple one-way channel between two programs: one writes bytes in, the other reads them out. The kernel keeps a small array describing each chunk of data currently in the pipe, and each entry is a struct pipe_buffer.
While it does not contain a function pointer directly, it contains a pointer to struct pipe_buf_operations that on the other hand has function pointers:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/include/linux/pipe_fs_i.h
struct pipe_buffer {
struct page *page;
unsigned int offset, len;
const struct pipe_buf_operations *ops;
unsigned int flags;
unsigned long private;
};
struct pipe_buf_operations {
...
/*
* When the contents of this pipe buffer has been completely
* consumed by a reader, ->release() is called.
*/
void (*release)(struct pipe_inode_info *, struct pipe_buffer *);
...
};
Line by line:
struct pipe_bufferdescribes one chunk of data in a pipe: which memory page holds it, where in the page it starts and how long it is, a pointeropsto a table of operations, some flags, and a private value.struct pipe_buf_operationsis that table. Itsreleaseentry is a function pointer that is called when the data has been completely read. If we can makeopspoint at a table we control, then closing the pipe will call a function of our choosing.
Bypassing KASLR/SMEP
When one writes to the pipes, struct pipe_buffer is populated. Most importantly, ops will point to the static structure anon_pipe_buf_ops which resides in the .data segment:
// https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/fs/pipe.c
static const struct pipe_buf_operations anon_pipe_buf_ops = {
.release = anon_pipe_buf_release,
.try_steal = anon_pipe_buf_try_steal,
.get = generic_pipe_buf_get,
};
Line by line:
- This is a constant table of operations used for ordinary, anonymous pipe data.
releasepoints toanon_pipe_buf_release, the function that runs when the data is consumed.try_stealandgetpoint to other helper functions.
KASLR, Kernel Address Space Layout Randomisation, is a defence that loads the kernel at a random address each boot, so an attacker cannot hard-code addresses. SMEP, Supervisor Mode Execution Prevention, stops the kernel from executing code that lives in user memory. Both defences depend on the attacker not knowing where kernel code and data are. The ops pointer gives that away: it always points to anon_pipe_buf_ops, a fixed structure in the kernel's .data segment. Since the difference between the .data segment and the .text segment is always the same, having anon_pipe_buf_ops basically allows us to calculate the kernel base address. Once the base is known, every other kernel address can be computed, and the defences are neutralised.
We spray a lot of struct pipe_buffer objects and reclaim the location of the stale struct sk_buff data buffer:

[Figure 9: Freed fake message reclaimed with a struct pipe_buffer]
As we still have a reference from the struct sk_buff, we can read its data buffer, leak the content of struct pipe_buffer and reveal the address of anon_pipe_buf_ops:
[+] anon_pipe_buf_ops: ffffffffa1e78380
[+] kbase_addr: ffffffffa0e00000
Line by line:
- The first line is the leaked address of
anon_pipe_buf_ops, read out of the pipe buffer that landed in our stale slot. - The second line is the kernel base address computed from it.
With this information, we can now find JOP/ROP gadgets. Note that when reading from the unix socket, we actually free its buffer as well:

[Figure 10: Freed fake message reclaimed with a struct pipe_buffer]
A gadget is a short sequence of existing kernel instructions that ends in a return or jump, and that does something useful when chained together. ROP, Return-Oriented Programming, is the technique of stringing such gadgets together so that the processor executes them in sequence, achieving arbitrary behaviour without injecting any new code. JOP, Jump-Oriented Programming, is the same idea using jumps instead of returns. Reading from the unix socket frees its buffer, which conveniently leaves the slot free again for the next stage.
Escalating privileges
We reclaim the stale struct pipe_buffer with a fake one with ops pointing to a fake struct pipe_buf_operations. This fake structure is planted at the same location since we know its address, and obviously, this structure should contain a malicious function pointer as release.

[Figure 11: Freed struct pipe_buffer reclaimed with a fake struct pipe_buffer]
The final stage of the exploit is to close all pipes in order to trigger the release which in turn will kick off the JOP chain. Finding JOP gadgets is hard, thus the goal is to achieve a kernel stack pivot as soon as possible in order to execute a kernel ROP chain.
A stack pivot means changing the stack pointer so that the processor starts using a memory area the attacker controls as its call stack. The stack is where the processor keeps track of where to return after a function finishes; if you control it, you control what runs next. Pivoting early makes the rest of the chain much easier to build.
Kernel ROP chain
We save the value of RBP at some scratchpad address in kernel so that we can later resume the execution, then we call commit_creds(prepare_kernel_cred(NULL)) to install kernel credentials and finally we call switch_task_namespaces(find_task_by_vpid(1), init_nsproxy) to switch the namespace of process 1 to the one of the init process. After that, we restore the value of RBP and return to resume the execution (which will immediately make free_pipe_info() return).
RBP is a register, a small storage slot inside the processor, used to keep track of the current stack frame. Saving it lets the exploit return cleanly afterwards instead of crashing. commit_creds(prepare_kernel_cred(NULL)) is the classic two-step used to become root: prepare_kernel_cred(NULL) builds a fresh set of full credentials, and commit_creds installs them on the current process. switch_task_namespaces(find_task_by_vpid(1), init_nsproxy) then moves process 1 into the initial namespace, the one the whole machine started with, which is the step that breaks the container isolation.
Escaping the container and popping a root shell
Arriving back in userland, we now have root permissions to change mnt, pid and net namespaces to escape the container and break out of the kubernetes pod. Ultimately, we pop a root shell.
setns(open("/proc/1/ns/mnt", O_RDONLY), 0);
setns(open("/proc/1/ns/pid", O_RDONLY), 0);
setns(open("/proc/1/ns/net", O_RDONLY), 0);
char *args[] = {"/bin/bash", "-i", NULL};
execve(args[0], args, NULL);
Line by line:
setns(open("/proc/1/ns/mnt", O_RDONLY), 0);opens the mount namespace of process 1 and joins it, so the program now sees the host's filesystem instead of the container's.setns(open("/proc/1/ns/pid", O_RDONLY), 0);joins the host's process namespace, so it can see and signal host processes.setns(open("/proc/1/ns/net", O_RDONLY), 0);joins the host's network namespace, so it can use the host's network interfaces.char *args[] = {"/bin/bash", "-i", NULL};builds the argument list for an interactive shell.execve(args[0], args, NULL);replaces the current program with that shell, giving the attacker a root prompt on the host.
Proof-Of-Concept
The Proof-Of-Concept is available at https://github.com/google/security-research/tree/master/pocs/linux/cve-2021-22555.
A proof of concept is a working program that demonstrates the bug, so that defenders and other researchers can verify it and test their fixes.
Executing it on a vulnerable machine will grant you root:
theflow@theflow:~$ gcc -m32 -static -o exploit exploit.c
theflow@theflow:~$ ./exploit
[+] Linux Privilege Escalation by theflow@ - 2021
[+] STAGE 0: Initialization
[*] Setting up namespace sandbox...
[*] Initializing sockets and message queues...
[+] STAGE 1: Memory corruption
[*] Spraying primary messages...
[*] Spraying secondary messages...
[*] Creating holes in primary messages...
[*] Triggering out-of-bounds write...
[*] Searching for corrupted primary message...
[+] fake_idx: ffc
[+] real_idx: fc4
[+] STAGE 2: SMAP bypass
[*] Freeing real secondary message...
[*] Spraying fake secondary messages...
[*] Leaking adjacent secondary message...
[+] kheap_addr: ffff91a49cb7f000
[*] Freeing fake secondary messages...
[*] Spraying fake secondary messages...
[*] Leaking primary message...
[+] kheap_addr: ffff91a49c7a0000
[+] STAGE 3: KASLR bypass
[*] Freeing fake secondary messages...
[*] Spraying fake secondary messages...
[*] Freeing sk_buff data buffer...
[*] Spraying pipe_buffer objects...
[*] Leaking and freeing pipe_buffer object...
[+] anon_pipe_buf_ops: ffffffffa1e78380
[+] kbase_addr: ffffffffa0e00000
[+] STAGE 4: Kernel code execution
[*] Spraying fake pipe_buffer objects...
[*] Releasing pipe_buffer objects...
[*] Checking for root...
[+] Root privileges gained.
[+] STAGE 5: Post-exploitation
[*] Escaping container...
[*] Cleaning up...
[*] Popping root shell...
root@theflow:/# id
uid=0(root) gid=0(root) groups=0(root)
root@theflow:/#
Line by line:
gcc -m32 -static -o exploit exploit.ccompiles the exploit as a 32-bit program with all its libraries built in. The command compiles the exploit as a 32-bit program with all its libraries built in../exploitruns it.- Stage 0 sets up the namespace sandbox and initialises the sockets and message queues.
- Stage 1 performs the memory corruption: spray primary messages, spray secondary messages, create holes, trigger the out-of-bounds write, and search for the corrupted primary message. It prints the fake and real queue indices it found.
- Stage 2 bypasses SMAP: free the real secondary message, spray fake secondary messages, leak the adjacent secondary message, then free and re-spray to leak a primary message. It prints two kernel heap addresses.
- Stage 3 bypasses KASLR: free and re-spray fake secondary messages, free the
sk_buffdata buffer, spraypipe_bufferobjects, and leak and free one. It prints the address ofanon_pipe_buf_opsand the kernel base. - Stage 4 achieves kernel code execution by spraying fake
pipe_bufferobjects and releasing them, then checks for root and reports success. - Stage 5 escapes the container, cleans up and pops a root shell.
idconfirms the result:uid=0(root), the root account.
Timeline
2021-04-06 - Vulnerability reported to [redacted] 2021-04-13 - Patch merged upstream. 2021-07-07 - Public disclosure.
Thanks
Eduardo Vela Francis Perron Jann Horn
Glossary
- API: a defined way for one piece of software to ask another to do something, like a menu of requests with fixed names and formats.
- Buffer overflow: a bug where a program writes more data into a memory area than it can hold, spilling into neighbouring memory.
- Capability: a specific permission bit in Linux, such as
CAP_NET_ADMINfor network configuration, that grants a narrow right rather than full administrator power. - Compatibility mode: the kernel path that lets 32-bit programs run on a 64-bit kernel by translating their data structures.
- Container: an isolated box on a shared machine, holding a program and its dependencies, kept apart from the rest of the system.
- CVE: a public identifier for a known security vulnerability, so people can refer to it unambiguously.
- Function pointer: a value stored in memory that tells the program which code to run for an operation; overwriting it can redirect execution.
- Gadget: a short sequence of existing instructions ending in a return or jump, used as a building block in ROP or JOP.
- GFP_KERNEL_ACCOUNT: an allocation flag that charges the memory to the current user's accounting; before kernel 5.9 such allocations used separate memory pools.
- Heap spraying: allocating many copies of the same object so that the allocator fills memory with them, making a chosen slot likely to hold one.
- Information leak: getting a program to reveal data it should keep secret, typically a memory address.
- JOP (Jump-Oriented Programming): chaining existing code fragments that end in jumps to make the processor perform new behaviour.
- KASLR: Kernel Address Space Layout Randomisation, a defence that loads the kernel at a random address each boot.
- Kernel: the core of the operating system, which manages memory, processes, devices and permissions.
- Kubernetes: software that runs and isolates many containers across machines; a pod is one isolated unit it manages.
- kmalloc-512 / kmalloc-1024 / kmalloc-4096 / kmalloc-8192: kernel memory pools that hand out chunks of those sizes.
- memcpy(): a C function that copies a block of bytes from one place to another without checking sizes.
- memset(): a C function that fills a block of memory with a repeated byte value without checking sizes.
- Message queue: an inter-process communication feature where one program puts messages in a queue and another takes them out.
- Mitigation: a defence built into the system to make a class of attack harder.
- Namespace: a private view of part of the system, such as the network stack or the list of processes, given to a group of processes.
- Netfilter: the part of Linux that handles firewalls and packet filtering.
- Out-of-bounds write: writing data outside the memory area that was allocated for it.
- Pipe: a one-way channel between two programs, where one writes bytes and the other reads them.
- Privilege escalation: going from an ordinary user account to a more powerful one, ultimately the administrator.
- Primitive: the small, reliable effect obtained from a bug, which exploitation then builds on.
- Proof of concept: a working program that demonstrates a vulnerability so it can be verified and fixed.
- Reference counter: a number inside an object counting how many parts of the system use it; when it reaches zero the object is freed.
- Register: a small storage slot inside the processor, such as RBP, used while code runs.
- ROP (Return-Oriented Programming): chaining existing code fragments that end in returns to make the processor perform new behaviour.
- Slab: the kernel's memory management scheme that keeps pools of fixed-size chunks and hands them out on request.
- SMAP: Supervisor Mode Access Prevention, a processor feature that stops the kernel from accessing user memory.
- SMEP: Supervisor Mode Execution Prevention, a processor feature that stops the kernel from executing user memory.
- Socket: an endpoint for communication; a unix socket connects two programs on the same machine.
- Stack pivot: changing the processor's stack pointer so it uses an attacker-controlled memory area as its call stack.
- Structure (struct): a bundle of related values stored together in memory, like a form with several fields.
- Syscall: a request a program makes to the kernel, such as sending a message or setting a socket option.
- Use-after-free: a bug where a program keeps using memory it has already freed, which may have been reused for something else.
- Victim object: the object an exploit places next to a vulnerable one so that the corruption damages it in a useful way.