FOUNDING PRICING · 40% OFFfor the first 1,000 members · from ₹95/month
OutageOpenSSL11 min read

Heartbleed Explained: The OpenSSL Bug That Leaked Memory

How a missing bounds check in the OpenSSL heartbeat code let anyone read server memory in 2014, how it was fixed, and why you never trust a length field.

ShareXLinkedInWhatsApp
Close view of several tall racks filled with rack-mounted servers at the Wikimedia Foundation, their front panels lit by small blue and white lights.
Close view of several tall racks filled with rack-mounted servers at the Wikimedia Foundation, their front panels lit by small blue and white lights. Photo: Victor Grigas, CC BY-SA 3.0, via Wikimedia Commons.

On 7 April 2014 the OpenSSL project published a short advisory about a missing bounds check in its handling of the TLS heartbeat extension. The bug, soon known as Heartbleed and tracked as CVE-2014-0160, let anyone on the internet ask a vulnerable server to send back up to 64 KB of its own memory per request, with no password and no trace in the logs. That memory could hold passwords, session cookies and the server's private key.

The flaw was not in the cryptography and not in the TLS protocol. It was one unchecked number in a C program, and that is why it is the cleanest case study there is for a rule every engineer should carry: never trust a length that the other side tells you.

A diagram comparing an honest heartbeat, where the claimed payload length matches the bytes that arrived and the server echoes only those bytes, with a dishonest one, where the claimed length is far larger and the server's copy runs past the request into neighbouring memory that holds secrets.

What was exposed, and to whom

OpenSSL is an open source library that implements TLS, the protocol behind HTTPS. In 2014 it sat inside the Apache and nginx web servers, which heartbleed.com notes had a combined share of over 66% of active sites, and inside mail servers, chat servers, VPNs and network appliances.

The vulnerable versions were OpenSSL 1.0.1 to 1.0.1f, plus the 1.0.2 betas. The older 1.0.0 and 0.9.8 branches were not affected, because they did not contain the heartbeat code. Version 1.0.1 was also the first release with TLS 1.1 and 1.2, so administrators who had kept up to date were the ones exposed.

The researchers at Codenomicon who co-discovered the bug tested it against their own services from outside. They reported recovering, without any credentials, the secret keys for their certificates, user names and passwords, emails and documents. They sorted the damage into four kinds:

  • Primary key material: the server's private key. With it, an attacker can impersonate the site or decrypt traffic.
  • Secondary key material: user names and passwords.
  • Protected content: the actual messages, documents and financial details.
  • Collateral: memory addresses and similar details that help other attacks.

Netcraft's survey on the day found the heartbeat extension enabled on 17.5% of SSL sites, covering around half a million certificates issued by trusted authorities. Netcraft was clear that this counted servers that supported heartbeats, so it is an upper bound on exposure, not a count of confirmed victims.

A computer motherboard photographed at an angle, with four green memory modules seated in their slots beside the processor socket.
Memory modules on a desktop motherboard. Heartbleed leaked whatever a server process happened to be holding in RAM; this board is illustrative, not from an affected system. Photo: Mixabest, Public domain, via Wikimedia Commons.

The key dates:

WhenWhat happened
31 Dec 2011The heartbeat implementation, bug included, is committed to the OpenSSL source.
Feb 2012RFC 6520, the specification of the heartbeat extension, is published.
14 Mar 2012OpenSSL 1.0.1 is released. The bug is now in the wild.
3 Apr 2014The Codenomicon team finds the bug. Neel Mehta of Google Security found it independently and was the first to report it to OpenSSL.
7 Apr 2014OpenSSL publishes its advisory and releases the fixed 1.0.1g.
11 Apr 2014Participants in a public Cloudflare challenge recover a test server's private key using only this bug.
14 Apr 2014The Canada Revenue Agency says about 900 social insurance numbers were taken.
29 May 2014The Linux Foundation's Core Infrastructure Initiative names OpenSSL among its first funded projects.

What a TLS heartbeat is

A TLS connection is expensive to set up, so both sides would like to keep it open. The heartbeat extension gives them a cheap way to check that the other end is still there without renegotiating the connection. It matters most for DTLS, the variant of TLS that runs over UDP, where there is no underlying connection to tell you the peer has gone.

The exchange is simple. One side sends a heartbeat request containing a small payload of arbitrary bytes. The other side must reply with a heartbeat response containing an exact copy of that payload. If the copy comes back, the peer is alive.

The message format in RFC 6520 has four fields:

FieldSizeMeaning
type1 byteRequest or response
payload_length2 bytesHow long the sender says the payload is
payloadpayload_length bytesThe bytes to echo back
paddingat least 16 bytesRandom bytes the receiver ignores

Notice that the message carries its own length. That is normal for network protocols, and it is exactly where the trouble starts.

The bug: one length that was never compared with another

A heartbeat message does not arrive on its own. It travels inside a TLS record, and the TLS layer knows how many bytes that record actually contained, because it counted them as they came off the network. So at the moment the heartbeat code runs, the server holds two numbers:

  1. The record length: measured by the server itself. Trustworthy.
  2. The payload_length field: written by whoever sent the message. A claim.

For an honest peer, the two agree. The vulnerable code never checked. It read payload_length, allocated a reply buffer of that size, and copied that many bytes out of the request buffer into the reply. In outline, the logic was:

// p points at the heartbeat message inside the received record
type    = p[0];
claimed = (p[1] << 8) | p[2];        // payload_length, chosen by the sender
payload = p + 3;

reply = malloc(1 + 2 + claimed + 16);
memcpy(reply + 3, payload, claimed); // copies 'claimed' bytes, whatever arrived
send(reply);

If the sender claims a payload much longer than the one it actually sent, memcpy does not stop at the end of the request. C arrays do not carry their size, and memcpy copies exactly as many bytes as it is told to. It keeps reading from the addresses that follow the request buffer, which belong to the same process and hold whatever that process stored there earlier. All of it goes into the reply and out over the network.

Because payload_length is a 16-bit field, one reply could carry up to 65,535 bytes that were never part of the request. That is the 64 KB in the advisory. Nothing limited how many heartbeats a peer could send, so the leak could be repeated to sample memory again and again.

The CVE entry classifies this as a buffer over-read. Nothing was overwritten, nothing crashed, and no code was injected. The server simply read too far and posted the result to whoever asked.

A diagram of a heartbeat message inside a TLS record, showing the record length measured by the server alongside the payload length claimed by the sender, and the comparison added by the fix: type, length field, claimed payload and minimum padding must fit inside the record, otherwise the message is discarded.
Two lengths, one measured and one claimed, and the comparison the fix added

Why nobody noticed for two years

It looked like normal traffic. A heartbeat request followed by a heartbeat response is a legitimate exchange. Heartbleed.com states that exploitation left nothing abnormal in the logs, so site owners could not tell afterwards whether they had been probed.

The server never misbehaved. A buffer overflow that writes out of bounds tends to corrupt something and crash. An over-read inside memory the process already owns is silent. No fault is raised, so nothing draws attention to it.

It needed no privileges. The CVE record describes a remote attacker with no authentication. Client certificates did not help, because the heartbeat code could run before authentication finished.

The specification was right; the code was not. RFC 6520 says a heartbeat whose payload_length is too large must be discarded silently. The check existed on paper and was simply not written. The change was reviewed before it was merged, and the omission was missed there as well.

The project was tiny compared with its reach. When the Core Infrastructure Initiative later announced its support, part of the funding was for two full-time core developers for OpenSSL. A library protecting a large share of the internet's traffic had been maintained on very thin resources.

The fix, and the clean-up that followed

The patch, prepared by Adam Langley and Bodo Moeller and shipped in OpenSSL 1.0.1g, adds the comparison that was missing. Before doing anything else, the code now confirms that the type byte, the two length bytes, the claimed payload and the minimum 16 bytes of padding all fit inside the record that actually arrived. If they do not, the message is dropped without a reply, as the RFC requires:

if (1 + 2 + claimed + 16 > record_length)
    return 0;   // discard silently

For anyone who could not upgrade at once, the advisory offered a blunt alternative: recompile with -DOPENSSL_NO_HEARTBEATS and remove the feature entirely.

Patching closed the hole, but it could not undo what might already have leaked. Because exploitation left no trace, operators had to assume the worst. Heartbleed.com set out the recovery steps: patch, then revoke the old certificate and issue a new one with a new private key, then invalidate session keys and cookies, and only then ask users to change passwords. The order matters. A password changed on a server that is still vulnerable, or still using a key that may have been copied, can be stolen again.

Whether a private key could really be extracted was debated at first. Cloudflare set up a deliberately vulnerable nginx server and challenged the public to steal its key. On 11 April the first valid submission arrived from a software engineer who had sent at least 2.5 million requests during the day; a second participant succeeded with around 100,000. Key theft was practical.

Real damage was reported too. The Canada Revenue Agency said about 900 social insurance numbers were removed from its systems during a six-hour window, before it shut its online services to patch.

A timeline diagram: the bug is committed on 31 December 2011, ships in OpenSSL 1.0.1 on 14 March 2012, stays unnoticed for just over two years, is found on 3 April 2014 and fixed in 1.0.1g on 7 April 2014, followed by a clean-up list of patching, replacing keys and certificates, invalidating sessions and changing passwords.
Two years exposed, four days from discovery to fix, and a clean-up in a strict order

What changed afterwards

  • Funding for shared infrastructure. The Linux Foundation's Core Infrastructure Initiative, backed by large technology companies, was created to fund under-resourced open source projects that everyone depends on. Its first grants went to OpenSSL, OpenSSH and the Network Time Protocol, and it paid for an independent security audit of the OpenSSL code.
  • Forks with a narrower scope. In June 2014 Google announced BoringSSL, its own fork, explaining that it had been carrying more than 70 patches on top of OpenSSL across its products. The OpenBSD project started LibreSSL and removed large amounts of old code.
  • A long tail. Years later, internet scans were still finding devices running vulnerable versions. In May 2022 the US agency CISA added CVE-2014-0160 to its catalogue of vulnerabilities known to be exploited. Fixing the library took a day. Getting every copy of it replaced never fully finished.

The computer science underneath

Where TLS sits. TLS wraps an ordinary TCP connection in encryption and authentication, as covered in HTTPS and TLS, demystified. Heartbleed did not break any of that mathematics. It went around it: the process that performs the encryption necessarily holds the plaintext and the keys in memory, and the bug read them from there.

One process, one address space. Everything a server process handles lives in the same virtual address space: request buffers, decrypted form data from other users, session tokens, the private key. The lesson on the memory layout of a process shows how those regions are arranged. Memory allocators reuse freed blocks, so the bytes sitting next to one user's request are often the leftovers of another user's.

Bounds are the programmer's job in C. A C array is a block of memory and a starting address. The language does not store its size and does not check an index or a copy length against it, a point made in arrays and memory. The famous version of this mistake is the write overflow described in buffer overflows, DEP, ASLR and stack canaries. Heartbleed is its read-only sibling, and the standard defences against overflows did not apply: nothing was written, so a canary had nothing to detect, and no injected code ran, so DEP had nothing to block.

Why the private key is the worst thing to lose. A certificate binds a public key to a domain name, and the matching private key is the only thing that proves a server is the real one. PKI, certificates and chains of trust explains the chain. If the private key leaks, patching is not enough: the certificate has to be revoked and replaced, because whoever holds a copy of the old key can keep impersonating the site.

What an interviewer could ask from this

What was the root cause of Heartbleed in one sentence? The server copied as many bytes as a length field in the request claimed, without checking that claim against the number of bytes that had actually been received.

Is it a buffer overflow? Not in the usual sense. It is a buffer over-read: an out-of-bounds read, not a write. No memory was corrupted, which is why there was no crash and no log entry.

Was TLS itself broken? No. The protocol and the specification of the heartbeat extension were sound, and RFC 6520 says an oversized length must be discarded. One implementation skipped the check.

Why did patching not end the incident? The bug may already have leaked private keys and passwords, and there was no way to tell. Operators had to replace keys and certificates, expire sessions and then reset passwords, in that order.

How would you prevent this class of bug? Validate every length and offset from the network against what you measured yourself before using it. Prefer memory-safe languages or bounds-checked buffer types for parsers. Fuzz protocol handlers with malformed input, and keep optional features out of the default build if few people need them.

Takeaways

  • A length field in a message is a claim made by the sender. Compare it with what you actually received before you allocate, copy or index with it.
  • Out-of-bounds reads are quiet. They do not crash and do not show in logs, so only careful review, testing and fuzzing find them.
  • Encryption protects data in transit, not in the memory of the process doing the encrypting. A memory disclosure bug walks around the cryptography.
  • After a possible key leak the order of recovery matters: patch, replace keys and certificates, expire sessions, then change passwords.
  • Software that everyone depends on still needs someone paid to maintain and audit it.

Sources

  1. The Heartbleed Bug (heartbleed.com, Codenomicon)
  2. OpenSSL Security Advisory, 07 Apr 2014: TLS heartbeat read overrun (CVE-2014-0160)
  3. CVE-2014-0160 record (CVE Program)
  4. RFC 6520: TLS and DTLS Heartbeat Extension
  5. The Register: Anatomy of OpenSSL's Heartbleed
  6. Netcraft: Half a million widely trusted websites vulnerable to Heartbleed bug
  7. Cloudflare: The Results of the CloudFlare Challenge
  8. The Register: Heartbleed exploit steals 900 Canadian tax IDs
  9. Linux Foundation: Core Infrastructure Initiative announces new backers and first projects to receive support
  10. ImperialViolet: BoringSSL (20 June 2014)
  11. Wikipedia: Heartbleed

Written by the Codevizag Academy team

An independent explainer built from the public sources listed above. Codevizag Academy is not affiliated with OpenSSL. Found a mistake? Write to support@codevizag.com.

More case studies

Understood it? Now prove it.

The lessons behind this case study are free, and 20 problems a month are judged on real test cases at no cost.

Start solving free