Skip to main content

40. Use-After-Free: Reclaim Freed Memory

UAF (Use-After-Free) is a vulnerability that occurs when a pointer continues to be used after its heap memory has been freed with free(). It is continually found in modern browsers, kernels, and server software, and it is a recurring CTF topic.

How It Works

char *buf = malloc(64);
free(buf);
// buf is now a dangling pointer
strcpy(buf, "pwned"); // UAF occurs!

If a pointer is not initialized to NULL after free(), buf becomes a dangling pointer. If a chunk of the same size is allocated again in this state, the attacker can take control of that area through the tcache/fastbin reuse mechanism.

Attack Scenarios

  1. Heap Spray — Fill the heap with objects the same size as the freed chunk to place desired data at that location.
  2. Type Confusion — Cause the freed pointer to be reinterpreted as another type and overwrite the vtable pointer.
  3. Tcache Poisoning — Manipulate tcache's fd pointer to make an arbitrary address the location of the next allocation.

Observing UAF with GDB

gdb ./vuln
pwndbg> heap
pwndbg> bins # Inspect tcache/fastbin state
pwndbg> vis_heap_chunks

The vis_heap_chunks command in pwndbg lets you visualize how freed chunks are linked into tcache.

Defenses

TechniqueDescription
  • Nulling pointers — Make free(p); p = NULL; a habit
  • Heap Hardening — glibc 2.32+ safe-linking encrypts tcache fd
  • ASAN (AddressSanitizer) — Automatically detects UAF during development
  • CFI (Control Flow Integrity) — Prevents vtable pointer corruption

CTF Approach

When you encounter a UAF challenge, use this sequence:

  1. Inspect mitigations with checksec (PIE, RELRO, Canary)
  2. Understand the allocation/free flow and check whether chunks of the same size can be reused
  3. Identify the libc version → understand the tcache structure
  4. Automate the exploit with pwntools

UAF looks simple, but it requires a deep understanding of heap structures. It is the starting point of heap mastery. 🔥