Review: a length from the packet is trusted
A message decoder copies as many bytes as the packet says, into a fixed-size buffer. An easy embedded C problem (Code review for embedded C), run and graded…
easy · Code review for embedded C · find-the-bug · code-review · buffer-overflow · security
Review comment. "len comes straight from the received packet and is used as the memcpy size. A packet that claims more than PAYLOAD_MAX bytes writes past out->data. Please reject it."
Packets are [type][len][payload...]. The decoder already checks that the packet is long enough for the length it claims. Fix it by changing one line, so that a payload longer than PAYLOAD_MAX is rejected too.
Starter code
bool msg_decode(const uint8_t *pkt, size_t pkt_len, msg_t *out) {
if (pkt_len < 2) return false;
uint8_t len = pkt[1];
if ((size_t)len + 2 > pkt_len) return false;
out->len = len;
memcpy(out->data, &pkt[2], len);
return true;
}Example tests
A normal message, then one that claims 40 bytes
uint8_t ok[] = { 0x01, 3, 0xAA, 0xBB, 0xCC };
show(ok, sizeof ok);
uint8_t big[42] = { 0x01, 40 };
show(big, sizeof big);Expected output:
3 bytes: AA BB CC
rejectedLearn it first
- Code review for embedded C · What to look for in firmware changes, how to comment, and what to leave to tools.
More Code review for embedded C problems
- Review: an error path keeps the bus lock · After one failed sensor read, every later read on the shared bus deadlocks.
- Review: sizeof on an array parameter · A function meant to clear a receive buffer only clears its first few bytes.
- Review: a timeout that breaks after 49 days · A deadline check adds to a 32-bit millisecond tick, which wraps.
- Review: the ring buffer grew to 100 bytes · A change resized a ring buffer, but its index wrap still uses a bit mask.
- Review: blocks got bigger than the loop counter · A checksum loop uses a uint8_t index, and the block size was raised past 255.
- Review: the sensor's temperature is read in the wrong byte order · A driver copies a big-endian signed field straight into a little-endian int16_t.
- Review: strncpy does not always terminate · A setter copies a name with strncpy, and a long name leaves the field without a terminator.