Anatomy of OpenSSL's Heartbleed: Just four bytes trigger horror bug

The code behind the C-bomb dropped on the world


Analysis The password-leaking OpenSSL bug dubbed Heartbleed is so bad, switching off the internet for a while sounds like a good plan.

A tiny flaw in the widely used encryption library allows anyone to trivially and secretly dip into vulnerable systems, from your bank's HTTPS server to your private VPN, to steal passwords, login cookies, private crypto-keys and much more.

How, in 2014, is this possible?

A simple script for the exploit engine Metasploit can, in a matter of seconds, extract sensitive in-memory data from systems that rely on OpenSSL 1.0.1 to 1.0.1f for TLS encryption. The bug affects about 500,000, or 17.5 per cent, of trusted HTTPS websites, we're told, as well as client software, email servers, chat services, and anything else using the aforementioned versions of OpenSSL.

A good number of popular web services have now been patched following disclosure of the vulnerability on Monday; you can use this tool to check (use at your own risk, of course), but don't forget to do more than patch your OpenSSL installation if you're affected – change your keys, dump your session cookies and evaluate your at-risk data.

Too long, didn't read: A summary

This serious flaw (CVE-2014-0160) is a missing bounds check before a memcpy() call that uses non-sanitized user input as the length parameter. An attacker can trick OpenSSL into allocating a 64KB buffer, copy more bytes than is necessary into the buffer, send that buffer back, and thus leak the contents of the victim's memory, 64KB at a time. The patch is here, and the blunder is far worse than Apple's gotofail.

The TLS heartbeat

The bug lies in OpenSSL's implementation of the TLS heartbeat extension: it's a keep-alive feature in which one end of the connection sends a payload of arbitrary data to the other end, which sends back an exact copy of that data to prove everything's OK. The heartbeat message, according to the official standard, looks like this, in C:

struct
{
  HeartbeatMessageType type;
  uint16 payload_length;
  opaque payload[HeartbeatMessage.payload_length];
  opaque padding[padding_length]; 
} HeartbeatMessage;

This HeartbeatMessage arrives via an SSL3_RECORD structure, a basic building block of SSL/TLS communications. The key fields in SSL3_RECORD are given below; length is how many bytes are in the received HeartbeatMessage and data is a pointer to that HeartbeatMessage.

struct ssl3_record_st
{
  unsigned int length;    /* How many bytes available */
  [...]
  unsigned char *data;    /* pointer to the record data */
  [...]
} SSL3_RECORD;

So just to be clear, the SSL3 record's data points to the start of the received HeartbeatMessage and length is the number of bytes in the received HeartbeatMessage. Meanwhile, inside the received HeartbeatMessage, payload_length is the number of bytes in the arbitrary payload that has to be sent back.

Whoever sends a HeartbeatMessage controls the payload_length but as we will see, this is never checked against the parent SSL3_RECORD's length field, allowing an attacker to overrun memory.

The diagram below shows how the attack works:

The Register illustration of the attack

Click to enlarge ... note: this does not include the padding bytes

In the above example, an attacker sends a four-byte HeartbeatMessage including a single byte payload, which is correctly acknowledged by the SSL3's length record. But the attacker lies in the payload_length field to claim the payload is 65535 bytes in size. The victim ignores the SSL3 record, and reads 65535 bytes from its own memory, starting from the received HeartbeatMessage payload, and copies it into a suitably sized buffer to send back to the attacker. It thus hoovers up far too many bytes, dangerously leaking information as indicated above in red.

Show me the code

The broken OpenSSL code that processes the incoming HeartbeatMessage looks like this, where p is a pointer to the start of the message:

/* Read type and payload length first */
hbtype = *p++;
n2s(p, payload);
pl = p;

So the message type is popped into the hbtype variable, the pointer is incremented by one byte, and the n2s() macro writes the 16-bit length of the heartbeat payload to the variable payload and increments the pointer by two bytes. Then pl becomes a pointer to the contents of the payload.

Let's say a heartbeat message with a payload_length of 65535, ie: a heartbeat with a 64KB payload, the maximum possible, is received. The code has to send back a copy of the incoming HeartbeatMessage, so it allocates a buffer big enough to hold the 64KB payload plus one byte to store the message type, two bytes to store the payload length, and some padding bytes, as per the above structure.

It constructs the reply HeartbeatMessage structure with the following code, where bp is a pointer to the start of the reply HeartbeatMessage:

/* Enter response type, length and copy payload */
*bp++ = TLS1_HB_RESPONSE;
s2n(payload, bp);
memcpy(bp, pl, payload);

So the code writes the response type to the start of the buffer, increments the buffer pointer, uses the s2n() macro to write the 16-bit payload length to memory and increment the buffer pointer by two bytes, and then it copies payload number of bytes from the received payload into the outgoing payload for the reply.

Remember, payload is controlled by the attacker, and it's quite large at 64KB. If the actual HeartbeatMessage sent by the attacker only has a payload of, say, one byte, and its payload_length is a lie, then the above memcpy() will read beyond the end of the received HeartbeatMessage and start reading from the victim process's memory.

And this memory will contain other juicy information, such as passwords or decrypted messages from other clients. Sending another heartbeat message leaks another 64KB, so rinse and repeat to scour the victim's system for goodies.

In fact, the bug leaks this sort of information, although we understand Yahoo! has since patched its systems:

The fix

The patch in OpenSSL 1.0.1g is essentially a bounds check, using the correct record length in the SSL3 structure (s3->rrec) that described the incoming HeartbeatMessage.

hbtype = *p++;
n2s(p, payload);
if (1 + 2 + payload + 16 > s->s3->rrec.length)
    return 0; /* silently discard per RFC 6520 sec. 4 */
pl = p;

OpenSSL's implementation of TLS heartbeats was committed to the project's source code 61 minutes to midnight on Saturday, 31 December, 2011. What we're experiencing now is the mother of all delayed hangovers. ®

Bootnote

There was some confusion over exactly how many bytes were leaked by Heartbleed, given that the maximum TLS record length is 16KB. However, this situation being the clusterf*ck that it is, OpenSSL will happily spaff 64KB back to you if you ask nicely.


Linus Torvalds issues early Linux Kernel update to fix swapfile SNAFU

‘Subtle and very nasty bug’ meant 5.12 rc1 could trash entire filesystems

Linux overlord Linus Torvalds has rushed out a new release candidate of Linux 5.12 after the first in the new series was found to include a ‘subtle and very nasty bug’ that was so serious he marked rc1 as unsuitable for use.

“We had a very innocuous code cleanup and simplification that raised no red flags at all, but had a subtle and very nasty bug in it: swap files stopped working right. And they stopped working in a particularly bad way: the offset of the start of the swap file was lost,” Torvalds wrote in a March 3rd post to the Linux Kernel Mailing List.

Continue reading

Just when you thought it was safe to enjoy a beer: Beware the downloaded patch applied in haste

Let us tell you a tale of the Mailman's Apprentice

Who, Me? The weekend is over and Monday is here. Celebrate your IT prowess with another there-but-for-the-grace confession from the Who, Me? archives.

Our tale, from a reader the Regomiser has elected to dub "Simon", takes us back to the early part of this century and to an anonymous antipodean institution of learning.

Continue reading

Remember that day in March 2020 when you were asked to get the business working from home – tomorrow, if possible? Here's how that worked out

IT pros from orgs large and small tell The Reg the tech delivered, mostly, but couriers and home Wi-Fi suddenly became your problem

Covid Logfile Brianna Haley was given one day to be ready to roll out Zoom for 13,000 users at over 1,000 sites.

Haley* is a project analyst for a large healthcare provider that, as COVID-19 marched across the world in March 2020, realised imminent lockdowns meant it would soon be unable to consult with patients.

Continue reading

The torture garden of Microsoft Exchange: Grant us the serenity to accept what they cannot EOL

Time to fix those legacy evils, though.... right?

Column It is the monster which corrupts all it touches. It is an energy-sucking vampire that thrives on the pain it promotes. It cannot be killed, but grows afresh as each manifestation outdoes the last in awfulness and horror. It is Microsoft Exchange and its drooling minion, Outlook.

Let us start with the most numerous of its victims, the end users. Chances are, you are one. You may be numbed by lifelong exposure, your pain receptors and critical faculties burned out though years of corrosion. You might be like me, an habitual avoider whose work requirements periodically force its tentacles back in through the orifices.

Continue reading

Delayed, overbudget and broken. Of course Microsoft's finest would be found in NASA's Orion

In Space No One Can Hear You Scream (as Windows crashes again)

BORK!BORK!BORK! Getting astronauts to the Moon or Mars is the least of NASA's problems. Persuading Microsoft Windows not to fall over along the way is apparently a far greater challenge.

Spotted by Register reader Scott during a visit to the otherwise excellent Space Center Houston, there is something all too real lurking within the mock-up of the Orion capsule in which NASA hopes to send its astronauts for jaunts beyond low Earth orbit.

Continue reading

Name True, iCloud access false: Exceptional problem locks online storage account, stumps Apple customer service

You're naming yourself wrong?

An iCloud customer says she spent more than six hours on the phone to Apple after being locked out of the service because her name is apparently incompatible with the application code.

"Actor, author, artist" Rachel True posted on Twitter about an error with the iCloud application, an unhandled exception with "Type error: cannot set value `true` to property `lastName`."

Continue reading

Intel CPU interconnects can be exploited by malware to leak encryption keys and other info, academic study finds

Side-channel ring race 'hard to mitigate with existing defenses'

Chip-busting boffins in America have devised yet another way to filch sensitive data by exploiting Intel's processor design choices.

Doctoral student Riccardo Paccagnella, master's student Licheng Luo, and assistant professor Christopher Fletcher, all from the University of Illinois at Urbana-Champaign, delved into the way CPU ring interconnects work, and found they can be abused for side-channel attacks. The upshot is that one application can infer another application's private memory and snoop on the user's key presses.

Continue reading

NASA shows Mars that humans can drive a remote control space tank at .01 km/h

Perseverance takes first drive around landing spot named in honor of seminal sci-fi author Octavia E. Butler

NASA’s Perseverance rover trekked across Mars for the first time last Thursday, March 4, 2021.

The vehicle went four whole meters forward, turned 150 degrees to the left, then moved another two-and-a-half meters. The entire drive covered a whopping 6.5 m (21.3 feet) across Martian terrain. The journey took about 33 minutes.

Continue reading

Google's ex-boss tells the US it's time to take the gloves off on autonomous weapons

Plus: AI Index 2021 report takeaways, Chocolate Factory banished from top ethics conference, and more

In brief US government should avoid hastily banning AI-powered autonomous weapons and instead step up its efforts in developing such systems to keep up with foreign enemies, according to the National Security Commission on AI.

The independent group headed by ex-Google CEO Eric Schmidt and funded by the Department of Defense has published its final report advising the White House on how best to advance AI and machine learning to stay ahead of its competitors.

Continue reading

Keeping up the PECR: ICO fines two marketing text pests £330k for sending 2.6 million messages

Leads Work Ltd and Valca Vehicle and Life Cover Agency tried to exploit household finance fears in lockdown, says data watchdog

Two businesses that dispatched more than 2.6 million nuisance text messages seeking to exploit lower household incomes during Britain’s first lockdown are nursing a combined financial penalty of £330,000 from the UK’s data watchdog.

The Information Commissioner’s Office (ICO) said it had received 10,000 official moans against West Sussex-based Leads Work Ltd [PDF], which sent more than 2.6 million lead generation texts between 16 May and 26 June 2020.

Continue reading

Biting the hand that feeds IT © 1998–2021