Answer#
Many protocols send "this many bytes follow". A hostile sender can announce four billion bytes and send five, or send nothing. Rust prevents the memory-corruption version of this mistake, but your parser can still panic on a bad slice, or allocate gigabytes because the sender said so.
The parser below does four things in order: it needs the four header bytes, converts the length without truncation, refuses lengths above a limit before doing anything with them, and uses get so that a short buffer is an error.
#[derive(Debug, PartialEq)]
enum FrameError {
Truncated,
TooLarge,
}
const MAX_FRAME: usize = 1 << 20; // 1 MiB
/// A frame is a 4-byte big-endian length, then that many bytes. The length comes from the sender.
fn parse_frame(data: &[u8]) -> Result<&[u8], FrameError> {
let header: [u8; 4] = data.get(..4).ok_or(FrameError::Truncated)?.try_into().unwrap();
let len = usize::try_from(u32::from_be_bytes(header)).map_err(|_| FrameError::TooLarge)?;
if len > MAX_FRAME {
return Err(FrameError::TooLarge); // refuse before allocating or slicing anything
}
let end = 4usize.checked_add(len).ok_or(FrameError::TooLarge)?;
data.get(4..end).ok_or(FrameError::Truncated)
}
fn main() {
println!("{:?}", parse_frame(&[0, 0, 0, 3, b'a', b'b', b'c', b'!']));
println!("{:?}", parse_frame(&[0, 0, 0, 9, b'a']));
println!("{:?}", parse_frame(&[0xFF, 0xFF, 0xFF, 0xFF, 1, 2]));
println!("{:?}", parse_frame(&[0, 0]));
}Ok([97, 98, 99])
Err(Truncated)
Err(TooLarge)
Err(Truncated)The four calls show a good frame, a frame that claims 9 bytes but holds 1, a length of about four billion that is refused as too large, and a buffer too short to contain a header.
How to do it#
- Define a maximum size per message type and enforce it before allocating.
- Use
u32::from_be_bytes(orfrom_le_bytes, as the protocol says) on a fixed-size array; get the array withtry_intofrom a slice you obtained withget. - Use
checked_addorchecked_mulfor offsets and sizes. - Return a typed error; the caller decides whether to close the connection.
- Keep reading incrementally (a streaming parser) when messages may be large, with a limit on the total.
Common mistakes#
Vec::with_capacity(len)withlenfrom the packet. This is the allocation attack.data[4..4 + len], which panics on short data and can overflow in the addition.- Casting with
as usizeon a 32-bit target after checking on a 64-bit machine;try_fromkeeps the check honest.
Related questions#
How do I test a parser like this?#
With normal unit tests for the known cases, and then with fuzzing and random inputs. See the thread on fuzzing basics.
What about text-based formats?#
The same rules hold: limit the total size, the number of items and the nesting depth before you allocate based on any count in the text.
Sources#
- Standard library,
slice::get: https://doc.rust-lang.org/std/primitive.slice.html#method.get - Standard library,
u32::from_be_bytes: https://doc.rust-lang.org/std/primitive.u32.html#method.from_be_bytes - CWE-770, "Allocation of Resources Without Limits or Throttling": https://cwe.mitre.org/data/definitions/770.html