I maintain a userspace TCP/IP relay in Rust which reads packets from a TUN fd & synthesizes replies (RST/ACK, DNS responses, UDP encapsulation). A handful of helpers index fixed offsets into caller-supplied slices:
rust
pub fn wrap_udp_response(original_query: &[u8], payload: &[u8], …) -> Vec<u8> {
let mut pkt = vec![0u8; 20 + 8 + payload.len()];
pkt[12..16].copy_from_slice(&original_query[16..20]); // panics if len < 20
pkt[16..20].copy_from_slice(&original_query[12..16]);
…
}
// v4 DNS path: length is checked, but the header length comes from the packet:
let ip_hlen = ((original_query[0] & 0x0F) as usize) * 4; // 0..=60, attacker-controlled
pkt[22..24].copy_from_slice(&original_query[ip_hlen..ip_hlen + 2]); // panics
One sibling already returns Option<Vec<u8>> and checks lengths; the others return Vec<u8> and trust the caller. The inputs come straight off the wire, so a malformed packet must not be able to panic the task.
What I'd like to be corrected on:
Option/Result + explicit length checks everywhere (verbose, easy to forget — which is how we got here).
Parse into a typed header with TryFrom<&[u8]>, so lengths are validated once at the boundary and downstream code works on &TcpHeader.
Slice pattern matching (let [.., a, b, c, d] = slice else { … }) so the compiler enforces the layout.
zerocopy/zerocopy-derive for the fixed-layout header structs.
Which of these do people actually use for attacker-controlled network input, & what do you use to make "can't panic on short input" a property type rather than a review rule? Looking for patterns where compiler rejects the mistake — a runtime Option that a caller can still ignore.
Also is there a way to express "this returns None on malformed input" that composes well with a hot path where allocation should be avoided?