use std::net::IpAddr;
use pnet_packet::ethernet::EtherTypes;
use crate::protocols::ethernet::Frame;
use crate::model::host::{NetworkRole, StatusProtocol};
use crate::protocols::error::PacketError;
use crate::protocols::{dhcp, ip, ndp};
#[non_exhaustive]
pub enum ProtocolMatch {
Unhandled,
Solicited(Option<IpAddr>),
Unsolicited,
AllNodes {
identifier: u16,
sequence: u16,
},
}
pub struct Reading {
pub matched: ProtocolMatch,
pub declared: Option<NetworkRole>,
}
impl Reading {
fn unhandled() -> Self {
Self {
matched: ProtocolMatch::Unhandled,
declared: None,
}
}
fn matched(matched: ProtocolMatch) -> Self {
Self {
matched,
declared: None,
}
}
fn declaring(matched: ProtocolMatch, role: NetworkRole) -> Self {
Self {
matched,
declared: Some(role),
}
}
}
pub trait DiscoveryProtocol: Send {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError>;
fn status_protocol(&self) -> StatusProtocol;
fn capture_clause(&self) -> &'static str;
}
pub fn sweep_protocols() -> Vec<Box<dyn DiscoveryProtocol>> {
vec![
Box::new(ArpProtocol),
Box::new(NdpProtocol),
Box::new(RouterAdvertProtocol),
Box::new(DhcpProtocol),
Box::new(Icmpv6EchoProtocol),
]
}
pub struct ArpProtocol;
impl DiscoveryProtocol for ArpProtocol {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError> {
if frame.ethertype() != EtherTypes::Arp {
return Ok(Reading::unhandled());
}
Ok(Reading::matched(ProtocolMatch::Solicited(None)))
}
fn status_protocol(&self) -> StatusProtocol {
StatusProtocol::Arp
}
fn capture_clause(&self) -> &'static str {
"arp"
}
}
pub struct NdpProtocol;
impl DiscoveryProtocol for NdpProtocol {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError> {
match ndp::advertisement(frame) {
Some(advert) if is_assignable(advert.target) => {
let matched = ProtocolMatch::Solicited(Some(IpAddr::V6(advert.target)));
Ok(match advert.router {
true => Reading::declaring(matched, NetworkRole::Router),
false => Reading::matched(matched),
})
}
Some(_) | None => Ok(Reading::unhandled()),
}
}
fn status_protocol(&self) -> StatusProtocol {
StatusProtocol::Ndp
}
fn capture_clause(&self) -> &'static str {
"icmp6"
}
}
fn is_assignable(address: std::net::Ipv6Addr) -> bool {
if address.is_unspecified() {
return false;
}
let segments = address.segments();
let link_local = (segments[0] & 0xffc0) == 0xfe80;
let no_interface_id = segments[4..] == [0, 0, 0, 0];
!(link_local && no_interface_id)
}
pub struct RouterAdvertProtocol;
impl DiscoveryProtocol for RouterAdvertProtocol {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError> {
Ok(match ndp::is_router_advertisement(frame) {
true => Reading::declaring(ProtocolMatch::Unsolicited, NetworkRole::Router),
false => Reading::unhandled(),
})
}
fn status_protocol(&self) -> StatusProtocol {
StatusProtocol::Ndp
}
fn capture_clause(&self) -> &'static str {
"icmp6"
}
}
pub struct DhcpProtocol;
impl DiscoveryProtocol for DhcpProtocol {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError> {
let Some(reply) = dhcp::server_reply(frame) else {
return Ok(Reading::unhandled());
};
let named_itself = matches!(
(reply.server, ip::ipv4_source(frame)),
(Some(server), Ok(source)) if server == source
);
Ok(match named_itself {
true => Reading::declaring(ProtocolMatch::Unsolicited, NetworkRole::DhcpServer),
false => Reading::matched(ProtocolMatch::Unsolicited),
})
}
fn status_protocol(&self) -> StatusProtocol {
StatusProtocol::Dhcp
}
fn capture_clause(&self) -> &'static str {
"(udp port 67 or udp port 68)"
}
}
pub struct Icmpv6EchoProtocol;
impl DiscoveryProtocol for Icmpv6EchoProtocol {
fn interpret(&self, frame: &Frame<'_>) -> Result<Reading, PacketError> {
if frame.ethertype() != EtherTypes::Ipv6 {
return Ok(Reading::unhandled());
}
let destination = ip::ipv6_destination(frame)?;
if !destination.is_unicast_link_local() {
return Ok(Reading::unhandled());
}
match ip::icmpv6_echo_token(frame) {
Some((identifier, sequence)) => Ok(Reading::matched(ProtocolMatch::AllNodes {
identifier,
sequence,
})),
None => Ok(Reading::unhandled()),
}
}
fn status_protocol(&self) -> StatusProtocol {
StatusProtocol::IcmpEcho
}
fn capture_clause(&self) -> &'static str {
"icmp6"
}
}
#[cfg(test)]
pub(crate) mod tests {
#[test]
fn an_advertisement_naming_an_address_nothing_can_hold_is_left_alone() {
use std::net::Ipv6Addr;
assert!(!is_assignable(Ipv6Addr::UNSPECIFIED));
assert!(
!is_assignable("fe80::".parse().expect("a valid address")),
"the link-local prefix is not an address in it"
);
assert!(is_assignable("fe80::1".parse().expect("a valid address")));
assert!(is_assignable(
"fe80::a8bb:ccff:fedd:eeff"
.parse()
.expect("a valid address")
));
assert!(is_assignable(
"2001:db8::1".parse().expect("a valid address")
));
}
use super::*;
use crate::protocols::{arp, ethernet, ip as ip_protocol};
use pnet_base::MacAddr;
use pnet_packet::icmpv6::echo_reply::{Icmpv6Codes, MutableEchoReplyPacket};
use pnet_packet::icmpv6::{Icmpv6Types, MutableIcmpv6Packet};
use pnet_packet::ip::{IpNextHeaderProtocol, IpNextHeaderProtocols};
use std::net::{Ipv4Addr, Ipv6Addr};
pub(crate) const LOCAL_MAC: MacAddr = MacAddr(0x02, 0x00, 0x00, 0x00, 0x00, 0x01);
pub(crate) const PEER_MAC: MacAddr = MacAddr(0x02, 0x00, 0x00, 0x00, 0x00, 0x02);
pub(crate) const ICMPV6_ECHO_LEN: usize = 8;
pub(crate) fn arp_reply_frame(sender_ip: Ipv4Addr) -> Vec<u8> {
arp::build_request(PEER_MAC, sender_ip, Ipv4Addr::new(198, 51, 100, 1))
}
pub(crate) fn ipv6_frame(
destination: Ipv6Addr,
protocol: IpNextHeaderProtocol,
body: &[u8],
) -> Vec<u8> {
let source = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let eth_header =
ethernet::build_header(PEER_MAC, LOCAL_MAC, pnet_packet::ethernet::EtherTypes::Ipv6);
let ip_header = ip_protocol::build_ipv6_header(
source,
destination,
body.len() as u16,
protocol,
ip_protocol::HOP_LIMIT_ON_LINK,
);
[eth_header, ip_header, body.to_vec()].concat()
}
pub(crate) fn echo_reply_frame_with(
destination: Ipv6Addr,
identifier: u16,
sequence: u16,
) -> Vec<u8> {
let mut body = vec![0u8; ICMPV6_ECHO_LEN];
{
let mut echo = MutableEchoReplyPacket::new(&mut body).expect("echo reply buffer");
echo.set_icmpv6_type(Icmpv6Types::EchoReply);
echo.set_icmpv6_code(Icmpv6Codes::NoCode);
echo.set_identifier(identifier);
echo.set_sequence_number(sequence);
}
ipv6_frame(destination, IpNextHeaderProtocols::Icmpv6, &body)
}
pub(crate) fn echo_reply_frame(destination: Ipv6Addr) -> Vec<u8> {
echo_reply_frame_with(destination, 0, 0)
}
pub(crate) fn neighbor_solicitation_body() -> Vec<u8> {
let mut body = vec![0u8; MutableIcmpv6Packet::minimum_packet_size() + 20];
{
let mut icmp = MutableIcmpv6Packet::new(&mut body).expect("icmpv6 buffer");
icmp.set_icmpv6_type(Icmpv6Types::NeighborSolicit);
}
body
}
#[test]
fn arp_protocol_ignores_non_arp_frames() {
let frame_bytes = echo_reply_frame(Ipv6Addr::LOCALHOST);
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let result = ArpProtocol.interpret(&frame);
assert!(matches!(result.unwrap().matched, ProtocolMatch::Unhandled));
}
#[test]
fn arp_protocol_claims_arp_frames_as_solicited() {
let frame_bytes = arp_reply_frame(Ipv4Addr::new(192, 0, 2, 50));
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let result = ArpProtocol.interpret(&frame).unwrap();
assert!(matches!(result.matched, ProtocolMatch::Solicited(None)));
}
#[test]
fn icmpv6_protocol_ignores_non_ipv6_frames() {
let frame_bytes = arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2));
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let result = Icmpv6EchoProtocol.interpret(&frame);
assert!(matches!(result.unwrap().matched, ProtocolMatch::Unhandled));
}
#[test]
fn icmpv6_protocol_ignores_traffic_not_addressed_to_a_link_local_unicast() {
let frame_bytes = echo_reply_frame(Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1)); let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let result = Icmpv6EchoProtocol.interpret(&frame);
assert!(matches!(result.unwrap().matched, ProtocolMatch::Unhandled));
}
#[test]
fn icmpv6_protocol_claims_an_echo_reply_for_the_all_nodes_probe() {
let frame_bytes = echo_reply_frame(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1));
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
for _ in 0..2 {
let result = Icmpv6EchoProtocol.interpret(&frame).unwrap();
assert!(matches!(result.matched, ProtocolMatch::AllNodes { .. }));
}
assert_eq!(
Icmpv6EchoProtocol.status_protocol(),
StatusProtocol::IcmpEcho
);
}
#[test]
fn icmpv6_protocol_carries_the_echoed_token_back() {
let frame_bytes =
echo_reply_frame_with(Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1), 0x5ac5, 2);
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let result = Icmpv6EchoProtocol.interpret(&frame).unwrap();
assert!(matches!(
result.matched,
ProtocolMatch::AllNodes {
identifier: 0x5ac5,
sequence: 2
}
));
}
#[test]
fn icmpv6_protocol_ignores_ipv6_traffic_that_is_not_an_echo_reply() {
let link_local = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 1);
for frame_bytes in [
ipv6_frame(link_local, IpNextHeaderProtocols::Tcp, &[0u8; 20]),
ipv6_frame(
link_local,
IpNextHeaderProtocols::Icmpv6,
&neighbor_solicitation_body(),
),
ipv6_frame(link_local, IpNextHeaderProtocols::Icmpv6, &[]),
] {
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
assert!(matches!(
Icmpv6EchoProtocol.interpret(&frame).unwrap().matched,
ProtocolMatch::Unhandled
));
}
}
pub(crate) fn ndp_frame(body: &[u8]) -> Vec<u8> {
let source = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2);
let eth_header =
ethernet::build_header(PEER_MAC, LOCAL_MAC, pnet_packet::ethernet::EtherTypes::Ipv6);
let ip_header = ip_protocol::build_ipv6_header(
source,
Ipv6Addr::new(0xff02, 0, 0, 0, 0, 0, 0, 1),
body.len() as u16,
IpNextHeaderProtocols::Icmpv6,
ip_protocol::HOP_LIMIT_NDP,
);
[eth_header, ip_header, body.to_vec()].concat()
}
pub(crate) fn advertisement_body(target: Ipv6Addr, flags: u8) -> Vec<u8> {
let mut body = vec![0u8; 24];
{
let mut advert = pnet_packet::icmpv6::ndp::MutableNeighborAdvertPacket::new(&mut body)
.expect("advertisement buffer");
advert.set_icmpv6_type(Icmpv6Types::NeighborAdvert);
advert.set_target_addr(target);
advert.set_flags(flags);
}
body
}
#[test]
fn an_advertisement_declares_a_router_only_when_its_sender_said_so() {
let target = Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xAA);
for (flags, declared) in [(0b1000_0000, Some(NetworkRole::Router)), (0, None)] {
let frame_bytes = ndp_frame(&advertisement_body(target, flags));
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let reading = NdpProtocol.interpret(&frame).unwrap();
assert!(matches!(
reading.matched,
ProtocolMatch::Solicited(Some(IpAddr::V6(claimed))) if claimed == target
));
assert_eq!(reading.declared, declared, "flags {flags:#010b}");
}
}
#[test]
fn a_router_advertisement_names_its_sender_a_router() {
let mut body = vec![0u8; 16];
body[0] = Icmpv6Types::RouterAdvert.0;
let frame_bytes = ndp_frame(&body);
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
let reading = RouterAdvertProtocol.interpret(&frame).unwrap();
assert!(matches!(reading.matched, ProtocolMatch::Unsolicited));
assert_eq!(reading.declared, Some(NetworkRole::Router));
assert_eq!(RouterAdvertProtocol.status_protocol(), StatusProtocol::Ndp);
let neighbour = ndp_frame(&advertisement_body(
Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0xAA),
0b1000_0000,
));
let frame = crate::protocols::ethernet::parse(&neighbour).unwrap();
assert!(matches!(
RouterAdvertProtocol.interpret(&frame).unwrap().matched,
ProtocolMatch::Unhandled
));
}
#[test]
fn a_dhcp_answer_names_a_server_only_where_the_server_answered() {
let server = Ipv4Addr::new(192, 0, 2, 1);
let itself = dhcp_reply_frame(server, Some(server));
let frame = crate::protocols::ethernet::parse(&itself).unwrap();
let reading = DhcpProtocol.interpret(&frame).unwrap();
assert!(matches!(reading.matched, ProtocolMatch::Unsolicited));
assert_eq!(reading.declared, Some(NetworkRole::DhcpServer));
let relayed = dhcp_reply_frame(server, Some(Ipv4Addr::new(198, 51, 100, 254)));
let frame = crate::protocols::ethernet::parse(&relayed).unwrap();
let reading = DhcpProtocol.interpret(&frame).unwrap();
assert!(matches!(reading.matched, ProtocolMatch::Unsolicited));
assert_eq!(
reading.declared, None,
"the sender is a relay, not a server"
);
let frame_bytes = arp_reply_frame(Ipv4Addr::new(192, 0, 2, 20));
let frame = crate::protocols::ethernet::parse(&frame_bytes).unwrap();
assert!(matches!(
DhcpProtocol.interpret(&frame).unwrap().matched,
ProtocolMatch::Unhandled
));
}
pub(crate) fn dhcp_reply_frame(server_id: Ipv4Addr, from: Option<Ipv4Addr>) -> Vec<u8> {
const BOOTREPLY: u8 = 2;
const FIXED_LEN: usize = 236;
let mut message = vec![0u8; FIXED_LEN];
message[0] = BOOTREPLY;
message.extend_from_slice(&[99, 130, 83, 99]);
message.extend_from_slice(&[53, 1, 5]); message.push(54);
message.push(4);
message.extend_from_slice(&server_id.octets());
message.push(255);
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(
from.unwrap_or(server_id),
Ipv4Addr::new(192, 0, 2, 50),
))
.push(
crate::protocols::craft::Udp::new(dhcp::SERVER_PORT, dhcp::CLIENT_PORT)
.with_payload(message),
)
.build()
.expect("a test datagram");
[
ethernet::build_header(PEER_MAC, LOCAL_MAC, pnet_packet::ethernet::EtherTypes::Ipv4),
datagram,
]
.concat()
}
pub(crate) fn mdns_frame() -> Vec<u8> {
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(
Ipv4Addr::new(192, 0, 2, 50),
Ipv4Addr::new(224, 0, 0, 251),
))
.push(
crate::protocols::craft::Udp::new(
crate::protocols::mdns::PORT,
crate::protocols::mdns::PORT,
)
.with_payload(vec![0u8; 12]),
)
.build()
.expect("a test datagram");
[
ethernet::build_header(PEER_MAC, LOCAL_MAC, pnet_packet::ethernet::EtherTypes::Ipv4),
datagram,
]
.concat()
}
}