Length-prefix validation before allocation
ID: length-prefix-validation-before-allocation
Length-prefix validation before allocation checks that an encoded payload length is permitted and safely usable before requesting memory allocation based on it. A fixed-width length field bounds what the encoding can represent; an application can impose a smaller limit. TLS vectors, for example, have explicitly specified minimum and maximum byte lengths.[ref]
The Transport Layer Security Protocol Version 1.3 (RFC 8446). §3.4, variable-length vectors and permitted bounds
For an original decoder model, let be the decoded unsigned payload length, the application limit and the bytes remaining in a complete input buffer after the prefix. Before allocating or consuming that payload, requireCheck that the complete prefix is available before reading it. For a two-byte big-endian prefix
02 01, . With and , the input fails both checks. Prefix 01 2c instead declares bytes and satisfies these two bounds. The example counts only payload bytes in .Arithmetic needs its own bound. If an allocation includes additional bytes and the size type's maximum value is , verify and before forming . Computing the sum first can already cause integer overflow. Similarly, when allocating elements of positive size , check before multiplication.
For a streaming decoder, can mean that more input is needed rather than that the final message is malformed. It still does not justify consuming unavailable bytes or allocating beyond the stated resource limit. Nested fields need bounds relative to their enclosing field. These checks establish safe structural handling of a length-prefixed encoding; they do not authenticate the sender or validate the payload's meaning.
New to topics? Read the docs here!