Skip to content

Commit 41ff7f9

Browse files
test: add tests asserting EchoReplyPacket::from_reply is always none on invalid data
Invalid data including truncated packets, wrong ICMP type, and destination unreachable. Also includes a test asserting a valid echo reply is correctly parsed.
1 parent c0238c2 commit 41ff7f9

1 file changed

Lines changed: 47 additions & 0 deletions

File tree

src/packet.rs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,50 @@ impl<V: IpVersion> EchoReplyPacket<V> {
134134
&self.payload
135135
}
136136
}
137+
138+
#[cfg(test)]
139+
mod tests {
140+
use std::net::Ipv4Addr;
141+
142+
use bytes::Bytes;
143+
144+
use super::EchoReplyPacket;
145+
146+
#[test]
147+
fn from_reply_rejects_truncated_packet() {
148+
// Too short to be a valid ICMP packet (needs at least 8 bytes)
149+
let buf = Bytes::from_static(&[0x00, 0x00]);
150+
let result = EchoReplyPacket::<Ipv4Addr>::from_reply(Ipv4Addr::LOCALHOST, buf);
151+
assert!(result.is_none(), "Should reject truncated packet");
152+
}
153+
154+
#[test]
155+
fn from_reply_rejects_wrong_icmp_type() {
156+
// ICMP Echo Request (type 8) instead of Echo Reply (type 0)
157+
// Format: type(1), code(1), checksum(2), identifier(2), sequence(2)
158+
let buf = Bytes::from_static(&[0x08, 0x00, 0x00, 0x00, 0x12, 0x34, 0x00, 0x01]);
159+
let result = EchoReplyPacket::<Ipv4Addr>::from_reply(Ipv4Addr::LOCALHOST, buf);
160+
assert!(result.is_none(), "Should reject Echo Request (type 8)");
161+
}
162+
163+
#[test]
164+
fn from_reply_rejects_destination_unreachable() {
165+
// ICMP Destination Unreachable (type 3)
166+
let buf = Bytes::from_static(&[0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
167+
let result = EchoReplyPacket::<Ipv4Addr>::from_reply(Ipv4Addr::LOCALHOST, buf);
168+
assert!(result.is_none(), "Should reject Destination Unreachable");
169+
}
170+
171+
#[test]
172+
fn from_reply_accepts_valid_echo_reply() {
173+
// Valid ICMP Echo Reply (type 0)
174+
// Format: type(1), code(1), checksum(2), identifier(2), sequence(2), payload...
175+
let buf = Bytes::from_static(&[
176+
0x00, 0x00, 0x00, 0x00, 0x12, 0x34, 0x00, 0x01, b't', b'e', b's', b't',
177+
]);
178+
let packet = EchoReplyPacket::<Ipv4Addr>::from_reply(Ipv4Addr::LOCALHOST, buf).unwrap();
179+
assert_eq!(packet.identifier(), 0x1234);
180+
assert_eq!(packet.sequence_number(), 0x0001);
181+
assert_eq!(packet.payload(), b"test");
182+
}
183+
}

0 commit comments

Comments
 (0)