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
- Heap Spray — Fill the heap with objects the same size as the freed chunk to place desired data at that location.
- Type Confusion — Cause the freed pointer to be reinterpreted as another type and overwrite the vtable pointer.
- Tcache Poisoning — Manipulate tcache's
fdpointer 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
| Technique | Description |
|---|
- Nulling pointers — Make
free(p); p = NULL;a habit - Heap Hardening — glibc 2.32+
safe-linkingencrypts 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:
- Inspect mitigations with
checksec(PIE, RELRO, Canary) - Understand the allocation/free flow and check whether chunks of the same size can be reused
- Identify the libc version → understand the tcache structure
- 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. 🔥