use crate::protocols::craft::{Ethernet, Icmpv4, Icmpv6, Ipv4, Ipv6, Packet};
use crate::protocols::error::Result;
use crate::protocols::ip;
use pnet_base::MacAddr;
use pnet_packet::ethernet::EtherTypes;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
pub const ECHO_PROBE_CODE: u8 = 9;
const ECHO_REPLY_V4: u8 = 0;
const ECHO_REPLY_V6: u8 = 129;
const ALL_NODES_MAC: MacAddr = MacAddr(0x33, 0x33, 0, 0, 0, 1);
const ALL_NODES_V6: Ipv6Addr = Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1);
pub fn build_all_nodes_echo_request_v6(
src_mac: MacAddr,
src_addr: Ipv6Addr,
identifier: u16,
sequence: u16,
) -> Vec<u8> {
echo_frame_v6(
src_mac,
ALL_NODES_MAC,
src_addr,
ALL_NODES_V6,
ip::HOP_LIMIT_ON_LINK,
identifier,
sequence,
)
}
pub fn build_echo_request_v6(
src_mac: MacAddr,
dst_mac: MacAddr,
src_addr: Ipv6Addr,
dst_addr: Ipv6Addr,
hop_limit: u8,
identifier: u16,
sequence: u16,
) -> Vec<u8> {
echo_frame_v6(
src_mac, dst_mac, src_addr, dst_addr, hop_limit, identifier, sequence,
)
}
pub fn build_echo_request_v4(
src_mac: MacAddr,
dst_mac: MacAddr,
src_addr: Ipv4Addr,
dst_addr: Ipv4Addr,
identifier: u16,
sequence: u16,
) -> Vec<u8> {
Packet::new()
.push(Ethernet::new(src_mac, dst_mac).with_ethertype(EtherTypes::Ipv4))
.push(Ipv4::new(src_addr, dst_addr))
.push(Icmpv4::echo_request(identifier, sequence))
.build()
.expect("an echo request fits every length field it is counted by")
}
fn echo_frame_v6(
src_mac: MacAddr,
dst_mac: MacAddr,
src_addr: Ipv6Addr,
dst_addr: Ipv6Addr,
hop_limit: u8,
identifier: u16,
sequence: u16,
) -> Vec<u8> {
Packet::new()
.push(Ethernet::new(src_mac, dst_mac).with_ethertype(EtherTypes::Ipv6))
.push(Ipv6::new(src_addr, dst_addr).with_hop_limit(hop_limit))
.push(Icmpv6::echo_request(identifier, sequence))
.build()
.expect("an echo request fits every length field it is counted by")
}
pub fn build_echo_request_message(
src_addr: IpAddr,
dst_addr: IpAddr,
code: u8,
identifier: u16,
sequence: u16,
payload: &[u8],
) -> Result<Vec<u8>> {
match (src_addr, dst_addr) {
(IpAddr::V4(_), IpAddr::V4(_)) => Ok(Icmpv4::echo_request(identifier, sequence)
.with_payload(payload)
.with_code(code)
.to_bytes()),
(IpAddr::V6(_), IpAddr::V6(_)) => Icmpv6::echo_request(identifier, sequence)
.with_payload(payload)
.with_code(code)
.to_bytes(Some((src_addr, dst_addr))),
(src, dst) => Err(super::error::PacketError::FamilyMismatch { src, dst }),
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EchoReply {
Ours {
sequence: u16,
},
SomebodyElses,
Other {
icmp_type: u8,
},
Truncated,
}
pub fn classify_echo_reply(message: &[u8], identifier: u16, over_ipv6: bool) -> EchoReply {
let Ok((seen_identifier, sequence)) = echo_token(message) else {
return EchoReply::Truncated;
};
let icmp_type = message[0];
let expected = if over_ipv6 {
ECHO_REPLY_V6
} else {
ECHO_REPLY_V4
};
if icmp_type != expected {
return EchoReply::Other { icmp_type };
}
if seen_identifier != identifier {
return EchoReply::SomebodyElses;
}
EchoReply::Ours { sequence }
}
pub fn echo_token(message: &[u8]) -> Result<(u16, u16)> {
let head: &[u8; 8] = message.first_chunk().ok_or_else(|| {
super::error::PacketError::truncated("an ICMP echo message", 8, message.len())
})?;
Ok((
u16::from_be_bytes([head[4], head[5]]),
u16::from_be_bytes([head[6], head[7]]),
))
}
const TIMESTAMP_REPLY_V4: u8 = 14;
const TIMESTAMP_PAYLOAD_LEN: usize = 12;
pub fn build_timestamp_request(identifier: u16, sequence: u16) -> Vec<u8> {
Icmpv4::timestamp_request(identifier, sequence)
.with_payload([0u8; TIMESTAMP_PAYLOAD_LEN])
.to_bytes()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TimestampReply {
pub originate: u32,
pub receive: u32,
pub transmit: u32,
}
const NON_STANDARD: u32 = 0x8000_0000;
const MILLIS_PER_DAY: u32 = 86_400_000;
impl TimestampReply {
pub const fn is_standard(self) -> bool {
self.receive & NON_STANDARD == 0 && self.transmit & NON_STANDARD == 0
}
pub const fn is_a_time_of_day(self) -> bool {
self.is_standard() && self.receive < MILLIS_PER_DAY && self.transmit < MILLIS_PER_DAY
}
pub fn offset_from(self, local_millis: u32) -> Option<i64> {
if !self.is_a_time_of_day() || local_millis >= MILLIS_PER_DAY {
return None;
}
let day = i64::from(MILLIS_PER_DAY);
let difference = i64::from(self.transmit) - i64::from(local_millis);
Some(match difference {
d if d > day / 2 => d - day,
d if d < -day / 2 => d + day,
d => d,
})
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimestampAnswer {
Ours {
sequence: u16,
reply: TimestampReply,
},
SomebodyElses,
Other {
icmp_type: u8,
},
Truncated,
}
pub fn classify_timestamp_reply(message: &[u8], identifier: u16) -> TimestampAnswer {
let Ok((seen_identifier, sequence)) = echo_token(message) else {
return TimestampAnswer::Truncated;
};
if message[0] != TIMESTAMP_REPLY_V4 {
return TimestampAnswer::Other {
icmp_type: message[0],
};
}
if seen_identifier != identifier {
return TimestampAnswer::SomebodyElses;
}
let Some(values) = message.get(8..8 + TIMESTAMP_PAYLOAD_LEN) else {
return TimestampAnswer::Truncated;
};
let word = |at: usize| {
u32::from_be_bytes([values[at], values[at + 1], values[at + 2], values[at + 3]])
};
TimestampAnswer::Ours {
sequence,
reply: TimestampReply {
originate: word(0),
receive: word(4),
transmit: word(8),
},
}
}
pub fn build_echo_request(
src_mac: MacAddr,
dst_mac: MacAddr,
src_addr: IpAddr,
dst_addr: IpAddr,
hop_limit: u8,
identifier: u16,
sequence: u16,
) -> Result<Vec<u8>> {
match (src_addr, dst_addr) {
(IpAddr::V4(src), IpAddr::V4(dst)) => Ok(build_echo_request_v4(
src_mac, dst_mac, src, dst, identifier, sequence,
)),
(IpAddr::V6(src), IpAddr::V6(dst)) => Ok(build_echo_request_v6(
src_mac, dst_mac, src, dst, hop_limit, identifier, sequence,
)),
(src, dst) => Err(super::error::PacketError::FamilyMismatch { src, dst }),
}
}
#[cfg(test)]
mod tests {
use super::*;
use pnet_packet::Packet as _;
use pnet_packet::icmp::{IcmpPacket, IcmpTypes};
use pnet_packet::icmpv6::{Icmpv6Packet, Icmpv6Types};
use pnet_packet::ipv4::Ipv4Packet;
use pnet_packet::ipv6::Ipv6Packet;
const SRC_MAC: MacAddr = MacAddr(0x02, 0, 0, 0, 0, 1);
const DST_MAC: MacAddr = MacAddr(0x02, 0, 0, 0, 0, 2);
const ID: u16 = 0xBEEF;
const SEQ: u16 = 7;
fn v6(s: &str) -> Ipv6Addr {
s.parse().expect("a valid address")
}
#[test]
fn the_all_nodes_request_is_addressed_to_the_whole_segment_and_stays_on_it() {
let frame = build_all_nodes_echo_request_v6(SRC_MAC, v6("fe80::1"), ID, SEQ);
let eth = super::super::ethernet::parse(&frame).expect("a frame");
assert_eq!(eth.destination(), ALL_NODES_MAC);
assert_eq!(eth.ethertype(), EtherTypes::Ipv6);
let ip = Ipv6Packet::new(eth.payload()).expect("an IPv6 header");
assert_eq!(ip.get_destination(), ALL_NODES_V6);
assert_eq!(
ip.get_hop_limit(),
ip::HOP_LIMIT_ON_LINK,
"a router must discard it rather than forward it"
);
let icmp = Icmpv6Packet::new(ip.payload()).expect("an ICMPv6 message");
assert_eq!(icmp.get_icmpv6_type(), Icmpv6Types::EchoRequest);
assert_ne!(icmp.get_checksum(), 0, "checksummed over the pseudo-header");
}
#[test]
fn an_ipv4_echo_request_is_a_complete_pingable_frame() {
let frame = build_echo_request_v4(
SRC_MAC,
DST_MAC,
Ipv4Addr::new(192, 0, 2, 1),
Ipv4Addr::new(192, 0, 2, 9),
ID,
SEQ,
);
let eth = super::super::ethernet::parse(&frame).expect("a frame");
assert_eq!(eth.ethertype(), EtherTypes::Ipv4);
let ip = Ipv4Packet::new(eth.payload()).expect("an IPv4 header");
assert_eq!(
ip.get_next_level_protocol(),
pnet_packet::ip::IpNextHeaderProtocols::Icmp
);
assert_eq!(ip.get_total_length() as usize, eth.payload().len());
assert_ne!(ip.get_checksum(), 0);
let icmp = IcmpPacket::new(ip.payload()).expect("an ICMP message");
assert_eq!(icmp.get_icmp_type(), IcmpTypes::EchoRequest);
assert_ne!(icmp.get_checksum(), 0);
}
#[test]
fn an_echo_carries_back_the_token_that_names_the_request() {
let v4 = build_echo_request_v4(
SRC_MAC,
DST_MAC,
Ipv4Addr::new(192, 0, 2, 1),
Ipv4Addr::new(192, 0, 2, 9),
ID,
SEQ,
);
let v4_message = &v4[crate::protocols::sizes::ETH_HDR_LEN + 20..];
assert_eq!(echo_token(v4_message).expect("a token"), (ID, SEQ));
let v6_frame = build_echo_request_v6(
SRC_MAC,
DST_MAC,
v6("fe80::1"),
v6("fe80::2"),
ip::HOP_LIMIT_ON_LINK,
ID,
SEQ,
);
let v6_message = &v6_frame[crate::protocols::sizes::ETH_HDR_LEN + 40..];
assert_eq!(echo_token(v6_message).expect("a token"), (ID, SEQ));
}
#[test]
fn a_unicast_request_wakes_only_the_host_it_names() {
let frame = build_echo_request_v6(
SRC_MAC,
DST_MAC,
v6("fe80::1"),
v6("fe80::2"),
ip::HOP_LIMIT_ON_LINK,
ID,
SEQ,
);
let eth = super::super::ethernet::parse(&frame).expect("a frame");
assert_eq!(eth.destination(), DST_MAC);
assert_ne!(eth.destination(), ALL_NODES_MAC);
assert_eq!(
Ipv6Packet::new(eth.payload())
.expect("an IPv6 header")
.get_destination(),
v6("fe80::2")
);
}
#[test]
fn the_dispatching_form_builds_what_the_family_specific_ones_do() {
let v4 = build_echo_request(
SRC_MAC,
DST_MAC,
IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
IpAddr::V4(Ipv4Addr::new(192, 0, 2, 9)),
ip::HOP_LIMIT_ROUTED,
ID,
SEQ,
)
.expect("one family");
let direct = build_echo_request_v4(
SRC_MAC,
DST_MAC,
Ipv4Addr::new(192, 0, 2, 1),
Ipv4Addr::new(192, 0, 2, 9),
ID,
SEQ,
);
let read = |frame: &[u8]| {
let eth = super::super::ethernet::parse(frame).expect("a frame");
let ip = Ipv4Packet::new(eth.payload()).expect("a header");
(
eth.destination(),
eth.ethertype(),
ip.get_source(),
ip.get_destination(),
ip.get_ttl(),
ip.get_next_level_protocol(),
ip.payload().to_vec(),
)
};
assert_eq!(read(&v4), read(&direct));
let mismatched = build_echo_request(
SRC_MAC,
DST_MAC,
IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)),
IpAddr::V6(v6("2001:db8::1")),
ip::HOP_LIMIT_ROUTED,
ID,
SEQ,
);
assert!(mismatched.is_err(), "two families cannot make one packet");
}
#[test]
fn the_message_form_carries_no_headers_of_its_own() {
let message = build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::from([192, 0, 2, 9]),
0,
ID,
SEQ,
b"payload",
)
.expect("one family");
let parsed = IcmpPacket::new(&message).expect("an ICMP message");
assert_eq!(parsed.get_icmp_type(), IcmpTypes::EchoRequest);
assert_eq!(echo_token(&message).expect("a token"), (ID, SEQ));
assert_eq!(&message[8..], b"payload");
}
#[test]
fn the_probe_code_is_written_into_the_message() {
let probe = build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::from([192, 0, 2, 9]),
ECHO_PROBE_CODE,
ID,
SEQ,
&[],
)
.expect("one family");
assert_eq!(probe[1], ECHO_PROBE_CODE);
assert_ne!(ECHO_PROBE_CODE, 0, "a zero code asks nothing");
let v6_probe = build_echo_request_message(
IpAddr::V6(v6("2001:db8::1")),
IpAddr::V6(v6("2001:db8::9")),
ECHO_PROBE_CODE,
ID,
SEQ,
&[],
)
.expect("one family");
assert_eq!(v6_probe[1], ECHO_PROBE_CODE);
}
#[test]
fn a_payload_is_carried_verbatim_and_may_be_empty() {
let empty = build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::from([192, 0, 2, 9]),
0,
ID,
SEQ,
&[],
)
.expect("one family");
assert_eq!(empty.len(), 8);
let long = build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::from([192, 0, 2, 9]),
0,
ID,
SEQ,
&[0xA5; 120],
)
.expect("one family");
assert_eq!(&long[8..], &[0xA5; 120]);
}
#[test]
fn each_family_gets_its_own_message_type() {
let v4 = build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::from([192, 0, 2, 9]),
0,
ID,
SEQ,
&[],
)
.expect("one family");
assert_eq!(v4[0], 8);
let v6_message = build_echo_request_message(
IpAddr::V6(v6("2001:db8::1")),
IpAddr::V6(v6("2001:db8::9")),
0,
ID,
SEQ,
&[],
)
.expect("one family");
assert_eq!(
Icmpv6Packet::new(&v6_message)
.expect("an ICMPv6 message")
.get_icmpv6_type(),
Icmpv6Types::EchoRequest
);
}
#[test]
fn an_ipv6_message_is_checksummed_against_its_addresses() {
let message = build_echo_request_message(
IpAddr::V6(v6("2001:db8::1")),
IpAddr::V6(v6("2001:db8::9")),
0,
ID,
SEQ,
&[],
)
.expect("one family");
let checksum = u16::from_be_bytes([message[2], message[3]]);
assert_ne!(checksum, 0);
let elsewhere = build_echo_request_message(
IpAddr::V6(v6("2001:db8::1")),
IpAddr::V6(v6("2001:db8::a")),
0,
ID,
SEQ,
&[],
)
.expect("one family");
assert_ne!(
checksum,
u16::from_be_bytes([elsewhere[2], elsewhere[3]]),
"the checksum did not depend on the destination"
);
}
#[test]
fn a_mixed_pair_of_addresses_is_refused() {
assert!(
build_echo_request_message(
IpAddr::from([192, 0, 2, 1]),
IpAddr::V6(v6("2001:db8::9")),
0,
ID,
SEQ,
&[],
)
.is_err()
);
}
#[test]
fn a_reply_is_ours_only_when_it_carries_our_identifier() {
let ours = Icmpv4::echo_reply(ID, SEQ).to_bytes();
assert_eq!(
classify_echo_reply(&ours, ID, false),
EchoReply::Ours { sequence: SEQ }
);
let theirs = Icmpv4::echo_reply(ID ^ 0xFFFF, SEQ).to_bytes();
assert_eq!(
classify_echo_reply(&theirs, ID, false),
EchoReply::SomebodyElses
);
}
#[test]
fn a_reply_is_read_under_its_own_family_numbering() {
let v4 = Icmpv4::echo_reply(ID, SEQ).to_bytes();
let v6 = Icmpv6::echo_reply(ID, SEQ)
.to_bytes(Some((
IpAddr::V6(v6("2001:db8::1")),
IpAddr::V6(v6("2001:db8::9")),
)))
.expect("one family");
assert_eq!(
classify_echo_reply(&v4, ID, false),
EchoReply::Ours { sequence: SEQ }
);
assert_eq!(
classify_echo_reply(&v6, ID, true),
EchoReply::Ours { sequence: SEQ }
);
assert_eq!(
classify_echo_reply(&v6, ID, false),
EchoReply::Other { icmp_type: 129 },
"an IPv6 reply read as IPv4"
);
assert_eq!(
classify_echo_reply(&v4, ID, true),
EchoReply::Other { icmp_type: 0 },
"an IPv4 reply read as IPv6"
);
}
#[test]
fn an_error_is_reported_as_itself() {
let error = Icmpv4 {
icmp_type: 3,
code: 13,
checksum: super::super::craft::Field::Computed,
rest_of_header: [0; 4],
payload: vec![0; 8],
}
.to_bytes();
assert_eq!(
classify_echo_reply(&error, ID, false),
EchoReply::Other { icmp_type: 3 }
);
}
#[test]
fn a_message_too_short_to_carry_a_token_says_so() {
assert_eq!(
classify_echo_reply(&[0, 0, 0], ID, false),
EchoReply::Truncated
);
assert_eq!(classify_echo_reply(&[], ID, false), EchoReply::Truncated);
}
#[test]
fn a_timestamp_request_is_framed_the_way_rfc_792_asks() {
let message = build_timestamp_request(0xBEEF, 7);
assert_eq!(message[0], 13, "a timestamp request");
assert_eq!(message[1], 0, "code zero");
assert_eq!(echo_token(&message).expect("a token"), (0xBEEF, 7));
assert_eq!(
message.len(),
8 + TIMESTAMP_PAYLOAD_LEN,
"header, identifier and sequence, then three four-byte readings"
);
assert!(
message[8..].iter().all(|byte| *byte == 0),
"this host's own clock does not go on the wire"
);
}
fn timestamp_reply(identifier: u16, sequence: u16, values: [u32; 3]) -> Vec<u8> {
let mut message = vec![14u8, 0, 0, 0];
message.extend_from_slice(&identifier.to_be_bytes());
message.extend_from_slice(&sequence.to_be_bytes());
for value in values {
message.extend_from_slice(&value.to_be_bytes());
}
message
}
#[test]
fn a_timestamp_reply_yields_its_three_readings() {
let message = timestamp_reply(0xBEEF, 7, [0, 1_000, 1_005]);
let TimestampAnswer::Ours { sequence, reply } = classify_timestamp_reply(&message, 0xBEEF)
else {
panic!("the reply answers this scan");
};
assert_eq!(sequence, 7);
assert_eq!(reply.receive, 1_000);
assert_eq!(reply.transmit, 1_005);
assert!(reply.is_standard());
}
#[test]
fn the_offset_is_the_targets_clock_less_ours() {
let ahead = TimestampReply {
originate: 0,
receive: 5_000,
transmit: 5_000,
};
assert_eq!(ahead.offset_from(2_000), Some(3_000));
assert_eq!(ahead.offset_from(9_000), Some(-4_000));
}
#[test]
fn a_reply_across_midnight_is_a_small_offset_and_not_a_days_worth() {
const DAY: u32 = 86_400_000;
let target_past_midnight = TimestampReply {
originate: 0,
receive: 500,
transmit: 500,
};
assert_eq!(
target_past_midnight.offset_from(DAY - 500),
Some(1_000),
"one second ahead, not a day behind"
);
let target_before_midnight = TimestampReply {
originate: 0,
receive: DAY - 500,
transmit: DAY - 500,
};
assert_eq!(
target_before_midnight.offset_from(500),
Some(-1_000),
"one second behind, not a day ahead"
);
}
#[test]
fn a_reading_that_is_not_a_time_of_day_yields_no_offset() {
let absurd = TimestampReply {
originate: 0,
receive: 2_000_000_000,
transmit: 2_000_000_000,
};
assert!(
absurd.is_standard(),
"the high bit is clear, so the RFC's own flag says nothing"
);
assert!(!absurd.is_a_time_of_day());
assert_eq!(absurd.offset_from(2_000), None);
let last = TimestampReply {
originate: 0,
receive: 86_399_999,
transmit: 86_399_999,
};
assert!(last.is_a_time_of_day());
let midnight = TimestampReply {
originate: 0,
receive: 86_400_000,
transmit: 86_400_000,
};
assert!(!midnight.is_a_time_of_day());
assert_eq!(last.offset_from(86_400_000), None);
}
#[test]
fn a_non_standard_clock_yields_no_offset_at_all() {
let non_standard = TimestampReply {
originate: 0,
receive: 0x8000_0000 | 5_000,
transmit: 0x8000_0000 | 5_000,
};
assert!(!non_standard.is_standard());
assert_eq!(non_standard.offset_from(2_000), None);
let half = TimestampReply {
originate: 0,
receive: 5_000,
transmit: 0x8000_0000 | 5_000,
};
assert!(!half.is_standard());
assert_eq!(half.offset_from(2_000), None);
}
#[test]
fn another_scans_timestamp_reply_is_not_ours() {
let message = timestamp_reply(0x1234, 1, [0, 1, 2]);
assert_eq!(
classify_timestamp_reply(&message, 0xBEEF),
TimestampAnswer::SomebodyElses
);
}
#[test]
fn what_is_not_a_timestamp_reply_is_named_by_its_type() {
let echo = vec![0u8, 0, 0, 0, 0xBE, 0xEF, 0, 1];
assert_eq!(
classify_timestamp_reply(&echo, 0xBEEF),
TimestampAnswer::Other { icmp_type: 0 }
);
let unreachable = vec![3u8, 1, 0, 0, 0, 0, 0, 0];
assert_eq!(
classify_timestamp_reply(&unreachable, 0xBEEF),
TimestampAnswer::Other { icmp_type: 3 }
);
}
#[test]
fn a_timestamp_reply_without_its_readings_is_truncated() {
let mut message = timestamp_reply(0xBEEF, 7, [0, 1, 2]);
message.truncate(8 + 4);
assert_eq!(
classify_timestamp_reply(&message, 0xBEEF),
TimestampAnswer::Truncated
);
assert_eq!(
classify_timestamp_reply(&[], 0xBEEF),
TimestampAnswer::Truncated
);
}
proptest::proptest! {
#[test]
fn classifying_a_timestamp_reply_never_panics(
message in proptest::collection::vec(proptest::prelude::any::<u8>(), 0..64)
) {
let _ = classify_timestamp_reply(&message, 0xBEEF);
}
#[test]
fn the_offset_never_panics(
receive in proptest::prelude::any::<u32>(),
transmit in proptest::prelude::any::<u32>(),
local in proptest::prelude::any::<u32>(),
) {
let reply = TimestampReply { originate: 0, receive, transmit };
if let Some(offset) = reply.offset_from(local) {
assert!(offset.abs() <= 86_400_000 / 2, "folded onto the half-day");
}
}
}
}