FAQ - Help and questions

How do I parse length-prefixed binary data from the network without trusting the length?

#security#parsing#binarypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Treat the length field as a claim. Read it with from_be_bytes, convert with try_from, compare against a hard maximum before allocating, add with checked_add and take the payload with slice get so a short buffer gives an error instead of a panic. Never allocate a buffer the size the sender asks for.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

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.

src/main.rsrust
#[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]));
}
text
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#

  1. Define a maximum size per message type and enforce it before allocating.
  2. Use u32::from_be_bytes (or from_le_bytes, as the protocol says) on a fixed-size array; get the array with try_into from a slice you obtained with get.
  3. Use checked_add or checked_mul for offsets and sizes.
  4. Return a typed error; the caller decides whether to close the connection.
  5. Keep reading incrementally (a streaming parser) when messages may be large, with a limit on the total.

Common mistakes#

  • Vec::with_capacity(len) with len from 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 usize on a 32-bit target after checking on a 64-bit machine; try_from keeps the check honest.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet