use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use pnet_base::MacAddr;
use crate::protocols::ethernet::Frame;
use crate::protocols::text::field as text;
pub const GROUP_ADDRESS: MacAddr = MacAddr(0x01, 0x00, 0x0C, 0xCC, 0xCC, 0xCC);
const LLC_SNAP: [u8; 3] = [0xAA, 0xAA, 0x03];
const SNAP_HEADER: [u8; 5] = [0x00, 0x00, 0x0C, 0x20, 0x00];
const CDP_HDR_LEN: usize = 4;
const RECORD_HDR_LEN: usize = 4;
const MAX_RECORDS: usize = 128;
const RECORD_DEVICE_ID: u16 = 0x0001;
const RECORD_ADDRESSES: u16 = 0x0002;
const RECORD_PORT_ID: u16 = 0x0003;
const RECORD_CAPABILITIES: u16 = 0x0004;
const RECORD_SOFTWARE_VERSION: u16 = 0x0005;
const RECORD_PLATFORM: u16 = 0x0006;
const RECORD_NATIVE_VLAN: u16 = 0x000A;
const RECORD_DUPLEX: u16 = 0x000B;
const RECORD_MANAGEMENT_ADDRESSES: u16 = 0x0016;
const PROTOCOL_TYPE_NLPID: u8 = 1;
const NLPID_IPV4: u8 = 0xCC;
const PROTOCOL_TYPE_IEEE_802_2: u8 = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Capabilities(u32);
impl Capabilities {
const ROUTER: u32 = 0x01;
const TRANSPARENT_BRIDGE: u32 = 0x02;
const SOURCE_ROUTE_BRIDGE: u32 = 0x04;
const SWITCH: u32 = 0x08;
const HOST: u32 = 0x10;
const IGMP: u32 = 0x20;
const REPEATER: u32 = 0x40;
pub fn is_router(self) -> bool {
self.0 & Self::ROUTER != 0
}
pub fn is_switch(self) -> bool {
self.0 & (Self::SWITCH | Self::TRANSPARENT_BRIDGE | Self::SOURCE_ROUTE_BRIDGE) != 0
}
pub fn is_host(self) -> bool {
self.0 & Self::HOST != 0
}
pub fn is_repeater(self) -> bool {
self.0 & Self::REPEATER != 0
}
pub fn is_igmp_capable(self) -> bool {
self.0 & Self::IGMP != 0
}
pub fn bits(self) -> u32 {
self.0
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Announcement<'a> {
pub device_id: Option<&'a str>,
pub port_id: Option<&'a str>,
pub capabilities: Option<Capabilities>,
pub software_version: Option<&'a str>,
pub platform: Option<&'a str>,
pub native_vlan: Option<u16>,
pub full_duplex: Option<bool>,
pub address: Option<IpAddr>,
}
pub fn parse<'a>(frame: &Frame<'a>) -> Option<Announcement<'a>> {
let payload = frame.payload_as_claimed()?;
let (llc, rest) = payload.split_at_checked(LLC_SNAP.len())?;
if llc != LLC_SNAP {
return None;
}
let (snap, rest) = rest.split_at_checked(SNAP_HEADER.len())?;
if snap != SNAP_HEADER {
return None;
}
let mut rest = rest.get(CDP_HDR_LEN..)?;
let mut announcement = Announcement::default();
let mut seen = 0usize;
while seen < MAX_RECORDS {
let Some((kind, value, remainder)) = next_record(rest) else {
break;
};
rest = remainder;
seen += 1;
match kind {
RECORD_DEVICE_ID => keep_first(&mut announcement.device_id, text(value)),
RECORD_PORT_ID => keep_first(&mut announcement.port_id, text(value)),
RECORD_SOFTWARE_VERSION => keep_first(&mut announcement.software_version, text(value)),
RECORD_PLATFORM => keep_first(&mut announcement.platform, text(value)),
RECORD_CAPABILITIES => keep_first(
&mut announcement.capabilities,
value
.first_chunk::<4>()
.map(|bytes| Capabilities(u32::from_be_bytes(*bytes))),
),
RECORD_NATIVE_VLAN => keep_first(
&mut announcement.native_vlan,
value
.first_chunk::<2>()
.map(|bytes| u16::from_be_bytes(*bytes)),
),
RECORD_DUPLEX => keep_first(
&mut announcement.full_duplex,
value.first().map(|byte| *byte != 0),
),
RECORD_ADDRESSES | RECORD_MANAGEMENT_ADDRESSES => {
keep_first(&mut announcement.address, first_address(value));
}
_ => {}
}
}
let read_something = announcement.device_id.is_some()
|| announcement.port_id.is_some()
|| announcement.capabilities.is_some();
read_something.then_some(announcement)
}
fn keep_first<T>(field: &mut Option<T>, value: Option<T>) {
if field.is_none() {
*field = value;
}
}
fn next_record(bytes: &[u8]) -> Option<(u16, &[u8], &[u8])> {
let header = bytes.first_chunk::<4>()?;
let kind = u16::from_be_bytes([header[0], header[1]]);
let length = usize::from(u16::from_be_bytes([header[2], header[3]]));
if length < RECORD_HDR_LEN {
return None;
}
let value = bytes.get(RECORD_HDR_LEN..length)?;
let remainder = bytes.get(length..)?;
Some((kind, value, remainder))
}
fn first_address(value: &[u8]) -> Option<IpAddr> {
let rest = value.get(4..)?;
let (protocol_type, rest) = rest.split_first()?;
let (protocol_length, rest) = rest.split_first()?;
let (protocol, rest) = rest.split_at_checked(usize::from(*protocol_length))?;
let address_length = usize::from(u16::from_be_bytes(*rest.first_chunk::<2>()?));
let address = rest.get(2..2 + address_length)?;
match (*protocol_type, protocol) {
(PROTOCOL_TYPE_NLPID, [NLPID_IPV4]) => address
.first_chunk::<4>()
.map(|bytes| IpAddr::V4(Ipv4Addr::from(*bytes))),
(PROTOCOL_TYPE_IEEE_802_2, _) if address_length == 16 => address
.first_chunk::<16>()
.map(|bytes| IpAddr::V6(Ipv6Addr::from(*bytes))),
_ => None,
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::protocols::ethernet;
pub(crate) const SWITCH_MAC: MacAddr = MacAddr(0x00, 0x1B, 0x2C, 0x3D, 0x4E, 0x5F);
fn record(kind: u16, value: &[u8]) -> Vec<u8> {
let length = u16::try_from(RECORD_HDR_LEN + value.len()).expect("a record length");
let mut bytes = kind.to_be_bytes().to_vec();
bytes.extend_from_slice(&length.to_be_bytes());
bytes.extend_from_slice(value);
bytes
}
fn frame_of(records: &[Vec<u8>]) -> Vec<u8> {
let mut payload = Vec::new();
payload.extend_from_slice(&LLC_SNAP);
payload.extend_from_slice(&SNAP_HEADER);
payload.extend_from_slice(&[0x02, 0xB4, 0x00, 0x00]);
for record in records {
payload.extend_from_slice(record);
}
let mut bytes = Vec::new();
bytes.extend_from_slice(&[
GROUP_ADDRESS.0,
GROUP_ADDRESS.1,
GROUP_ADDRESS.2,
GROUP_ADDRESS.3,
GROUP_ADDRESS.4,
GROUP_ADDRESS.5,
]);
bytes.extend_from_slice(&[
SWITCH_MAC.0,
SWITCH_MAC.1,
SWITCH_MAC.2,
SWITCH_MAC.3,
SWITCH_MAC.4,
SWITCH_MAC.5,
]);
bytes.extend_from_slice(
&u16::try_from(payload.len())
.expect("a length")
.to_be_bytes(),
);
bytes.extend_from_slice(&payload);
bytes.resize(bytes.len().max(60), 0);
bytes
}
fn ipv4_address_record(address: Ipv4Addr) -> Vec<u8> {
let mut value = 1u32.to_be_bytes().to_vec();
value.push(PROTOCOL_TYPE_NLPID);
value.push(1);
value.push(NLPID_IPV4);
value.extend_from_slice(&4u16.to_be_bytes());
value.extend_from_slice(&address.octets());
record(RECORD_ADDRESSES, &value)
}
#[test]
fn a_second_unreadable_record_does_not_erase_the_first() {
let bytes = frame_of(&[
record(RECORD_DEVICE_ID, b"core-switch-01"),
record(RECORD_DEVICE_ID, &[0xFF, 0xFE, 0xFD]),
record(RECORD_PORT_ID, b"GigabitEthernet1/0/14"),
]);
let frame = ethernet::parse(&bytes).expect("a frame");
let announcement = parse(&frame).expect("an announcement");
assert_eq!(announcement.device_id, Some("core-switch-01"));
assert_eq!(announcement.port_id, Some("GigabitEthernet1/0/14"));
}
pub(crate) fn switch_announcement() -> Vec<u8> {
frame_of(&[
record(RECORD_DEVICE_ID, b"core-sw-02"),
record(RECORD_PORT_ID, b"GigabitEthernet1/0/14"),
record(
RECORD_CAPABILITIES,
&(Capabilities::SWITCH | Capabilities::ROUTER).to_be_bytes(),
),
record(RECORD_NATIVE_VLAN, &40u16.to_be_bytes()),
ipv4_address_record(Ipv4Addr::new(10, 0, 0, 2)),
])
}
#[test]
fn a_switch_announcement_is_read_field_by_field() {
let bytes = frame_of(&[
record(RECORD_DEVICE_ID, b"core-sw-02.example.net"),
record(RECORD_PORT_ID, b"GigabitEthernet1/0/14"),
record(
RECORD_CAPABILITIES,
&(Capabilities::SWITCH | Capabilities::IGMP).to_be_bytes(),
),
record(RECORD_SOFTWARE_VERSION, b"Cisco IOS Software, Version 15.2"),
record(RECORD_PLATFORM, b"cisco WS-C2960X-48TS-L"),
record(RECORD_NATIVE_VLAN, &40u16.to_be_bytes()),
record(RECORD_DUPLEX, &[1]),
ipv4_address_record(Ipv4Addr::new(10, 0, 0, 2)),
]);
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
let announcement = parse(&frame).expect("a CDP announcement");
assert_eq!(announcement.device_id, Some("core-sw-02.example.net"));
assert_eq!(announcement.port_id, Some("GigabitEthernet1/0/14"));
assert_eq!(
announcement.software_version,
Some("Cisco IOS Software, Version 15.2")
);
assert_eq!(announcement.platform, Some("cisco WS-C2960X-48TS-L"));
assert_eq!(announcement.native_vlan, Some(40));
assert_eq!(announcement.full_duplex, Some(true));
assert_eq!(
announcement.address,
Some(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 2)))
);
let capabilities = announcement.capabilities.expect("capabilities");
assert!(capabilities.is_switch());
assert!(capabilities.is_igmp_capable());
assert!(!capabilities.is_router());
assert!(!capabilities.is_host());
}
#[test]
fn the_frame_is_identified_by_its_snap_header_rather_than_an_ethertype() {
let bytes = frame_of(&[record(RECORD_DEVICE_ID, b"sw-01")]);
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
assert!(
frame.payload_length().is_some(),
"the field is a length, not an EtherType"
);
assert!(
frame.ethertype().0 <= 1500,
"and so it names no protocol: {:#06x}",
frame.ethertype().0
);
assert_eq!(
parse(&frame).expect("an announcement").device_id,
Some("sw-01")
);
}
#[test]
fn trailing_padding_is_cut_off_rather_than_walked() {
let bytes = frame_of(&[record(RECORD_DEVICE_ID, b"sw")]);
assert_eq!(bytes.len(), 60, "the fixture is padded, as a real frame is");
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
let announcement = parse(&frame).expect("it returns rather than hanging");
assert_eq!(announcement.device_id, Some("sw"));
assert_eq!(announcement.port_id, None, "the padding invented nothing");
}
#[test]
fn a_record_length_counts_its_own_header() {
let bytes = frame_of(&[
record(RECORD_DEVICE_ID, b"sw-01"),
record(RECORD_PORT_ID, b"Gi1/0/1"),
record(RECORD_NATIVE_VLAN, &99u16.to_be_bytes()),
]);
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
let announcement = parse(&frame).expect("an announcement");
assert_eq!(announcement.device_id, Some("sw-01"));
assert_eq!(
announcement.port_id,
Some("Gi1/0/1"),
"the second record was found where the first said it would be"
);
assert_eq!(announcement.native_vlan, Some(99), "and so was the third");
}
#[test]
fn a_record_shorter_than_its_own_header_stops_the_walk() {
let mut bytes = frame_of(&[record(RECORD_DEVICE_ID, b"sw-01")]);
let insert_at = bytes.len() - 20;
bytes.splice(
insert_at..insert_at,
[0x00, 0x03, 0x00, 0x00].into_iter().chain([0u8; 8]),
);
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
let announcement = parse(&frame).expect("it returns rather than hanging");
assert_eq!(announcement.device_id, Some("sw-01"));
}
#[test]
fn a_frame_of_another_protocol_is_declined() {
let bytes = ethernet::build_header(
SWITCH_MAC,
GROUP_ADDRESS,
pnet_packet::ethernet::EtherTypes::Ipv4,
);
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
assert_eq!(parse(&frame), None);
}
#[test]
fn another_snap_protocol_is_declined() {
let mut bytes = frame_of(&[record(RECORD_DEVICE_ID, b"sw-01")]);
let snap_protocol_at = 14 + LLC_SNAP.len() + 3;
bytes[snap_protocol_at] = 0x01;
bytes[snap_protocol_at + 1] = 0x11;
let frame = ethernet::parse(&bytes).expect("an Ethernet frame");
assert_eq!(parse(&frame), None);
}
}