Simvik

Read TLS records from a byte stream

Validate a TLS record header as soon as it arrives, and tell the caller whether to wait for more bytes. A medium embedded C problem (TLS for embedded…

medium · TLS for embedded systems · tls · parsing · streams · robustness

TLS runs over TCP, which delivers a byte stream, not messages. The client reads into a buffer and has to work out where each record ends. Every record starts with a 5-byte header:

Byte01–23–4
Fieldcontent typeversion, big-endianlength of the body, big-endian

Write tls_record(buf, n, h) for the n bytes received so far:

  1. Fewer than 5 bytes: REC_NEED_MORE.
  2. Fill h, then reject the header with REC_BAD if the type is not 20–23 (change_cipher_spec, alert, handshake, application_data), the version is not 0x0301–0x0303, the length is over TLS_MAX_RECORD, or the length is 0 for any type except application_data (23).
  3. A valid header whose body has not fully arrived: REC_NEED_MORE.
  4. Otherwise REC_OK: the record is buf[0 .. 5 + len).

Check the header before waiting for the body, so a corrupt length cannot make the device wait for bytes that never come.

Starter code

int tls_record(const uint8_t *buf, size_t n, rec_hdr_t *h) {
  if (n < TLS_HDR_LEN) return REC_NEED_MORE;
  h->type = buf[0];
  h->version = (uint16_t)(buf[1] << 8 | buf[2]);
  h->len = (uint16_t)(buf[3] << 8 | buf[4]);
  if (n < TLS_HDR_LEN + h->len) return REC_NEED_MORE;
  return REC_OK;
}

Example tests

An alert record arriving a few bytes at a time

uint8_t alert[] = { 21, 0x03, 0x03, 0x00, 0x02, 2, 40 };
feed(alert, 3);
feed(alert, 5);
feed(alert, 7);

Expected output:

3 bytes: need more
5 bytes: need more
7 bytes: ok (type 21, version 0x0303, 2 body bytes)

A header that is not TLS at all

const uint8_t *http = (const uint8_t *)"HTTP/1.1 400 Bad Request";
feed(http, 5);

Expected output:

5 bytes: bad

Learn it first

More TLS for embedded systems problems