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:
| Byte | 0 | 1–2 | 3–4 |
|---|---|---|---|
| Field | content type | version, big-endian | length of the body, big-endian |
Write tls_record(buf, n, h) for the n bytes received so far:
- Fewer than 5 bytes:
REC_NEED_MORE. - Fill
h, then reject the header withREC_BADif the type is not 20–23 (change_cipher_spec, alert, handshake, application_data), the version is not 0x0301–0x0303, the length is overTLS_MAX_RECORD, or the length is 0 for any type except application_data (23). - A valid header whose body has not fully arrived:
REC_NEED_MORE. - Otherwise
REC_OK: the record isbuf[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: badLearn it first
- TLS for embedded systems · Handshakes, certificates, PSK, DTLS and fitting TLS in RAM.
More TLS for embedded systems problems
- Is the certificate valid? · Check a server certificate's validity period and hostname, including wildcards.
- Verify a certificate chain · Walk a server's certificate chain to a trusted root, checking names, CA flags, path length, dates and signatures.