Use-After-Free & Tcache Poisoning
Heap Vulnerabilities & Use-After-Free · Exploitation Fundamentals track
10 min read
In this module
Exploiting the Dangling Pointer
In the previous lesson, you saw that a dangling pointer still reaches its old chunk, and that free writes allocator state into the first 16 bytes. A use-after-free vulnerability turns that bug into an exploit by controlling what the dangling pointer finds. There are two broad ways to do it on glibc. The first swaps the program's object for one the attacker wrote. The second goes after the allocator itself and turns the bug into a write anywhere in memory.
Everything here is glibc 2.35 (Ubuntu 22.04) on x86-64, and it works the same on the glibc 2.39 that the labs run. Addresses continue the illustrative layout from lessons 1 and 2.
The Three-Step Attack
The object-replacement attack runs like this:
- Free. The program frees an object, say the 0x40-byte
struct sessionfrom lesson 2 at0x55555555b2a0, but keeps the pointer. - Reallocate. The attacker triggers a new allocation of a size that rounds to the same 0x50 chunk, and fills it with crafted bytes. tcache is LIFO, so if nothing else of that size was freed in between,
mallocreturns0x55555555b2a0again. - Use. The program uses the old pointer, reads the attacker's bytes, and believes it's looking at the original session.
The program has no way to tell the difference. Same address, same accessibility, same structural shape. Every field, though, now holds whatever the attacker put there. And notice the size discipline: a 0x38-byte request (chunk 0x40) won't do, because it uses a different tcache bin. The attacker needs a request between 0x39 and 0x48 bytes, and ideally one whose contents they control from the very first byte. Text fields read with read(), network buffers and string copies of exactly the right length are the usual candidates.
Type confusion occurs when a program treats a block of memory as one type of object when it actually contains another. In a use-after-free exploit, the old pointer expects to find (for example) a session object with a function pointer at offset 0, but instead finds a string the attacker supplied, whose first eight bytes are an address of their choosing. The program trusts the type, not the content.
Why Function Pointers Make It Worse
Many programs store function pointers inside objects, and C++ objects with virtual methods start with a vtable pointer that the compiler dereferences on every virtual call. If the attacker's replacement object contains a crafted function or vtable pointer, the program will call whatever the attacker wired up next time it touches the object. That's control-flow hijacking, and with a bit of ROP it becomes arbitrary code execution.
No buffer overrun is needed. No return address gets clobbered. The attacker substitutes one object for another, riding the allocator's own reuse machinery. You can try exactly this in the Heap Use-After-Free lab.
Object replacement needs the freed object to contain something worth controlling. When it doesn't, or when the attacker wants to reach memory outside the heap, the dangling pointer can be turned on the allocator.
Tcache Poisoning
Recall that a freed tcache chunk's first eight bytes are the (mangled) next pointer, and that malloc follows it without checking where it leads. If a use-after-free lets you write to a freed chunk, you can edit next and make a later malloc return an address of your choosing. Then the program writes its own data, often data you supply, to that address. This is tcache poisoning, and it's the most common way a heap bug becomes an arbitrary write on modern glibc.
Here's the full sequence. The target is a global function pointer, handler, at 0x555555558060 in the program's .bss. (In a PIE binary you'd need to have leaked the program's base address to know that. In a non-PIE binary like the labs build, it's fixed and readable from the binary.)
Step 1: Allocate and free two chunks
char *a = malloc(0x40); /* 0x55555555b2a0, chunk size 0x50 */char *b = malloc(0x40); /* 0x55555555b2f0 */free(a);free(b); /* bin 3: b -> a, count 2 */You need two chunks in the bin, and the reason is in the 2.35 source. __libc_malloc only calls tcache_get when tcache->counts[tc_idx] > 0, and that count is a separate number in tcache_perthread_struct that a poisoned next pointer doesn't change. With one chunk freed, the first malloc takes it and drops the count to zero; the poisoned pointer becomes the bin head but is never consulted. Before glibc 2.30 the code checked the head pointer instead of the count, and one free was enough. Many older write-ups still show it that way.
Step 2: Leak the heap
Safe-linking means you need to know where b lives to forge a pointer for it. Use the use-after-free read on a, the first chunk freed into the empty bin:
0x55555555b2a0: 0x000000055555555b 0x5d8c1e3fa7b2c491 <- a: next = (a >> 12) ^ NULL0x55555555b shifted left by 12 is 0x55555555b000, the page holding both a and b. Since b sits on the same page, b >> 12 is also 0x55555555b. You don't even need b's exact address, just its page.
Step 3: Forge the mangled pointer and write it
The stored value must decode to the target, so encode the target with b's position:
def mangle(pos, ptr): return (pos >> 12) ^ ptr
mangle(0x55555555b2f0, 0x555555558060) # 0x55500000d53bWrite that value into the first eight bytes of b through the dangling pointer. The heap now reads:
0x55555555b2e0: 0x0000000000000000 0x0000000000000051 <- chunk b header0x55555555b2f0: 0x000055500000d53b 0x5d8c1e3fa7b2c491 <- b: next decodes to 0x555555558060Nothing has checked anything yet. tcache keeps no record of what next used to be.
Step 4: First malloc returns b
malloc(0x40) sees counts[3] == 2, so tcache_get pops the head, b. It sets the new head to REVEAL_PTR(b->next), which is 0x555555558060, drops the count to 1, zeroes b's key, and returns b. The program gets a perfectly normal-looking chunk.
Step 5: Second malloc returns the target
The next malloc(0x40) sees counts[3] == 1 and pops 0x555555558060. Before it does, it checks that the address is 16-byte aligned, which it is. Then it:
- sets the new head to
REVEAL_PTRof whatever eight bytes sit at0x555555558060(garbage, but the count is now zero, so nobody will follow it) - writes zero to
0x555555558068, clearing what it thinks is thekeyfield - returns
0x555555558060as if it were a heap chunk
Step 6: The program writes for you
Whatever the program stores into its "new buffer" lands on handler. If that's a name field read from the attacker, the attacker writes the address of their choice over handler, and the next call through it goes there.
Predict: an attacker skips Step 1's second free, so only b is in bin 3, then poisons b's next pointer exactly as above. What do the next two malloc(0x40) calls return?
Answer. The first returns b and drops counts[3] to zero, leaving the decoded target sitting in entries[3]. The second sees a count of zero and skips tcache entirely. _int_malloc finds nothing in the fastbins, small bins or unsorted bin, so it carves a fresh 0x50 chunk from the top. The target is never returned. On glibc 2.30 and later the count must be at least 2 when you poison.
The Alignment Check
The single check standing between a poisoned pointer and a returned chunk is the alignment test in tcache_get. If the decoded pointer isn't a multiple of 16, glibc aborts with malloc(): unaligned tcache chunk detected. In practice this means:
- A target like
0x555555558068can't be returned directly. Point at0x555555558060instead and write eight bytes of padding first, as long as clobbering those eight bytes doesn't break anything. - Getting the mangling wrong, say by using the wrong chunk's position, decodes to a random-looking address that's misaligned fifteen times out of sixteen. A crash with this message is a strong hint your
posis wrong. - tcache never checks the size field of the "chunk" it returns. The fastbin equivalent does, which is why fastbin attacks need a fake size value near the target and tcache attacks don't.
Remember the zero write to target + 8 as well. If those eight bytes matter, account for them.
Where to Point It on Modern glibc
For years the standard target was __free_hook: overwrite it with system, free a chunk containing "/bin/sh", done. glibc 2.34 removed __malloc_hook, __free_hook and friends from the allocator's code paths, so that recipe is dead on 2.35. Targets that still work depend on the binary and what you've leaked:
- Function pointers and objects in the program's own data. Dispatch tables, callback pointers, and C++ objects with vtables. In a non-PIE binary their addresses are fixed.
- The GOT, when the binary isn't built with full RELRO. With full RELRO the GOT is read-only after startup.
- The
tcache_perthread_structitself. It's at a known offset from the heap base. Pointing a chunk at it lets you rewrite every count and every bin head, which turns one poisoning into as many arbitrary allocations as you like. - libc's
stdiostructures, after a libc leak. File-stream oriented programming (FSOP) corrupts aFILEso that a later flush or exit calls attacker-chosen code. Modern variants have to get past glibc's vtable validation, and that's a lesson of its own. - The stack, after leaking a stack address (libc's
environvariable holds one). Pointing a chunk at a saved return address turns the heap bug back into the stack problem from Stack Buffer Overflows.
Real-World Impact
Use-after-free has been a leading bug class in web browsers for over a decade. Browsers churn through enormous numbers of objects while rendering pages and running JavaScript, and a malicious page can drive allocation and deallocation precisely enough to weaponise a dangling pointer in the browser's C++ code. Browsers mostly don't use glibc's allocator for those objects, so the tactics differ, but the shape of the attack matches the three steps above.
Browser vendors now invest heavily in mitigations: hardened allocators that separate objects by type, quarantining freed memory so it isn't reused straight away, and reference-counting schemes that keep freed memory poisoned while dangling pointers to it exist. Google's push to rewrite parts of Chrome in Rust, and Apple's adoption of Swift for system code, are both responses to the same problem.
Defensive Thinking
The best defence against use-after-free is to stop dangling pointers existing. Set pointers to NULL after freeing them, and remember that copies of the pointer elsewhere don't get cleared. Reach for smart pointers that manage lifetime for you. Better still, pick a language whose ownership rules make use-after-free a compile error.
For glibc specifically, tcache is the soft spot. Setting the tunable glibc.malloc.tcache_count=0 (via the GLIBC_TUNABLES environment variable) stops any chunk entering it, which makes the cheapest attacks above stop working, at a real cost in speed. Safe-linking and the alignment check raise the price of poisoning, and they're the reason Step 2 exists, but a single heap leak pays it.