A C++ sensor logger validates network input with len <= buf.size() - offset, where offset and len are int; why do hostile packets pass, and how do you fix it?
answer
- the int is not the type that wins
- size_t subtraction cannot go negative
- wraps modulo 2^64
- check sign before converting
- std::cmp_less and std::ssize
basics
~20 sbuf.size() returns std::size_t, so the int offset converts to unsigned and the subtraction wraps: an offset past the end or a negative one makes buf.size() - offset exceed the buffer, so bad lengths pass. Reject negatives first, then compare in one signedness.
solid answer
~50 s`buf.size()` is a `std::size_t`, whose rank is at least `int`'s, so the usual arithmetic conversions turn `offset` into `std::size_t`. With 8 readings and `offset == 10`, `8 - 10` wraps to 2^64 - 2; with `offset == -100`, the offset first becomes 2^64 - 100 and the difference wraps to 108. Either way `len <= ...` is true and the reader walks outside the buffer. Unsigned wrap is well defined, so UBSan's `undefined` group reports nothing; Clang's opt-in `-fsanitize=unsigned-integer-overflow` does flag it. The fix is to validate in a fixed order: reject negative `offset` and `len`, check `offset <= size` before subtracting, then compare `len` against the remaining space. C++20 helps: `std::cmp_less_equal` and friends compare mixed signedness by value, `std::in_range<T>(v)` checks a value fits before converting, and `std::ssize` gives a signed size when differences are needed.
code
cpp · 24 lines#include <cstddef>
#include <cstdint>
#include <cstdio>
#include <utility>
#include <vector>
// offset and len arrive from the network as int
bool fits_buggy(const std::vector<std::uint16_t>& buf, int offset, int len) {
return len <= buf.size() - offset; // every operand becomes size_t
}
bool fits_fixed(const std::vector<std::uint16_t>& buf, int offset, int len) {
if (offset < 0 || len < 0) return false;
if (std::cmp_greater(offset, buf.size())) return false;
return std::cmp_less_equal(len, buf.size() - static_cast<std::size_t>(offset));
}
int main() {
std::vector<std::uint16_t> buf(8);
std::printf("offset=10, len=4: buggy %d fixed %d\n", fits_buggy(buf, 10, 4), fits_fixed(buf, 10, 4));
std::printf("offset=-100,len=4: buggy %d fixed %d\n", fits_buggy(buf, -100, 4), fits_fixed(buf, -100, 4));
std::printf("offset=6, len=2: buggy %d fixed %d\n", fits_buggy(buf, 6, 2), fits_fixed(buf, 6, 2));
std::printf("offset=6, len=3: buggy %d fixed %d\n", fits_buggy(buf, 6, 3), fits_fixed(buf, 6, 3));
}go deeper
Remember that subtracting from a size() result can never go negative; it wraps to a huge number instead.
Trace the conversions in the check operand by operand and show which inputs pass that should not.
Rewrite the validation so no step can wrap, name the warnings and the sanitizer that would have caught it, and find sibling bugs like unsigned reverse loops.
Set the rule for untrusted integers: convert once at the boundary after validation, which warnings are errors, and where sanitizers run.
## Why the check is wrong The expression `len <= buf.size() - offset` contains two binary operators, and each applies the **usual arithmetic conversions** to its operands: 1. `buf.size() - offset`: `size()` returns `std::size_t` (`unsigned long` on 64-bit Linux and macOS). Its rank is at least `int`'s, so `offset` converts to `std::size_t`. A negative `offset` becomes 2^64 plus that value. 2. The subtraction is unsigned, so it is computed **modulo 2^64** and can never be negative. 3. `len <= ...`: `len` converts to `std::size_t` too. With an 8-element buffer: | `offset` | `len` | `buf.size() - offset` | Check result | |---|---|---|---| | 6 | 2 | 2 | passes, correctly | | 6 | 3 | 2 | fails, correctly | | 10 | 4 | 2^64 - 2 | **passes**: offset is past the end | | -100 | 4 | 108 | **passes**: offset is negative | | 4 | -2 | 4 | fails, by luck: `len` became huge | The last row shows why such code survives testing: some hostile inputs are rejected by accident, which hides the ones that are not. ## Why tools stay quiet - The check itself contains no undefined behaviour (the out-of-bounds read that follows it does). Unsigned arithmetic is defined to wrap, so `-fsanitize=undefined` has nothing to report. - Clang offers `-fsanitize=unsigned-integer-overflow`, deliberately outside the `undefined` group because wrapping is legal; it reports "unsigned integer overflow: 8 - 10 cannot be represented in type 'size_type' (aka 'unsigned long')". Expect noise from hash functions and other code that wraps on purpose. - `-Wsign-compare` flags the comparison (`-Wall` for C++ in GCC, `-Wextra` in Clang), and `-Wsign-conversion` flags the conversion of `offset`. Teams that build with neither never see a diagnostic. ## A correct check Validate in an order where no step can wrap: 1. Reject `offset < 0` and `len < 0` while they are still signed. 2. Reject `offset > buf.size()`; after this, `buf.size() - offset` cannot wrap. 3. Accept only `len <= buf.size() - offset`. C++20 gives library help in `<utility>`: `std::cmp_less`, `std::cmp_less_equal`, `std::cmp_greater` and the rest compare two integers of any signedness by mathematical value, so `std::cmp_greater(offset, buf.size())` is right even for a negative `offset`. `std::in_range<std::size_t>(offset)` asks whether a value fits a type before you convert it. These functions accept only signed and unsigned integer types, not `char` or `bool`. ## Other places the same wrap hides - `for (std::size_t i = v.size() - 1; i >= 0; --i)` never ends, because an unsigned `i >= 0` is always true, and on an empty vector `i` starts at the maximum value. GCC's `-Wtype-limits` (in `-Wextra`) warns; Clang 21 needed an explicit `-Wtautological-unsigned-zero-compare`. - `if (v.size() - 1 > idx)` on an empty container. - `end - begin` computed as `std::size_t` when `end < begin`. C++20's `std::ssize(c)` returns the size as a signed type (`std::ptrdiff_t` or wider), which makes `std::ssize(v) - 1` equal -1 for an empty vector and lets reverse loops use a signed index. ## Testing the boundary A validation function like this deserves table-driven tests at the edges, because the interesting inputs are exactly the ones a happy-path test never sends: - `offset` equal to the size with `len == 0` (valid, empty read) and with `len == 1` (invalid); - `offset` one past the size, and `offset` far past it; - `offset` and `len` negative, including `INT_MIN`; - `len` equal to the remaining space, and one more than it; - an empty buffer with `offset == 0`. Because the packet comes from the network, a fuzzer that drives the parser with arbitrary `offset` and `len` values finds this class of bug quickly, especially combined with AddressSanitizer, which reports many of the resulting out-of-bounds reads instead of letting them return stale data. ## Reviewing for this bug - Treat every subtraction involving a `size()` result as suspect unless the code has already proven the minuend is larger. - Convert untrusted signed input at one boundary, after validation, and keep the rest of the code in one signedness. - Turn `-Wsign-compare` into an error and consider `-Wsign-conversion` for parsing code that handles untrusted input.
- Why does -fsanitize=undefined not catch this wrap, and what does?Unsigned arithmetic is defined to wrap modulo 2^N, so it is not undefined behaviour and the `undefined` group ignores it. Clang provides `-fsanitize=unsigned-integer-overflow` as an opt-in check outside that group; it reports the wrapping subtraction at run time, but it also fires on intentional wraps such as hash mixing, so it is usually enabled for parsing code rather than globally.
- Would changing offset and len to std::size_t in the signature fix the bug?It moves the bug. A negative value from the network converts to a huge `std::size_t` at the call site, and `buf.size() - offset` still wraps when `offset` exceeds the size. The check must still compare `offset` with the size before subtracting; unsigned parameters only remove the chance to reject negatives explicitly.
- the subtraction cannot overflow because size_t is 64 bits wide
- UBSan would have reported this wrap
- a negative offset makes the comparison fail, so negatives are safe
- casting buf.size() to int is always a safe fix
- unsigned parameters prevent negative input from the network
Assumes C++20 or later for std::cmp_less, std::cmp_less_equal, std::cmp_greater, std::in_range and std::ssize; the conversion rules themselves apply to every standard.