Skip to main content
Be Bitwise

Heap Overflow & Allocator Metadata

Heap Vulnerabilities & Use-After-Free · Exploitation Fundamentals track

11 min read

In this module

Beyond the Stack

You've seen stack buffer overflows clobber the return address. Heap overflows look different. There's no return address on the heap. Writing past a heap buffer corrupts whatever happens to be next door: usually another object, and always, on glibc, the allocator's own metadata.

This lesson works through what an overflow can do to ptmalloc2 chunks, how the unsorted bin behaves, one "House of" technique that still works today, and the checks that retired the older ones. The version is glibc 2.35 (Ubuntu 22.04) on x86-64, with notes where a technique's life span depends on the release. The labs run glibc 2.39, and nothing here differs there.

How Heap Memory Is Organised

Lesson 1 showed that chunks sit back to back, each one starting with prev_size and size, and that an in-use chunk's last 8 usable bytes overlap the next chunk's prev_size.

There's no gap, no guard byte, nothing between the end of A's usable space and B's size field. A useful formula: for a chunk of size S with user pointer p, the next chunk's size field is at p + S - 8. For a 0x30 chunk that's p + 0x28, the very first byte past the 0x28 bytes malloc(0x28) promised.

Allocator Metadata Corruption

Allocator metadata corruption occurs when a heap overflow writes past the end of an allocated object and into the header of the next chunk, or into the list pointers of a free one. Because glibc trusts its size fields and list pointers when it splits, merges and recycles chunks, corrupting them can make the allocator hand out overlapping memory or return a pointer to an address of the attacker's choosing.

What an Overflow Reaches

Take this layout: a = malloc(0x28) (chunk 0x30), then b = malloc(0x40) and c = malloc(0x40) (0x50 each). The program reads up to 0x40 bytes into a. Here's the heap after an attacker sends 0x28 A characters followed by 8 bytes of their choice:

text
0x55555555b290: 0x0000000000000000 0x0000000000000031 <- chunk a
0x55555555b2a0: 0x4141414141414141 0x4141414141414141 <- a
0x55555555b2b0: 0x4141414141414141 0x4141414141414141
0x55555555b2c0: 0x4141414141414141 0x00000000000000a1 <- chunk b: size was 0x51
0x55555555b2d0: 0x0000000000000000 0x0000000000000000 <- b
...
0x55555555b310: 0x0000000000000000 0x0000000000000051 <- chunk c
0x55555555b320: 0x0000000000000000 0x0000000000000000 <- c

An overflow of eight bytes gave the attacker b's size field. Depending on what follows, an overflow like this gets used in one of four ways.

Overwrite the neighbour's data. Skip the metadata and aim for the object behind it: a function pointer or length field in b. The size field is in the way, so a careful exploit rewrites it with its original value (0x51 here) and keeps going. The Heap Overflow lab works on this principle.

Grow the neighbour. That's what the dump shows. b now claims to be 0xa0 bytes, exactly covering itself and c. When the program frees b, _int_free checks the pointer and the size for sanity, finds an aligned size in tcache range, and puts it in the 0xa0 tcache bin. It never looks at what follows. The next malloc(0x90) returns 0x55555555b2d0 with 0x98 usable bytes, and those bytes contain c's header and all of c's data. Two live pointers now cover the same memory. If c is later freed into tcache, writing through the big chunk edits c's next pointer, and you're back to lesson 3's tcache poisoning.

Shrink the neighbour, or clear its PREV_INUSE. Lesson 1 noted that free trusts PREV_INUSE and prev_size when merging backwards. An off-by-one that writes a single 0x00 past the end of a buffer (common with string handling that forgets the terminator) can turn a size of 0x501 into 0x500. When that chunk is freed through the normal path, glibc believes the chunk before it is free, reads prev_size (which the overflowing buffer also controls, as its last 8 bytes) and tries to merge with a "chunk" that the attacker described. This is the poison null byte.

Corrupt a free neighbour's list pointers. If the next chunk is already free in tcache or a fastbin, its mangled next/fd sits at offset 0x10 from its header, a few bytes past the size field. An overflow reaches it directly, which gives tcache poisoning without any use-after-free.

The Checks a Merge Must Pass

Backward merging is where the poison null byte lives or dies, and glibc has added checks there over time. On 2.35, before merging a chunk p with the previous chunk, free checks that the chunk found at p - prev_size has a size equal to prev_size (aborting with corrupted size vs. prev_size while consolidating, added in 2.29). Then it unlinks that chunk from its bin, and the unlink code checks:

  • the size recorded in the chunk matches the prev_size of the chunk after it (corrupted size vs. prev_size)
  • fd->bk and bk->fd both point back at the chunk being unlinked (corrupted double-linked list)

So the attacker must build a fake free chunk whose size agrees with the forged prev_size and whose fd and bk point at places that point back to it. That needs a heap address, or careful partial overwrites. It's fiddly, but it still works on 2.35, and the how2heap project keeps a tested example for each glibc release.

The Unsorted Bin

Chunks too big for tcache and fastbins, or freed when their tcache bin is full, go through the unsorted bin. It's one circular, doubly linked list whose head lives inside main_arena in libc. Freed chunks are merged with free neighbours and placed at the head. Nothing is sorted at free time.

The sorting happens in malloc. When a request misses tcache and the fastbins and small bins, _int_malloc walks the unsorted bin from the tail. An exact-size match is returned (or, if there's tcache room, stashed there and returned once the walk is done). Every other chunk is moved into its small or large bin. If the request still isn't satisfied, glibc finds a bigger chunk in the sorted bins, splits it, and puts the remainder back in the unsorted bin.

The doubly linked pointers aren't protected by safe-linking. A lone chunk in the unsorted bin has fd and bk both pointing at the bin's head inside main_arena:

text
0x55555555b6c0: 0x0000000000000000 0x0000000000000501 <- free 0x500 chunk
0x55555555b6d0: 0x00007ffff7e19ce0 0x00007ffff7e19ce0 <- fd, bk -> main_arena

0x7ffff7e19ce0 is libc's base address plus an offset fixed for that particular libc build. Read it through a use-after-free or an uninitialised-memory bug, subtract the offset (find it once in a debugger), and libc's ASLR is gone. It's the most common libc leak in heap exploitation.

Since glibc 2.29, the unsorted-bin walk checks each chunk before using it: the size must be sane, the next chunk's prev_size must match, the next chunk's PREV_INUSE must be clear, and bk->fd must point back at the chunk. Those checks killed the unsorted bin attack, which corrupted a chunk's bk so that the unlink wrote the bin's address over an arbitrary target.

Predict: a program allocates one 0x500 chunk, then frees it without allocating anything after it. Which bin is it in afterwards?

Answer. None. 0x500 is too big for tcache (the largest tcache size is 0x410) and for the fastbins, so it takes the normal free path. Its upper neighbour is the top chunk, and a chunk bordering the top is merged into it. Heap exploits that want a chunk in the unsorted bin allocate a small "guard" chunk after it first, so it has something other than the top as its neighbour.

A House That Still Stands: House of Botcake

Heap techniques get named "House of" something, after a 2005 text called The Malloc Maleficarum. Most of the early ones are dead. House of Botcake still works: it applies from glibc 2.26, when tcache arrived, through at least 2.39. On 2.32 and later the last step also needs a heap leak, because the poisoned pointer has to be mangled.

Botcake turns a double free into overlapping chunks, sidestepping the tcache key check from lesson 2. The setup uses 0x110 chunks (malloc(0x100)):

  1. Allocate seven 0x110 chunks to fill tcache later, then prev and a, then a small guard chunk so a doesn't border the top.
  2. Free the seven. The 0x110 tcache bin is now full.
  3. Free a. tcache is full and 0x110 is beyond fastbin range, so a goes to the unsorted bin.
  4. Free prev. It's directly below a, and a is free, so glibc merges them into one 0x220 chunk in the unsorted bin. a's old header is still there, inside the merged chunk, still saying 0x111.
  5. malloc(0x100) once, which takes a chunk out of the tcache bin and leaves room for one more.
  6. Free a again. Its offset-8 word holds an old bk pointer from its time in the unsorted bin, which isn't tcache_key, so the double-free walk never runs. The size field still reads 0x111, so a goes into tcache.
  7. Now a is in tcache and inside the 0x220 free chunk at the same time. Request a slightly bigger size, say malloc(0x120). glibc carves it from the merged chunk starting at prev, so the returned buffer covers a's header and its next pointer at prev + 0x110.
  8. Write a mangled pointer, (a >> 12) ^ target, over a's next. Two malloc(0x100) calls later, glibc returns target.

The technique asks for one double free (or a use-after-free that can call free) and, on 2.32 and later, one heap leak. That's a modest price for an arbitrary allocation, and it's why Botcake shows up so often in modern CTF heap challenges.

The Checks That Killed the Rest

Every row below was once a standard technique. Each died to a specific check, and knowing which check is what lets you judge whether an old write-up applies to your target.

TechniqueWhat it abusedWhat stopped itSince
Classic unlinkForged fd/bk turned the unlink into a write-what-wherefd->bk and bk->fd must point back at the chunkmid-2000s
House of Orange (classic)Unsorted bin attack on _IO_list_all plus a fake FILE vtablelibio vtable validation, then the 2.29 unsorted checks2.24, 2.29
House of ForceOverwriting the top chunk's size with a huge valuemalloc(): corrupted top size2.29
Unsorted bin attackCorrupting an unsorted chunk's bkUnsorted list integrity checks2.29
Naive tcache double freeFreeing the same chunk twicetcache key field and bin walk2.29
One-free tcache poisoningPoisoning a bin holding one chunkmalloc checks the bin count, not the head2.30
Blind or partial pointer overwriteEditing tcache/fastbin links without a leakSafe-linking plus alignment checks2.32
Hook overwritesPointing __free_hook or __malloc_hook at systemHooks removed from malloc2.34

Notice what the table doesn't contain. Nothing in it stops an attacker who can write to a free chunk's link and has a heap leak. glibc's checks verify that metadata is self-consistent. They can't tell whether a consistent-looking value was written by the allocator or by an attacker who read the source.

Stack vs. Heap Overflow Comparison

AspectStack OverflowHeap Overflow
TargetReturn addressChunk headers, free-list links, adjacent objects
TriggerFunction return (ret)A later malloc or free
PredictabilityLayout fixed by the compilerLayout depends on allocation history
Typical resultDirect control of ripOverlapping chunks or an arbitrary allocation, then a write

Heap overflows tend to be harder to exploit, because the layout shifts with the order and sizes of earlier allocations, and a good exploit spends much of its length "grooming" the heap into a known state first. They're no less dangerous once an attacker pulls it off.

Real-World Heap Exploits

Browser engines are among the juiciest targets for heap bugs. Chrome, Firefox and Safari have each fixed large numbers of heap overflows and use-after-frees over the years. Rendering web content (parsing HTML, running JavaScript, laying out CSS) generates a torrent of dynamic allocation, and every allocation boundary is a potential overflow site. Server software on Linux uses glibc's allocator directly, which is why the details in this module turn up in real advisories as well as CTFs.

These bugs reinforce a lesson from Security Fundamentals: security comes from enforcing boundaries. On the heap, software has to do the enforcing, because the hardware sees one flat region of memory, and the allocator's checks can only confirm that its bookkeeping looks plausible. For the compiler and OS defences that sit around all of this, see Exploit Mitigations.