TExcelTAD
Home › Memory Safety & Binary Exploitation Concepts › Heap Buffer Overflow (CWE-122)

Heap Buffer Overflow (CWE-122)

A heap buffer overflow writes past the end of a block that came from malloc (or new). It is one of the most common memory-corruption bugs in modern advisories, because most data that comes from outside a program (a packet, an image, a font, a document) ends up in heap buffers whose size was decided by one part of the code and whose contents are written by another. The two parts disagree, usually because a length field in the input is trusted. The overflow then corrupts the next heap block: another object's fields, a function pointer, a C++ vtable pointer, or the allocator's own chunk headers.

The bug in a toy program

The toy decodes a type-length-value (TLV) message, a format found in countless protocols: one byte of type, one byte of length, then the value. The developer assumed values are short and allocates 16 bytes for them, then copies as many bytes as the message says:

bash · try it yourself
cat > tlv.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Message: [type:1][len:1][value:len]. The value is stored in a 16-byte heap buffer. */
struct item { uint8_t type; char *value; };

static struct item *decode(const uint8_t *msg, size_t msglen) {
    if (msglen < 2) return NULL;
    struct item *it = malloc(sizeof *it);
    it->type = msg[0];
    uint8_t len = msg[1];
    it->value = malloc(16);                       /* "values are short" */
    memcpy(it->value, msg + 2, len);              /* BUG: len never compared with 16 or msglen */
    it->value[len < 16 ? len : 15] = '\0';
    return it;
}

int main(void) {
    uint8_t ok[] = {1, 5, 'a', 'l', 'i', 'c', 'e'};
    uint8_t big[2 + 40] = {2, 40};
    memset(big + 2, 'B', 40);
    setvbuf(stdout, NULL, _IONBF, 0);
    struct item *a = decode(ok, sizeof ok);
    printf("type %d value %s\n", a->type, a->value);
    struct item *b = decode(big, sizeof big);
    printf("type %d\n", b->type);
    char *next = malloc(64);                      /* the next request after the corruption */
    printf("next allocation ok: %d\n", next != NULL);
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address tlv.c -o tlv && ./tlv 2>&1 | grep -E '^type|ERROR|WRITE|#[01] |located|allocated by|^=>'
echo "exit code: ${PIPESTATUS[0]}"
echo "== the same program without ASan"
gcc -g -O0 tlv.c -o tlv0 && ./tlv0 2>&1 | cat; echo "exit code: ${PIPESTATUS[0]}"
type 1 value alice
==15==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000080 at pc 0x73559b2eb303 bp 0x7fffd8ac83f0 sp 0x7fffd8ac7b98
WRITE of size 40 at 0x502000000080 thread T0
    #0 0x73559b2eb302 in memcpy ../../../../src/libsanitizer/sanitizer_common/sanitizer_common_interceptors_memintrinsics.inc:115
    #1 0x5b1c0c731467 in decode /home/learner/tlv.c:15
0x502000000080 is located 0 bytes after 16-byte region [0x502000000070,0x502000000080)
allocated by thread T0 here:
    #0 0x73559b2ed9c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
    #1 0x5b1c0c731418 in decode /home/learner/tlv.c:14
=>0x502000000080:[fa]fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
exit code: 1
== the same program without ASan
type 1 value alice
type 2
malloc(): corrupted top size
exit code: 134

The report, line by line

  • heap-buffer-overflow … WRITE of size 40: one memcpy of 40 bytes, caught before it writes (ASan's memcpy interceptor checks the whole range first).
  • #0 memcpy, #1 decode tlv.c:15: the interceptor and the line that called it.
  • 0 bytes after 16-byte region: the write starts inside the 16-byte block and runs past its end. allocated by … decode tlv.c:14 names the malloc(16).
  • [fa]: the first heap red-zone granule after the block.

Without ASan the program prints nothing wrong. The 40 bytes run 24 bytes past the block into the next part of the heap, here the allocator's top chunk, and the corruption is noticed only at the next malloc (malloc(): corrupted top size, SIGABRT). In a larger program the next allocation might be thousands of lines later, in a different module, or never: the overflow would silently change whatever object followed the block. That distance between cause and symptom is what makes heap bugs expensive to debug without sanitizers.

What an attacker looks for

The overwritten neighbour decides the impact. Overwriting the bytes of a string or a number changes data; overwriting a pointer, a length or a function pointer in the next object gives the attacker a second, more powerful primitive (a write to a chosen place, a call to a chosen place), and overwriting the allocator's headers can make later malloc calls return memory that overlaps other objects. Attackers therefore "groom" the heap so that a chosen object follows the vulnerable buffer. Defences answer at each step: hardened allocators separate objects by size and type, safe-linking protects free lists, CFI checks indirect calls, and memory tagging gives neighbouring blocks different tags so the first out-of-bounds byte faults (Mitigations).

Root cause

Two numbers describe the same buffer: the capacity (16, chosen at allocation) and the length (from the message). The code uses the second without checking it against the first, and also without checking it against the message length (msglen), which is a second bug: a message that claims 40 bytes but carries 5 would make memcpy read past the end of the input (an out-of-bounds read).

The fix

Validate the length against the input that is really there, then allocate exactly what is needed (or reject what exceeds a documented maximum):

bash · try it yourself
cat > tlv.c <<'SRC'
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct item { uint8_t type; uint8_t len; char *value; };

/* Returns NULL for malformed input. */
static struct item *decode(const uint8_t *msg, size_t msglen) {
    if (msglen < 2) return NULL;
    size_t len = msg[1];
    if (len > msglen - 2) return NULL;            /* the value must be inside the message */
    struct item *it = malloc(sizeof *it);
    char *v = malloc(len + 1);                    /* exactly what is needed, plus the NUL */
    if (!it || !v) { free(it); free(v); return NULL; }
    memcpy(v, msg + 2, len);
    v[len] = '\0';
    it->type = msg[0]; it->len = (uint8_t)len; it->value = v;
    return it;
}

int main(void) {
    uint8_t ok[] = {1, 5, 'a', 'l', 'i', 'c', 'e'};
    uint8_t big[2 + 40] = {2, 40};
    uint8_t liar[] = {3, 200, 'x'};               /* claims 200 bytes, carries 1 */
    memset(big + 2, 'B', 40);
    const uint8_t *msgs[] = {ok, big, liar};
    size_t lens[] = {sizeof ok, sizeof big, sizeof liar};
    for (int i = 0; i < 3; i++) {
        struct item *it = decode(msgs[i], lens[i]);
        if (it) { printf("type %d len %2d ok\n", it->type, it->len); free(it->value); free(it); }
        else printf("message %d rejected\n", i);
    }
    return 0;
}
SRC
gcc -g -O0 -fsanitize=address,undefined tlv.c -o tlv-fixed && ./tlv-fixed 2>&1
echo "exit code: $?"
type 1 len  5 ok
type 2 len 40 ok
message 2 rejected
exit code: 0

The 40-byte value is now accepted, because the buffer is sized to it; the lying message is rejected. If the protocol has a maximum value size, enforce it with an explicit constant and a test, not with the size of a buffer chosen years ago.

How it is detected

  • ASan in tests and fuzzing: heap overflows are among the most frequent ASan findings in OSS-Fuzz.
  • Compiler warnings catch constant cases (-Wstringop-overflow: "writing 32 bytes into a region of size 24").
  • Review: for every memcpy, memmove, strcpy and indexed write into a heap buffer, find where the length comes from and where the capacity was set; both must be visible, and compared, near the write.
  • Allocator aborts in production: malloc(): corrupted top size, free(): invalid next size, corrupted size vs. prev_size.

The CWE

CWE-122: Heap-based Buffer Overflow, a child of CWE-787. When the wrong length came from an integer overflow, record both (CWE-190 leading to CWE-122; see Integer Overflow to Undersized Allocation).

Pitfalls

  • Checking only one bound. len <= 16 without len <= msglen - 2 swaps the overflow for an over-read.
  • msglen - 2 with msglen < 2 underflows to a huge number in unsigned arithmetic; that is why the fix checks msglen < 2 first.
  • realloc growth bugs: computing the new size and then writing with the old index arithmetic, or forgetting that realloc can fail and return NULL while the old block stays valid.

Practice

1. How many bytes past the 16-byte block did the original memcpy try to write?

40 − 16 = 24 bytes.

2. Why did the non-ASan build print type 2 correctly and only fail at the next malloc?

The overflow corrupted memory after the block (here the top chunk's size field) but nothing read that memory until the allocator cut a new chunk from the top and checked its size.

3. Add a test message that the fixed decoder must reject because it is too short for its header.

uint8_t tiny[] = {4}; with length 1: msglen < 2, rejected before msg[1] is read.

Test yourself

In the ASan report, which line allocated the overflowed block?

  1. tlv.c:15
  2. tlv.c:14, the malloc(16)
  3. The memcpy interceptor
  4. main

What happened in the build without ASan?

  1. It crashed in memcpy
  2. It ran on, and glibc aborted at the next malloc with 'corrupted top size'
  3. It printed an ASan report
  4. Nothing ever happened

Which two checks does a length field from input need?

  1. Against the buffer capacity and against the bytes really present in the input
  2. Only that it is positive
  3. Only against the buffer capacity
  4. Against INT_MAX

Why do attackers care about the object that follows a vulnerable heap buffer?

  1. They don't
  2. Overwriting a pointer, length or function pointer in it turns the overflow into a more powerful primitive
  3. It holds the return address
  4. It is always the stack