Out-of-Bounds Reads and Heartbleed (CWE-125)
An out-of-bounds read doesn't corrupt anything. It copies bytes the program never meant to expose, and that is enough: private keys, session cookies, passwords and pointers (which defeat ASLR) all live in the same address space as the buffer being read. The most famous example is Heartbleed (CVE-2014-0160, disclosed in April 2014), a missing length check in OpenSSL's implementation of the TLS heartbeat extension (RFC 6520). A client sent a heartbeat request with a tiny payload but claimed a length of up to 64 KB, and the server echoed back that many bytes from its own heap, request after request, without crashing and without leaving a trace in the usual logs. It affected OpenSSL 1.0.1 through 1.0.1f; 1.0.1g fixed it. Out-of-bounds reads (CWE-125) have been in MITRE's CWE Top 25 every year since 2019.
The bug in a toy program
The toy implements the heartbeat idea on its own heap and nothing else: a request carries a 4-byte payload and claims a length, and the reply echoes claimed bytes. Another object, a lab-only "session key", happens to be allocated next to the payload. The first run is a normal build; the second is the same program under ASan. It runs in your sandbox:
cat > echo.c <<'SRC'
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* A toy "heartbeat": the request carries a payload and claims its length; the reply echoes it. */
struct request { size_t claimed; size_t actual; char *payload; };
static char *heartbeat(const struct request *rq) {
char *reply = malloc(rq->claimed);
memcpy(reply, rq->payload, rq->claimed); /* BUG: trusts the claimed length */
return reply;
}
static void show(const char *label, const char *p, size_t n) {
printf("%-8s", label);
for (size_t i = 0; i < n; i++) putchar(p[i] >= 32 && p[i] < 127 ? p[i] : '.');
putchar('\n');
}
int main(void) {
setvbuf(stdout, NULL, _IONBF, 0);
char *payload = malloc(8);
memcpy(payload, "ping", 4);
char *secret = malloc(24); /* another object on the heap */
strcpy(secret, "LAB-ONLY-SESSION-KEY-42");
struct request honest = {4, 4, payload}, lying = {64, 4, payload};
char *r1 = heartbeat(&honest); show("honest:", r1, honest.claimed);
char *r2 = heartbeat(&lying); show("lying:", r2, lying.claimed);
free(r1); free(r2); free(secret); free(payload);
return 0;
}
SRC
gcc -g -O0 echo.c -o echo && ./echo
echo "== the same program with ASan"
gcc -g -O0 -fsanitize=address echo.c -o echo-asan && ./echo-asan 2>&1 | grep -E '^honest|ERROR|READ|#1 |located|^=>'
echo "exit code: ${PIPESTATUS[0]}"honest: ping
lying: ping....................!.......LAB-ONLY-SESSION-KEY-42.!.......
== the same program with ASan
honest: ping
==21==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000018 at pc 0x7f6e7649f42e bp 0x7ffce68c5de0 sp 0x7ffce68c5588
READ of size 64 at 0x502000000018 thread T0
#1 0x56a90803d38f in heartbeat /home/learner/echo.c:10
0x502000000018 is located 0 bytes after 8-byte region [0x502000000010,0x502000000018)
allocated by thread T0 here:
#1 0x56a90803d5da in main /home/learner/echo.c:22
=>0x502000000000: fa fa 00[fa]fa fa 04 fa fa fa fa fa fa fa fa fa
exit code: 1
The normal build answers the lying request with 64 bytes: the 4-byte payload, then whatever follows it on the heap, including the neighbouring object's string, printed here with non-printable bytes as dots. No crash, no error. That silence is what made Heartbleed so damaging: servers kept running and leaked a different 64 KB on every request.
ASan stops the same request at once:
heap-buffer-overflow … READ of size 64: ASan uses the same name for reads and writes; the second line says which. Thememcpyinterceptor checked the source range before copying.#1 heartbeat echo.c:10: thememcpy.0 bytes after 8-byte region … allocated by … main echo.c:22: the source block is the 8-byte payload buffer. The shadow line shows00(the 8 payload bytes), the red zone that was touched, and further on04, a block of which only 4 bytes are addressable: the honest replyr1. ASan's allocator groups blocks by size class, so under ASan the 24-byte secret isn't next door at all; red zones and size classes are part of why ASan catches what glibc's layout would hide.
Root cause
The length in the message and the length of the data really received are two different numbers, and the code used the attacker's. OpenSSL's code had the same shape: it read the 16-bit payload length from the record and memcpy'd that many bytes from the start of the payload into the response, without comparing it with the size of the record that had arrived.
The fix
Compare the claimed length with what is really there, and silently drop the message if they disagree. RFC 6520 says exactly that: a heartbeat message whose payload length is too large must be discarded. OpenSSL 1.0.1g added that check before the copy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct request { size_t claimed; size_t actual; const char *payload; };
/* Returns NULL (drop the message) unless the claimed length matches the received payload. */
static char *heartbeat(const struct request *rq, size_t *outlen) {
if (rq->claimed == 0 || rq->claimed > rq->actual) return NULL;
char *reply = malloc(rq->claimed);
if (!reply) return NULL;
memcpy(reply, rq->payload, rq->claimed);
*outlen = rq->claimed;
return reply;
}
int main(void) {
struct request tests[] = {{4, 4, "ping"}, {64, 4, "ping"}, {0, 4, "ping"}, {3, 4, "ping"}};
for (int i = 0; i < 4; i++) {
size_t n = 0;
char *r = heartbeat(&tests[i], &n);
if (r) printf("claimed %2zu actual %zu -> reply \"%.*s\"\n", tests[i].claimed, tests[i].actual, (int)n, r);
else printf("claimed %2zu actual %zu -> dropped\n", tests[i].claimed, tests[i].actual);
free(r);
}
return 0;
}claimed 4 actual 4 -> reply "ping"
claimed 64 actual 4 -> dropped
claimed 0 actual 4 -> dropped
claimed 3 actual 4 -> reply "pin"
The lying request is dropped; the regression test is the {64, 4} case. A claim shorter than the data is harmless here (it echoes a prefix), though a strict protocol might reject it too.
How out-of-bounds reads are detected
- ASan catches over-reads like over-writes, on the heap, stack and globals.
- Fuzzing finds them easily with ASan and almost never without it, since nothing crashes. Heartbleed was found independently by Neel Mehta of Google Security and by Codenomicon engineers working on the company's Defensics testing tools.
- Review: every
memcpy/memmove, loop or index whose bound is a length field from input. Ask: "what proves this many bytes exist?" - In production there is little to see. Over-reads that cross into unmapped memory crash (
SIGSEGV); the rest leave no trace, which is why Heartbleed response included assuming keys were stolen.
Impact and response
After Heartbleed, fixing the code was only the first step. Because private keys may have leaked, operators had to patch, generate new keys, reissue and revoke certificates, and invalidate sessions and passwords. That is the general lesson for over-reads of secrets: the patch closes the hole, but anything that might have been read must be treated as exposed. The incident also led to the Linux Foundation's Core Infrastructure Initiative, which funded critical, under-resourced open-source projects, and OpenBSD forked OpenSSL into LibreSSL within weeks; Google's BoringSSL fork followed in June 2014.
The CWE
CWE-125: Out-of-bounds Read; MITRE also lists Heartbleed as the first observed example of CWE-130 (Improper Handling of Length Parameter Inconsistency), which names this exact root cause. Over-reads used to leak pointers are the usual first step of exploits that must defeat ASLR.
Pitfalls
- "It's only a read." Reads leak keys and pointers; a leaked pointer is often the piece an attacker needs to turn a separate write bug into code execution.
- Reading to the NUL.
strlen,printf("%s")andstrcpyon a buffer that isn't terminated read until they happen to find a zero byte: an over-read with no explicit length anywhere. - Checking
claimed <= MAXonly. A maximum keeps the reply small but still leaks up toMAXbytes; compare with the real received length.
Practice
1. In the leaked reply, why are there dots between "ping" and the secret string?
They are bytes that aren't printable: the rest of the payload chunk (zeros) and the next chunk's size field (0x21 prints as !, the rest are zeros). The reply shows the heap layout of the allocator lesson: payload chunk, header, secret chunk.
2. Why must keys be replaced after an over-read bug is fixed, but not necessarily after an overflow that only crashed?
An over-read may already have copied the key to an attacker without any trace. The fix stops future reads; it can't undo past ones. Whether an overflow led to compromise depends on evidence; an over-read of a secret is assumed to have exposed it.
3. Which test case in the fixed program corresponds to the Heartbleed request?
{64, 4, "ping"}: a claimed length larger than the received payload. It is dropped.
Test yourself
What did the normal (non-ASan) build do with the lying request?
- Crashed
- Returned 64 bytes, including the neighbouring object's secret string, without any error
- Returned 4 bytes
- Printed an error
Which versions of OpenSSL were affected by Heartbleed?
- 0.9.8 only
- 1.0.1 through 1.0.1f; 1.0.1g fixed it
- All versions ever
- 3.0.0 through 3.0.7
What did the fix compare?
- The claimed payload length with the length of the data actually received
- The payload with a blocklist
- The claimed length with 64 KB
- The record type
Why is fuzzing without ASan poor at finding over-reads?
- Fuzzers can't send long inputs
- Most over-reads don't crash, so without a sanitizer nothing signals the bug
- ASan makes programs faster
- Over-reads only happen on the stack