Skip to content

Validate Length Before Payload

The Course
•
40 min study

The length field in a header is a number chosen by whoever produced the bytes. If that producer is buggy or hostile, the number can be anything from 0 to 65535. A decoder that copies "length" bytes into a fixed buffer without checking has handed control of its memory to the input. This exact shape, a declared length trusted without a bound check, has caused some of the most serious security bugs in widely deployed C code: a peer claims a large payload, the program copies or echoes that many bytes, and memory that was never part of the message leaks out or gets overwritten.

The decoder's internal buffer holds 22 bytes: five header octets, at most sixteen payload octets, and one checksum. The five-byte header arrives first, so the decoder can read the declared length and reject it before a single payload byte is stored. That ordering is the defense.

Predict and run

Read the program before pressing Run. Write down the three numbers and give a different reason for each.

Predict before running C
#include <stdio.h>

int valid_length(unsigned long length) { return length <= 16 && length == 4; }

int main(void) {
    printf("%d %d %d\n", valid_length(4),valid_length(3),valid_length(17));
    return 0;
}
Check your prediction
Text
1 0 0

Length 4 passes both tests. Length 3 fits in the buffer, so it is perfectly memory-safe, but it is the wrong shape for a reading payload, which needs exactly two octets of sensor and two of value. Length 17 is wrong for a reading too, but it fails for a more serious reason first: storing it would write past the 16-byte payload area. Same result, two different contracts.

Memory safety and protocol validity are separate checks

It is tempting to delete length <= 16, since length == 4 already implies it. The project keeps both on purpose. The limit is a property of the buffer: no frame of any type may exceed it, because the storage is fixed at compile time. The exact length is a property of the type: a reading is four octets. When a future version adds a type whose payload is 8 octets, you will change the per-type rule, and the buffer limit must still hold. Keeping the two rules separate means that edit cannot accidentally remove the memory-safety check.

Here is what the missing check looks like in a buffering decoder:

C
unsigned char frame[22];
unsigned long length = ((unsigned long)frame[3] << 8) | frame[4];
memcpy(frame + 5, input, length);          /* length 65535 writes far past frame */

With length taken straight from the input, a declared 65535 writes 65535 bytes into a 17-byte region after the header. AddressSanitizer reports a stack-buffer-overflow on the first such run. Without it, the program overwrites whatever lives next to frame, which may be the return address. Bounds must be checked against the storage, not against what the input says about itself.

Check every metadata field, and report why

The header also carries a magic byte, a version and a type. Each one needs its own check, and a good validator reports which check failed. That turns "invalid frame" into a message you can debug, and lets tests assert that the right rule fired rather than any rule:

Classify a header C
#include <stdio.h>

typedef enum { HEADER_OK, BAD_MAGIC, BAD_VERSION, BAD_TYPE, OVER_LIMIT, WRONG_LENGTH } HeaderCheck;

static HeaderCheck check_header(const unsigned char h[5]) {
    unsigned long length = ((unsigned long)h[3] << 8) | h[4];
    if (h[0] != 0x54) { return BAD_MAGIC; }
    if (h[1] != 1) { return BAD_VERSION; }
    if (h[2] != 1) { return BAD_TYPE; }
    if (length > 16) { return OVER_LIMIT; }
    if (length != 4) { return WRONG_LENGTH; }
    return HEADER_OK;
}

int main(void) {
    static const char *names[] = {"ok", "bad magic", "bad version", "bad type", "over limit", "wrong length"};
    const unsigned char headers[3][5] = {{0x54, 1, 1, 0, 4}, {0x54, 1, 1, 0xFF, 0xFF}, {0x54, 1, 1, 0, 0}};
    for (size_t i = 0; i < 3; ++i) {
        printf("length %u %u: %s\n", (unsigned)headers[i][3], (unsigned)headers[i][4],
               names[check_header(headers[i])]);
    }
    return 0;
}
Text
length 0 4: ok
length 255 255: over limit
length 0 0: wrong length

The declared 65535 never gets near the buffer. A length of 0 is safe to store, since nothing is stored, but a reading cannot be empty.

After a bad header, stop

What should a decoder do with the bytes that follow a rejected header? The project's answer is: nothing. It enters a terminal error state until the caller resets it. The alternative, treating the next byte as a possible new header, sounds friendly but is dangerous. Payload bytes are arbitrary data, so a value byte that happens to be 0x54 would be read as magic, and a crafted payload could smuggle a complete fake frame inside a rejected one. Resynchronizing safely requires a protocol designed for it, with escape bytes or unambiguous delimiters. This one is not, so the decoder refuses to guess. Day 5 covers the reset that ends the error state.

Practice

Exercise

Your turn

Version 2 of the format adds a heartbeat frame: type 2, with an empty payload. Version 1 decoders must keep rejecting it, and readings keep their 4-octet payload in both versions. Write HeaderCheck check_header_v2(const unsigned char h[5]) with these rules, checked in this order:

  • magic must be 0x54;
  • version must be 1 or 2;
  • the type must exist in that version: type 1 in both, type 2 only in version 2 (anything else is a bad type);
  • the declared length must not exceed the 16-octet limit;
  • the length must be exactly the payload size of that type.

Run it on the seven headers in the starter and print:

Text
54 01 01 00 04: ok
54 02 02 00 00: ok
54 01 02 00 00: bad type
54 02 02 00 04: wrong length
54 03 01 00 04: bad version
54 02 03 00 00: bad type
54 02 02 FF FF: over limit
Your workspace C
#include <stdio.h>

typedef enum { HEADER_OK, BAD_MAGIC, BAD_VERSION, BAD_TYPE, OVER_LIMIT, WRONG_LENGTH } HeaderCheck;

/* Write check_header_v2 here. */

int main(void) {
    static const char *names[] = {"ok", "bad magic", "bad version", "bad type", "over limit", "wrong length"};
    const unsigned char headers[7][5] = {
        {0x54, 1, 1, 0, 4}, {0x54, 2, 2, 0, 0}, {0x54, 1, 2, 0, 0}, {0x54, 2, 2, 0, 4},
        {0x54, 3, 1, 0, 4}, {0x54, 2, 3, 0, 0}, {0x54, 2, 2, 0xFF, 0xFF},
    };
    /* Print one line per header: its five octets, then the result name. */
    (void)names; (void)headers;
    return 0;
}
Hint 1: the idea

The exact length is no longer one constant: it depends on the type. Decide the expected length at the same moment you accept the type, and keep the over-limit check separate, so a huge declared length is still reported as over the limit whatever the type.

Hint 2: a first step

Start from the rules of check_header above with only the version check widened to accept 1 or 2, and run. Lines 2, 4 and 7 are wrong: all three say bad type, because a type-2 header is refused before its length is ever looked at. Line 3 is right, but only by accident; once you accept type 2, it is the line that checks you accept it in version 2 only.

Show one solution
Run the solution C
#include <stdio.h>

typedef enum { HEADER_OK, BAD_MAGIC, BAD_VERSION, BAD_TYPE, OVER_LIMIT, WRONG_LENGTH } HeaderCheck;

/* Version 1: type 1 (reading, 4 octets). Version 2 adds type 2 (heartbeat, 0 octets).
   Checks magic, version, type for that version, the 16-octet limit, then the exact length. */
HeaderCheck check_header_v2(const unsigned char h[5]) {
    unsigned long length = ((unsigned long)h[3] << 8) | h[4];
    if (h[0] != 0x54) { return BAD_MAGIC; }
    if (h[1] != 1 && h[1] != 2) { return BAD_VERSION; }
    unsigned long expected;
    if (h[2] == 1) {
        expected = 4;
    } else if (h[2] == 2 && h[1] == 2) {
        expected = 0;
    } else {
        return BAD_TYPE;
    }
    if (length > 16) { return OVER_LIMIT; }
    if (length != expected) { return WRONG_LENGTH; }
    return HEADER_OK;
}

int main(void) {
    static const char *names[] = {"ok", "bad magic", "bad version", "bad type", "over limit", "wrong length"};
    const unsigned char headers[7][5] = {
        {0x54, 1, 1, 0, 4}, {0x54, 2, 2, 0, 0}, {0x54, 1, 2, 0, 0}, {0x54, 2, 2, 0, 4},
        {0x54, 3, 1, 0, 4}, {0x54, 2, 3, 0, 0}, {0x54, 2, 2, 0xFF, 0xFF},
    };
    for (size_t i = 0; i < 7; ++i) {
        for (size_t j = 0; j < 5; ++j) { printf("%02X%s", (unsigned)headers[i][j], j == 4 ? "" : " "); }
        printf(": %s\n", names[check_header_v2(headers[i])]);
    }
    return 0;
}
Text
54 01 01 00 04: ok
54 02 02 00 00: ok
54 01 02 00 00: bad type
54 02 02 00 04: wrong length
54 03 01 00 04: bad version
54 02 03 00 00: bad type
54 02 02 FF FF: over limit

Each bad header still differs from a good one in one field, so each line tests one rule, but the rules now interact: 54 01 02 and 54 02 02 differ only in the version, and one is a bad type while the other is valid. Choosing expected together with the type keeps the per-type table in one place; a third type would add one branch. The over-limit check stays before the exact-length check, so FF FF is reported as the attack it looks like rather than as an ordinary wrong length. The project decoder only implements version 1, and Extend and Download on Day 7 comes back to what adding the heartbeat would take. Next, the checksum guards the payload before anything is published.

Was this article helpful?

Your response is saved on this device.