networking · advanced · ~15 min

Parse the 5-byte TLS record header

Read a tiny but real wire-protocol header.

Challenge

A TLS record begins with:

byte 0: content_type   (20=ChangeCipherSpec, 21=Alert, 22=Handshake, 23=ApplicationData)
byte 1: legacy_version_major   (0x03)
byte 2: legacy_version_minor   (0x01 = TLS 1.0, 0x02 = 1.1, 0x03 = 1.2, 0x04 = 1.3)
byte 3..4: length (big-endian, <= 0x4000 for typical TLS)

Implement int parse_tls_record_header(const unsigned char *buf, int len, int *out_type, int *out_minor, int *out_length).

Return 1 on success (and 5 bytes available, length within reasonable limits), 0 otherwise.

Why this matters

Every TLS connection starts with a 5-byte record header. Knowing the layout demystifies the protocol; you can parse a capture without writing crypto.

Input format

Bytes + length + 3 outputs.

Output format

0/1 + populated outputs.

Constraints

Bound-check + refuse implausible length.

Starter code

#include <stddef.h>
int parse_tls_record_header(const unsigned char *buf, int len, int *out_type, int *out_minor, int *out_length) { /* TODO */ (void)buf; (void)len; (void)out_type; (void)out_minor; (void)out_length; return 0; }

Common mistakes

Reading length in little-endian. Accepting length > 0x4000.

Edge cases to handle

Length exactly 0x4000. Type outside the known set (allowed but uncommon).

Complexity

O(1).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.