Heap Hardening
Binary Hardening & Compiler Defenses · Security Fundamentals track
7 min read
In this module
Hardening the Heap
The heap is a sprawling, dynamic data structure, and that sprawl is itself attack surface. Heap corruption has been a dominant vulnerability class for over two decades, and the resulting arms race has produced ever-more-sophisticated heap hardening. This lesson walks through the defences modern allocators throw at exploitation.
Safe Unlinking
In classic glibc (ptmalloc2), freed chunks are stored in doubly-linked free lists. The unlink macro removes a chunk from a list by following its fd (forward) and bk (backward) pointers. In early versions, this was:
// Classic unsafe unlink#define unlink(P, BK, FD) { \ FD = P->fd; \ BK = P->bk; \ FD->bk = BK; // Write BK to FD->bk \ BK->fd = FD; // Write FD to BK->fd \}If an attacker corrupted P->fd and P->bk, they could make the unlink operation write an arbitrary value to an arbitrary address. This was the classic heap unlink exploit - one of the earliest arbitrary write primitives from heap corruption.
Safe unlinking adds integrity checks:
// Safe unlink (modern glibc)#define unlink(P, BK, FD) { \ FD = P->fd; \ BK = P->bk; \ if (FD->bk != P || BK->fd != P) \ abort(); \ FD->bk = BK; \ BK->fd = FD; \}The check verifies that the forward chunk's backward pointer and the backward chunk's forward pointer both point to the chunk being unlinked. If the attacker has corrupted any of these pointers, the check fails. This simple validation closed one of the most powerful exploitation techniques in heap exploitation history.
Heap Cookies and Metadata Protection
Beyond safe unlinking, modern allocators protect their metadata in additional ways:
Heap cookies (also called heap guards) are random values stored in chunk headers. Like stack canaries, they detect metadata corruption. If the cookie does not match the expected value when the chunk is processed, the allocator aborts. The Windows heap works this way, and scudo (below) checksums its headers. glibc's ptmalloc has no cookies; it relies on sanity checks of sizes, alignment and list links instead, which is where errors such as double free or corruption (out), free(): double free detected in tcache 2 and malloc(): corrupted top size come from.
Pointer mangling obfuscates pointers stored in heap metadata. glibc's version, safe-linking, uses PROTECT_PTR and REVEAL_PTR macros that XOR each free-list pointer with the address of the slot it's stored in, shifted right by 12. There's no secret key involved:
#define PROTECT_PTR(pos, ptr) \ ((void *)((((size_t)(pos)) >> 12) ^ ((size_t)(ptr))))#define REVEAL_PTR(pos, ptr) \ PROTECT_PTR(pos, ptr) // XOR is its own inverseBecause ASLR randomises the heap's position, an attacker who doesn't know where the heap is can't forge a mangled pointer that decodes to their target, and a pointer that decodes to a misaligned address is rejected. That blocks naive poisoning. It isn't a secret, though: one leaked heap address supplies the key. Worse, the last entry in a list stores NULL, so its mangled value is the key itself (pos >> 12), and reading it leaks the heap location.
glibc's tcache (thread-local cache) and fastbins were historically unprotected - single-linked lists with no integrity checks. Starting with glibc 2.32, safe-linking mangles both tcache and fastbin pointers, using the slot address >> 12 as above, and checks that each revealed pointer is suitably aligned. That makes tcache poisoning (writing a fake pointer into the free list) need a heap leak first.
Guard Pages
Guard pages are unmapped memory pages placed at the boundaries of heap regions. If a heap overflow or underflow crosses into a guard page, the CPU raises a segmentation fault, immediately halting the exploit.
Guard pages are not placed between every allocation - that would waste enormous amounts of memory (each guard page is typically 4 KB). Instead, they are placed at the boundaries of large allocations or between different heap regions. Some security-focused allocators use guard pages more aggressively, trading memory for safety.
PartitionAlloc
PartitionAlloc, developed for Chromium, takes a fundamentally different approach to heap security. Instead of trying to detect corruption after it happens, PartitionAlloc limits cross-type corruption by isolating allocations into separate memory partitions based on their broad category or origin.
Key design principles:
- Category-based isolation: Different kinds of allocation (in Blink, for example, buffers and strings versus other objects) come from different partitions. An overflow in a buffer partition can't reach an object in another partition because they live in separate memory regions.
- Separate metadata: Allocation metadata is stored out-of-line (in a separate page from the user data), so overflowing user data cannot corrupt allocator metadata.
- Guard partitions: Guard pages between partitions prevent overflows from crossing partition boundaries.
- No reuse across partitions or size buckets: Freed memory is only handed out again from the same partition and size bucket. That stops a freed buffer being reused as an object from another partition, but two different types of the same size in the same partition can still share memory, so use-after-free type confusion is narrowed rather than ruled out.
Hardened Allocators
Several allocators are designed specifically for security rather than performance:
scudo (used in Android's Bionic libc and Fuchsia) combines chunk header checksums, quarantine zones (delaying reallocation of freed memory to catch use-after-free), and randomized allocation patterns. It uses a CRC32 checksum on chunk headers to detect corruption.
hardened_malloc (used in GrapheneOS) goes further with large guard regions, randomized slot allocation within size classes, and mandatory zeroing of freed memory. It isolates allocations by size class and uses random slot selection within each class, making heap feng shui extremely difficult.
mimalloc with security features provides segment-level isolation, guard pages, and randomized free lists. It is designed to be a drop-in replacement for standard allocators with improved security properties.
Standard allocator memory layout:[chunk A][chunk B][chunk C][chunk D] ← adjacent, overflow from A corrupts B
PartitionAlloc layout:Partition 1: [string A]...[string C]... ← only stringsPartition 2: [object B]...[object D]... ← only objects[guard page between partitions]The Trade-Off Space
Heap hardening always involves trade-offs:
- Performance: Integrity checks, guard pages, and randomisation all cost CPU cycles and memory
- Compatibility: Some programs rely on allocator behaviour that hardened allocators deliberately break (like deterministic allocation ordering)
- Completeness: No single technique stops all heap attacks. Safe unlinking stops metadata corruption but not application data corruption. PartitionAlloc stops corruption across partitions but not within one.
Read each row of the diagram below from left to right: an attack, the check that was added to stop it, and the gap that check leaves. Every check here raised the price of an attack without ending it.
The trend in the industry is towards allocators that provide strong default security with acceptable performance overhead. Chrome's PartitionAlloc, Android's scudo, and the various hardened allocator projects demonstrate that significant security improvements are achievable with single-digit percentage performance costs.
ARM Memory Tagging Extension (MTE) and Intel's proposed memory tagging assign random tags to memory regions and pointers. Every memory access checks that the pointer's tag matches the memory's tag. This catches both spatial (overflow) and temporal (use-after-free) bugs with hardware-level enforcement and low overhead. MTE is available in ARM v8.5-A and is being deployed on Android devices.