use std::collections::{HashMap, HashSet};
use std::net::IpAddr;
use crate::config::OsDetection;
use crate::fingerprint::os;
use crate::model::host::{Host, HostStatus, NetworkRole, StatusProtocol, StatusReason};
use crate::model::ip::scoped::{ScopedIp, Zone};
use crate::model::ip::set::IpSet;
use crate::model::mac::MacAddr;
use crate::model::port::discovery::{Discovery, ScanResponse};
use crate::model::port::{Port, PortState, Protocol};
use crate::model::technique::TcpReply;
use crate::protocols::ethernet::{self, Frame};
use crate::protocols::{cdp, dhcp, lldp, tcp};
use crate::report::ScannerKind;
use crate::report::{Attachment, AttachmentSource};
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::StrategyError;
use crate::scanner::strategy::frames::{self, DiscoveryProtocol, ProtocolMatch};
use crate::transport::capture::{self, CaptureFilter, CaptureOptions, CapturedFrame, FrameStream};
use crate::transport::frame::{self as transport_frame, LinkType};
use crate::transport::mac::IntoCoreMac;
use crate::{info, warn};
use pnet_packet::ethernet::EtherTypes;
const LISTEN_SNAP_LEN: u32 = 512;
const LISTEN_BUFFER_BYTES: u32 = 4 * 1024 * 1024;
const LISTEN_QUEUE_DEPTH: usize = 4096;
const MAX_DECLARING_MACS: usize = 4096;
const MAX_RECORDED_HOSTS: usize = 65_536;
const ABORT_POLL: std::time::Duration = std::time::Duration::from_millis(250);
fn ip_source(packet: &[u8]) -> Option<IpAddr> {
match packet.first()? >> 4 {
4 => Some(IpAddr::V4(
pnet_packet::ipv4::Ipv4Packet::new(packet)?.get_source(),
)),
6 => Some(IpAddr::V6(
pnet_packet::ipv6::Ipv6Packet::new(packet)?.get_source(),
)),
_ => None,
}
}
fn tcp_segment(packet: &[u8]) -> Option<(IpAddr, &[u8])> {
use pnet_packet::ip::IpNextHeaderProtocols;
let (source, header_len, next) = match packet.first()? >> 4 {
4 => {
let ipv4 = pnet_packet::ipv4::Ipv4Packet::new(packet)?;
(
IpAddr::V4(ipv4.get_source()),
usize::from(ipv4.get_header_length()) * 4,
ipv4.get_next_level_protocol(),
)
}
6 => {
let ipv6 = pnet_packet::ipv6::Ipv6Packet::new(packet)?;
(
IpAddr::V6(ipv6.get_source()),
crate::protocols::sizes::IP_V6_HDR_LEN,
ipv6.get_next_header(),
)
}
_ => return None,
};
(next == IpNextHeaderProtocols::Tcp).then(|| Some((source, packet.get(header_len..)?)))?
}
#[derive(Debug, Clone, Default)]
pub struct OnLink {
ranges: IpSet,
}
impl OnLink {
pub fn of_links(links: &[Zone]) -> Self {
let mut ranges = IpSet::new();
for interface in crate::system::interface::interfaces() {
if !links.iter().any(|link| link.name() == interface.name()) {
continue;
}
for held in interface.addresses() {
ranges.insert_range(held.network());
}
}
Self { ranges }
}
pub fn of(ranges: IpSet) -> Self {
Self { ranges }
}
fn contains(&self, address: IpAddr) -> bool {
let confined = match address {
IpAddr::V4(v4) => {
v4.is_unspecified() || v4.is_loopback() || v4.is_link_local() || v4.is_multicast()
}
IpAddr::V6(v6) => {
v6.is_unspecified()
|| v6.is_loopback()
|| v6.is_unicast_link_local()
|| v6.is_multicast()
}
};
confined || self.ranges.contains(&address)
}
fn attaches(&self, address: IpAddr) -> bool {
match address {
IpAddr::V4(v4) => {
if v4.is_unspecified() || v4.is_loopback() || v4.is_multicast() {
return false;
}
v4.is_link_local() || self.ranges.contains(&address)
}
IpAddr::V6(v6) => {
if v6.is_unspecified() || v6.is_loopback() || v6.is_multicast() {
return false;
}
v6.is_unicast_link_local() || self.ranges.contains(&address)
}
}
}
fn is_stated(&self) -> bool {
!self.ranges.is_empty()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Default)]
pub enum Recording {
#[default]
Attached,
Everything,
Only(IpSet),
}
struct Announced<'a> {
source: AttachmentSource,
device_name: Option<&'a str>,
port: Option<&'a str>,
native_vlan: Option<u16>,
management_address: Option<IpAddr>,
roles: Vec<NetworkRole>,
}
impl<'a> Announced<'a> {
fn read(frame: &Frame<'a>) -> Option<Self> {
if let Some(advertisement) = lldp::parse(frame) {
let mut roles = Vec::new();
if let Some(capabilities) = advertisement.capabilities {
if capabilities.is_bridge() {
roles.push(NetworkRole::Switch);
}
if capabilities.is_router() {
roles.push(NetworkRole::Router);
}
}
return Some(Self {
source: AttachmentSource::Lldp,
device_name: advertisement.system_name,
port: match advertisement.port_id {
Some(lldp::Identifier::Text(port)) => Some(port),
_ => None,
},
native_vlan: advertisement.port_vlan,
management_address: advertisement.management_address,
roles,
});
}
let announcement = cdp::parse(frame)?;
let mut roles = Vec::new();
if let Some(capabilities) = announcement.capabilities {
if capabilities.is_switch() {
roles.push(NetworkRole::Switch);
}
if capabilities.is_router() {
roles.push(NetworkRole::Router);
}
}
Some(Self {
source: AttachmentSource::Cdp,
device_name: announcement.device_id,
port: announcement.port_id,
native_vlan: announcement.native_vlan,
management_address: announcement.address,
roles,
})
}
}
#[must_use]
pub struct PassiveListener {
ctx: ScanContext,
frames: FrameStream,
capture: capture::CaptureGuard,
recording: Recording,
on_link: OnLink,
deadline: Option<tokio::time::Instant>,
os: OsDetection,
mac_to_ip: HashMap<MacAddr, ScopedIp>,
declared: HashMap<MacAddr, HashSet<NetworkRole>>,
held: usize,
said_full: bool,
protocols: Vec<Box<dyn DiscoveryProtocol>>,
}
impl PassiveListener {
pub fn open(
links: &[Zone],
recording: Recording,
ctx: ScanContext,
) -> Result<Self, StrategyError> {
let options = Self::capture_options();
let (frames, capture) = capture::frames(links, &options, LISTEN_QUEUE_DEPTH)?;
let on_link = OnLink::of_links(links);
if matches!(recording, Recording::Attached) && !on_link.is_stated() {
warn!(
"no address is configured on {}, so there is nothing to tell this \
link's own machines from the traffic merely crossing it; \
recording everything heard",
links.iter().map(Zone::name).collect::<Vec<_>>().join(", "),
);
}
Ok(Self::over(frames, capture, recording, on_link, ctx))
}
#[cfg(any(test, feature = "test-support"))]
pub fn from_parts(
frames: FrameStream,
on_link: OnLink,
recording: Recording,
ctx: ScanContext,
) -> Self {
Self::over(
frames,
capture::CaptureGuard::noop(),
recording,
on_link,
ctx,
)
}
fn over(
frames: FrameStream,
capture: capture::CaptureGuard,
recording: Recording,
on_link: OnLink,
ctx: ScanContext,
) -> Self {
let mac_to_ip = Self::paired_with_known_hosts(&ctx);
Self {
held: ctx.host_count(),
ctx,
frames,
capture,
recording,
on_link,
os: OsDetection::default(),
deadline: None,
mac_to_ip,
declared: HashMap::new(),
said_full: false,
protocols: frames::sweep_protocols(),
}
}
fn paired_with_known_hosts(ctx: &ScanContext) -> HashMap<MacAddr, ScopedIp> {
let mut pairs = HashMap::new();
let mut keys = ctx.host_addresses();
keys.sort_unstable();
for key in keys {
let Some(Some(mac)) = ctx.read_host(key.clone(), Host::mac) else {
continue;
};
pairs.entry(mac).or_insert(key);
}
pairs
}
pub fn detecting_os(mut self, level: OsDetection) -> Self {
self.os = level;
self
}
pub fn stopping_after(mut self, span: std::time::Duration) -> Self {
self.deadline = Some(tokio::time::Instant::now() + span);
self
}
fn capture_options() -> CaptureOptions {
CaptureOptions::for_link_traffic(Self::filter())
.with_snaplen(LISTEN_SNAP_LEN)
.with_buffer_bytes(LISTEN_BUFFER_BYTES)
}
fn filter() -> CaptureFilter {
let mut clauses: Vec<&'static str> = frames::sweep_protocols()
.iter()
.map(|protocol| protocol.capture_clause())
.collect();
clauses.extend([
"(ether proto 0x88cc)",
"(ether dst 01:00:0c:cc:cc:cc)",
"(tcp)",
]);
clauses.sort_unstable();
clauses.dedup();
CaptureFilter::any_of(clauses)
}
fn read(&mut self, captured: &CapturedFrame) {
if captured.link != LinkType::Ethernet {
if let Some(packet) = transport_frame::strip_to_ip(captured.link, &captured.bytes)
&& !self.read_endpoint(packet, None, captured)
{
self.read_presence_in(packet, &captured.zone);
}
return;
}
let Ok(frame) = ethernet::parse(&captured.bytes) else {
return;
};
if self.read_announcement(&frame, captured) {
return;
}
self.read_forwarding(&frame);
let carries_ip = matches!(frame.ethertype(), EtherTypes::Ipv4 | EtherTypes::Ipv6);
if carries_ip
&& self.read_endpoint(frame.payload(), Some(frame.source().into_core()), captured)
{
return;
}
self.read_client(&frame, &captured.zone);
self.read_presence(&frame, &captured.zone);
}
fn read_announcement(&mut self, frame: &Frame<'_>, captured: &CapturedFrame) -> bool {
let source = frame.source().into_core();
let Some(announced) = Announced::read(frame) else {
return false;
};
let mut attachment = Attachment::new(
captured.zone.clone(),
announced.source,
captured.observed_at,
)
.with_device_mac(source);
if let Some(name) = announced.device_name {
attachment = attachment.with_device_name(name);
}
if let Some(port) = announced.port {
attachment = attachment.with_port(port);
}
if let Some(vlan) = announced.native_vlan {
attachment = attachment.with_native_vlan(vlan);
}
if let Some(address) = announced.management_address {
attachment = attachment.with_management_address(address);
}
let roles = announced.roles;
info!(
verbosity = 1,
"{} says this machine is on {}{}",
captured.zone,
attachment.device_name().unwrap_or("an unnamed device"),
match attachment.port() {
Some(port) => format!(" port {port}"),
None => String::new(),
},
);
let named_itself = match attachment.management_address() {
Some(address) if self.admits(address) => {
let mut host = Host::new(address);
host.record_mac(source);
for role in roles.iter().copied() {
host.add_network_role(role);
}
self.record(host, &captured.zone);
true
}
_ => false,
};
if !named_itself {
for role in roles {
self.note_declaration(source, role);
}
}
self.ctx.record_attachment(attachment);
true
}
fn read_endpoint(
&mut self,
packet: &[u8],
source_mac: Option<MacAddr>,
captured: &CapturedFrame,
) -> bool {
let Some((source, segment)) = tcp_segment(packet) else {
return false;
};
let Ok(parsed) = tcp::parse(segment) else {
return false;
};
if !self.admits(source) {
return true;
}
let mut host = Host::new(source);
if let Some(mac) = source_mac
&& self.on_link.is_stated()
&& self.on_link.contains(source)
{
host.record_mac(mac);
}
let served = matches!(
tcp::classify_probe_response(&parsed),
Some(TcpReply::SynAck)
);
let detail = if served {
let port = Port::new(parsed.source_port(), Protocol::Tcp, PortState::Open)
.with_discovery(
Discovery::new(ScanResponse::OverheardSynAck).seen_at(captured.observed_at),
);
host.add_port(port);
"syn-ack overheard, so this endpoint served somebody"
} else {
"a segment overheard from this host"
};
host.record_evidence(
HostStatus::Up,
StatusReason::new(StatusProtocol::Tcp, detail),
);
self.record(host, &captured.zone);
self.read_stack(packet, source);
true
}
fn read_forwarding(&mut self, frame: &Frame<'_>) {
if !self.on_link.is_stated() {
return;
}
let Ok(source) = crate::protocols::source_address(frame) else {
return;
};
if self.on_link.contains(source) {
return;
}
self.note_declaration(frame.source().into_core(), NetworkRole::Router);
}
fn note_declaration(&mut self, source_mac: MacAddr, role: NetworkRole) {
if let Some(key) = self.mac_to_ip.get(&source_mac).cloned() {
self.ctx.update_host(key, |host| {
host.add_network_role(role);
});
return;
}
if self.declared.len() >= MAX_DECLARING_MACS && !self.declared.contains_key(&source_mac) {
return;
}
self.declared.entry(source_mac).or_default().insert(role);
}
fn read_stack(&self, packet: &[u8], source: IpAddr) {
if matches!(self.os, OsDetection::Off) {
return;
}
let Some(observed) = os::StackObservation::from_ip_packet(packet) else {
return;
};
if !observed.is_syn_ack() && !observed.is_reset() {
return;
}
let Some(verdict) = os::classify(os::RuleDb::global(), &observed.into()) else {
return;
};
self.ctx.update_host(source, |host| {
os::identify(host, [verdict.as_evidence()]);
});
}
fn read_client(&mut self, frame: &Frame<'_>, zone: &Zone) {
let Some(request) = dhcp::client_request(frame) else {
return;
};
let Ok(source) = crate::protocols::source_address(frame) else {
return;
};
if source.is_unspecified() || !self.admits(source) {
return;
}
let mut host = Host::new(source);
if let Some(mac) = request.client_mac {
host.record_mac(mac.into_core());
}
if let Some(name) = request.hostname {
host.set_hostname(Some(name.to_owned()));
}
host.record_evidence(
HostStatus::Up,
StatusReason::new(
StatusProtocol::Dhcp,
"asked for its address and named itself",
),
);
self.record(host, zone);
}
fn read_presence(&mut self, frame: &Frame<'_>, zone: &Zone) {
let Ok(source) = crate::protocols::source_address(frame) else {
return;
};
let mac = frame.source().into_core();
self.credit_presence(source, Some(mac), zone, |protocol| {
protocol.interpret(frame).ok()
});
}
fn read_presence_in(&mut self, packet: &[u8], zone: &Zone) {
let Some(source) = ip_source(packet) else {
return;
};
self.credit_presence(source, None, zone, |protocol| {
Some(protocol.interpret_packet(packet))
});
}
fn credit_presence(
&mut self,
source: IpAddr,
mac: Option<MacAddr>,
zone: &Zone,
interpret: impl Fn(&dyn DiscoveryProtocol) -> Option<frames::Reading>,
) {
if !self.admits(source) {
return;
}
for protocol in &self.protocols {
let Some(reading) = interpret(protocol.as_ref()) else {
continue;
};
if matches!(reading.matched, ProtocolMatch::Unhandled) {
continue;
}
let mut host = Host::new(source);
if let Some(mac) = mac {
host.record_mac(mac);
}
host.record_evidence(
HostStatus::Up,
StatusReason::basic(protocol.status_protocol()),
);
if let Some(role) = reading.declared {
host.add_network_role(role);
}
self.record(host, zone);
return;
}
}
fn admits(&self, address: IpAddr) -> bool {
match &self.recording {
Recording::Attached => !self.on_link.is_stated() || self.on_link.attaches(address),
Recording::Everything => true,
Recording::Only(addresses) => addresses.contains(&address),
}
}
fn store(&mut self, key: ScopedIp, host: Host) {
if self.held >= MAX_RECORDED_HOSTS && !self.ctx.contains_host(&key) {
self.report_full();
return;
}
if self.ctx.write_host(key, |existing| {
existing.merge(host);
true
}) {
self.held += 1;
}
}
fn report_full(&mut self) {
if std::mem::replace(&mut self.said_full, true) {
return;
}
self.ctx.record_failure(
ScannerKind::Passive,
format!(
"this watch is holding the {MAX_RECORDED_HOSTS} machines it will hold, \
so the ones heard from here on are not being recorded; a link \
carrying traffic to anywhere else carries evidence about everywhere \
else, which is what the default recording scope leaves out"
),
);
}
fn record(&mut self, mut host: Host, zone: &Zone) {
host.set_zone(zone.clone());
let Some(mac) = host.mac() else {
let key = host.scoped_ip();
self.store(key, host);
return;
};
for role in self.declared.remove(&mac).into_iter().flatten() {
host.add_network_role(role);
}
let known = self.mac_to_ip.get(&mac).cloned();
let key = known.clone().unwrap_or_else(|| host.scoped_ip());
self.store(key.clone(), host);
if known.is_none() && self.ctx.contains_host(&key) {
self.mac_to_ip.insert(mac, key);
}
}
pub async fn observe(&mut self) -> Result<(), StrategyError> {
let mut stopping = tokio::time::interval(ABORT_POLL);
stopping.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
if self.ctx.handle.should_stop() {
break;
}
if self
.deadline
.is_some_and(|at| tokio::time::Instant::now() >= at)
{
break;
}
tokio::select! {
frame = self.frames.recv() => match frame {
Some(frame) => self.read(&frame),
None => break,
},
_ = stopping.tick() => {}
}
}
if let Some(counts) = self.capture.counts()
&& counts.dropped > 0
{
warn!(
"the capture discarded {} of {} frames it admitted, so what this \
phase did not hear is larger than what it did",
counts.dropped, counts.received,
);
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::scanner::session::ScanSession;
use crate::scanner::strategy::frames::tests::{
PEER_MAC, advertisement_body, arp_reply_frame, dhcp_reply_frame, ndp_frame,
};
use std::net::Ipv4Addr;
use std::time::SystemTime;
fn zone() -> Zone {
Zone::new(7, "sim0")
}
fn captured(bytes: Vec<u8>) -> CapturedFrame {
CapturedFrame {
zone: zone(),
link: LinkType::Ethernet,
bytes,
observed_at: SystemTime::UNIX_EPOCH,
}
}
fn listening(recording: Recording) -> (PassiveListener, ScanContext) {
over(recording, OnLink::default())
}
fn listening_on_a_known_link(recording: Recording) -> (PassiveListener, ScanContext) {
let mut ranges = IpSet::new();
ranges.insert_range("198.51.100.0/24".parse().expect("a valid range"));
over(recording, OnLink::of(ranges))
}
fn over(recording: Recording, on_link: OnLink) -> (PassiveListener, ScanContext) {
let (_session, ctx) = ScanSession::new();
let (_tx, rx) = tokio::sync::mpsc::channel(16);
(
PassiveListener::over(
rx,
capture::CaptureGuard::noop(),
recording,
on_link,
ctx.clone(),
),
ctx,
)
}
#[test]
fn the_listen_filter_admits_every_frame_a_listener_can_read() {
let ethernet = pcap::Capture::dead(pcap::Linktype::ETHERNET).expect("a dead capture");
let (filter, left_out) = PassiveListener::filter()
.for_link(ðernet)
.unwrap_or_else(|e| panic!("the listen filter does not compile: {e}"));
assert_eq!(
left_out,
Vec::<String>::new(),
"Ethernet expresses every clause"
);
let program = ethernet
.compile(&filter, true)
.unwrap_or_else(|e| panic!("the listen filter `{filter}` does not compile: {e}"));
let lldp = crate::protocols::ethernet::build_header(
PEER_MAC,
pnet_base::MacAddr(0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E),
lldp::ETHERTYPE,
);
let readable: [(&str, Vec<u8>); 5] = [
(
"an ARP frame",
arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2)),
),
(
"a neighbour advertisement",
ndp_frame(&advertisement_body(
std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2),
0,
)),
),
(
"a DHCP server reply",
dhcp_reply_frame(Ipv4Addr::new(192, 0, 2, 1), None),
),
("an LLDP advertisement", lldp),
(
"a TCP segment, which is how an endpoint is seen serving somebody",
{
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(
Ipv4Addr::new(198, 51, 100, 5),
Ipv4Addr::new(198, 51, 100, 9),
))
.push(crate::protocols::craft::Tcp::new(443, 51234))
.build()
.expect("a test segment");
[
crate::protocols::ethernet::build_header(
PEER_MAC,
PEER_MAC,
pnet_packet::ethernet::EtherTypes::Ipv4,
),
datagram,
]
.concat()
},
),
];
for (what, frame) in readable {
assert!(
program.filter(&frame),
"the listen filter rejects {what}, so a listener would never see \
one: {filter}"
);
}
}
const LINKS_WITHOUT_ETHERNET: [(i32, &str); 5] = [
(113, "a cooked Linux link"),
(12, "a raw IP link"),
(0, "a BSD loopback or utun"),
(108, "an OpenBSD loopback"),
(9, "a PPP link"),
];
#[test]
fn a_listener_compiles_what_a_link_without_ethernet_can_express() {
for (dlt, what) in LINKS_WITHOUT_ETHERNET {
let link = pcap::Capture::dead(pcap::Linktype(dlt)).expect("a dead capture");
let (filter, left_out) = PassiveListener::filter()
.for_link(&link)
.unwrap_or_else(|e| panic!("a listener refused {what}: {e}"));
link.compile(&filter, true)
.unwrap_or_else(|e| panic!("`{filter}` does not compile for {what}: {e}"));
assert!(filter.contains("(tcp)"), "{what} keeps TCP: {filter}");
assert!(
!filter.contains("ether dst"),
"{what} names no hardware address: {filter}"
);
assert!(
left_out.iter().any(|clause| clause.contains("ether dst")),
"{what} leaves the hardware address out: {left_out:?}"
);
}
}
#[test]
fn a_listener_opens_on_a_loopback_link() {
let Some(loopback) = crate::system::interface::interfaces()
.into_iter()
.find(|link| link.is_loopback())
else {
return;
};
match capture::frames(
std::slice::from_ref(&loopback.zone()),
&PassiveListener::capture_options(),
1,
) {
Ok(_) => {}
Err(refused) if refused.is_denied() => {}
Err(refused) => panic!("a listener refused {}: {refused}", loopback.name()),
}
}
#[test]
fn a_handshake_heard_on_a_tunnel_records_the_endpoint_that_served_it() {
use crate::protocols::tcp::flags;
let server = Ipv4Addr::new(198, 51, 100, 5);
let client = Ipv4Addr::new(198, 51, 100, 9);
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(server, client))
.push(crate::protocols::craft::Tcp::new(443, 51234).with_flags(flags::SYN | flags::ACK))
.build()
.expect("a test datagram");
let (mut listener, ctx) = listening_on_a_known_link(Recording::Attached);
listener.read(&CapturedFrame {
zone: zone(),
link: LinkType::Raw,
bytes: datagram,
observed_at: SystemTime::UNIX_EPOCH,
});
let host = ctx
.hosts_snapshot()
.into_iter()
.next()
.expect("the server was heard");
assert_eq!(host.primary_ip(), IpAddr::V4(server));
assert_eq!(host.mac(), None, "a tunnel carries no hardware address");
let port = host.ports().next().expect("an endpoint was recorded");
assert_eq!((port.number(), port.state()), (443, PortState::Open));
}
#[test]
fn an_advertisement_heard_on_a_tunnel_records_its_sender() {
let sender = IpAddr::V6(std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2));
let mut router_advert = vec![0u8; 16];
router_advert[0] = pnet_packet::icmpv6::Icmpv6Types::RouterAdvert.0;
let target = std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x99);
for (what, body, role) in [
("a router advertisement", router_advert, true),
(
"a neighbour advertisement",
advertisement_body(target, 0),
false,
),
] {
let packet = ndp_frame(&body).split_off(14);
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&CapturedFrame {
zone: zone(),
link: LinkType::Raw,
bytes: packet,
observed_at: SystemTime::UNIX_EPOCH,
});
let hosts = ctx.hosts_snapshot();
assert_eq!(hosts.len(), 1, "{what}: one sender, one host");
assert_eq!(hosts[0].primary_ip(), sender, "{what}: its sender");
assert_eq!(hosts[0].mac(), None, "{what}: no hardware address");
assert_eq!(
hosts[0].network_roles().contains(&NetworkRole::Router),
role,
"{what}"
);
}
}
#[test]
fn the_listener_filter_admits_its_readers_frames_and_no_lookups() {
let filter = PassiveListener::filter().to_string();
let program = pcap::Capture::dead(pcap::Linktype::ETHERNET)
.expect("a dead capture")
.compile(&filter, true)
.unwrap_or_else(|e| panic!("the listener filter `{filter}` does not compile: {e}"));
let udp = |port: u16| {
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(
Ipv4Addr::new(198, 51, 100, 7),
Ipv4Addr::new(198, 51, 100, 1),
))
.push(crate::protocols::craft::Udp::new(port, port).with_payload(vec![0u8; 12]))
.build()
.expect("a test datagram");
[
ethernet::build_header(PEER_MAC, PEER_MAC, EtherTypes::Ipv4),
datagram,
]
.concat()
};
for (what, frame) in [
(
"an ARP frame",
arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2)),
),
(
"a neighbour advertisement",
ndp_frame(&advertisement_body(
std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2),
0,
)),
),
(
"a DHCP server reply",
dhcp_reply_frame(Ipv4Addr::new(192, 0, 2, 1), None),
),
] {
assert!(program.filter(&frame), "{what} is not admitted: {filter}");
}
for (what, frame) in [("a DNS lookup", udp(53)), ("an mDNS message", udp(5353))] {
assert!(!program.filter(&frame), "{what} is admitted: {filter}");
}
}
#[test]
fn a_frame_credits_its_sender_and_no_address_it_merely_names() {
let (mut listener, ctx) = listening(Recording::Everything);
let target = std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0x99);
listener.read(&captured(ndp_frame(&advertisement_body(target, 0))));
let hosts = ctx.hosts_snapshot();
assert_eq!(hosts.len(), 1, "one frame, one sender, one host");
assert_eq!(
hosts[0].primary_ip(),
IpAddr::V6(std::net::Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 2)),
"the address the frame came from, not the one it named"
);
let (mut listener, ctx) = listening(Recording::Everything);
let relay = Ipv4Addr::new(192, 0, 2, 1);
let elsewhere = Ipv4Addr::new(198, 51, 100, 53);
listener.read(&captured(dhcp_reply_frame(elsewhere, Some(relay))));
let hosts = ctx.hosts_snapshot();
assert_eq!(hosts.len(), 1);
assert_eq!(
hosts[0].primary_ip(),
IpAddr::V4(relay),
"the machine that sent the frame, not the one option 54 named"
);
}
#[test]
fn a_recording_filter_keeps_out_what_the_link_carries_anyway() {
let mut wanted = IpSet::new();
wanted.insert(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 7)));
let (mut listener, ctx) = listening(Recording::Only(wanted));
listener.read(&captured(arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2))));
assert_eq!(
ctx.host_count(),
0,
"the frame was heard, and recording it was declined"
);
listener.read(&captured(arp_reply_frame(Ipv4Addr::new(198, 51, 100, 7))));
assert_eq!(ctx.host_count(), 1, "and the one in scope was kept");
}
fn tcp_frame(from: Ipv4Addr, sport: u16, to: Ipv4Addr, dport: u16, flags: u8) -> Vec<u8> {
tcp_frame_from(PEER_MAC, from, sport, to, dport, flags)
}
fn tcp_frame_from(
mac: pnet_base::MacAddr,
from: Ipv4Addr,
sport: u16,
to: Ipv4Addr,
dport: u16,
flags: u8,
) -> Vec<u8> {
let datagram = crate::protocols::craft::Packet::new()
.push(crate::protocols::craft::Ipv4::new(from, to))
.push(crate::protocols::craft::Tcp::new(sport, dport).with_flags(flags))
.build()
.expect("a test datagram");
[
crate::protocols::ethernet::build_header(
mac,
PEER_MAC,
pnet_packet::ethernet::EtherTypes::Ipv4,
),
datagram,
]
.concat()
}
#[test]
fn only_the_server_half_of_a_handshake_establishes_a_listener() {
use crate::protocols::tcp::flags;
let client = Ipv4Addr::new(198, 51, 100, 9);
let server = Ipv4Addr::new(198, 51, 100, 5);
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(tcp_frame(client, 51234, server, 443, flags::SYN)));
let hosts = ctx.hosts_snapshot();
assert_eq!(
hosts[0].primary_ip(),
IpAddr::V4(client),
"the sender is there, which is all a SYN proves"
);
assert_eq!(
hosts[0].port_count(),
0,
"and it proves nothing about the port it was aimed at"
);
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(tcp_frame(
server,
443,
client,
51234,
flags::SYN | flags::ACK,
)));
let host = ctx.hosts_snapshot().remove(0);
assert_eq!(host.primary_ip(), IpAddr::V4(server));
let port = host.ports().next().expect("an endpoint was recorded");
assert_eq!(port.number(), 443, "the source port, which is the listener");
assert_eq!(port.state(), PortState::Open);
assert_eq!(
port.discovery().map(Discovery::reason),
Some(&ScanResponse::OverheardSynAck),
"and it says the handshake was somebody else's"
);
}
#[test]
fn a_refusal_records_no_port_in_either_direction() {
use crate::protocols::tcp::flags;
let server = Ipv4Addr::new(198, 51, 100, 5);
let client = Ipv4Addr::new(198, 51, 100, 9);
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(tcp_frame(
server,
443,
client,
51234,
flags::RST | flags::ACK,
)));
let host = ctx.hosts_snapshot().remove(0);
assert_eq!(
host.status(),
HostStatus::Up,
"the refusal still proves its sender has a live stack"
);
assert_eq!(
host.port_count(),
0,
"a listener records an open port or no port; it never records a shut one"
);
}
#[test]
fn a_client_renewing_its_lease_names_itself_and_one_discovering_does_not() {
use crate::protocols::dhcp::tests as fixtures;
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(fixtures::renewal_frame(
Ipv4Addr::new(192, 0, 2, 74),
"office-printer-3",
)));
let host = ctx.hosts_snapshot().remove(0);
assert_eq!(host.primary_ip(), IpAddr::V4(Ipv4Addr::new(192, 0, 2, 74)));
assert_eq!(host.hostname(), Some("office-printer-3"));
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(fixtures::discover_frame("office-printer-3")));
assert_eq!(
ctx.host_count(),
0,
"a client with no address yet names no host"
);
}
#[test]
fn a_machine_that_forwards_somebody_elses_packet_is_a_router() {
use crate::protocols::tcp::flags;
const ROUTER_MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
let router = Ipv4Addr::new(198, 51, 100, 1);
let elsewhere = Ipv4Addr::new(93, 184, 216, 34);
let local = Ipv4Addr::new(198, 51, 100, 9);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Everything);
listener.read(&captured(tcp_frame_from(
ROUTER_MAC,
elsewhere,
443,
local,
51234,
flags::SYN | flags::ACK,
)));
assert!(
!ctx.hosts_snapshot()
.iter()
.any(|host| host.network_roles().contains(&NetworkRole::Router)),
"the frame names the sender's hardware address and nobody's router address"
);
listener.read(&captured(tcp_frame_from(
ROUTER_MAC,
router,
22,
local,
51235,
flags::SYN | flags::ACK,
)));
let host = ctx
.hosts_snapshot()
.into_iter()
.find(|host| host.primary_ip() == IpAddr::V4(router))
.expect("the router answered at an address of its own");
assert!(
host.network_roles().contains(&NetworkRole::Router),
"the claim held against its hardware address was applied"
);
}
#[test]
fn an_unknown_link_makes_nobody_a_router() {
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(arp_reply_frame(Ipv4Addr::new(198, 51, 100, 1))));
let host = ctx.hosts_snapshot().remove(0);
assert_eq!(
host.primary_ip(),
IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))
);
assert!(
!host.network_roles().contains(&NetworkRole::Router),
"with no link addressing known, off-link is not a question with an answer"
);
}
#[test]
fn the_default_records_this_links_machines_and_not_what_merely_crosses_it() {
use crate::protocols::tcp::flags;
let local = Ipv4Addr::new(198, 51, 100, 5);
let elsewhere = Ipv4Addr::new(93, 184, 216, 34);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Attached);
listener.read(&captured(tcp_frame(
local,
443,
Ipv4Addr::new(198, 51, 100, 9),
51234,
flags::SYN | flags::ACK,
)));
listener.read(&captured(tcp_frame(
elsewhere,
443,
Ipv4Addr::new(198, 51, 100, 9),
51235,
flags::SYN | flags::ACK,
)));
let recorded: Vec<IpAddr> = ctx
.hosts_snapshot()
.iter()
.map(super::Host::primary_ip)
.collect();
assert_eq!(recorded, vec![IpAddr::V4(local)]);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Everything);
listener.read(&captured(tcp_frame(
elsewhere,
443,
Ipv4Addr::new(198, 51, 100, 9),
51235,
flags::SYN | flags::ACK,
)));
assert_eq!(
ctx.host_count(),
1,
"nothing extra was captured; what changed is what may be recorded"
);
}
#[test]
fn a_link_with_no_addressing_of_its_own_records_what_it_hears() {
let (mut listener, ctx) = listening(Recording::Attached);
listener.read(&captured(arp_reply_frame(Ipv4Addr::new(198, 51, 100, 1))));
assert_eq!(ctx.host_count(), 1);
}
#[test]
fn a_stack_is_read_from_a_reply_that_was_arriving_anyway() {
let frame = || {
let mut bytes = crate::protocols::ethernet::build_header(
PEER_MAC,
PEER_MAC,
pnet_packet::ethernet::EtherTypes::Ipv4,
);
bytes.extend_from_slice(&[
0x45, 0x00, 0x00, 0x3c, 0xbe, 0xef, 0x40, 0x00, 0x40, 0x06, 0x00, 0x00, 0xc6, 0x33,
0x64, 0x05, 0xc6, 0x33, 0x64, 0x09, 0x01, 0xbb, 0xc3, 0x50, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x00, 0x02, 0xa0, 0x12, 0xfa, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x02, 0x04,
0x05, 0xb4, 0x04, 0x02, 0x08, 0x0a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x01, 0x03, 0x03, 0x07,
]);
captured(bytes)
};
let (mut listener, ctx) = listening_on_a_known_link(Recording::Attached);
listener.read(&frame());
let named = ctx.hosts_snapshot().remove(0);
assert_eq!(
named.os().map(|os| os.name().to_owned()),
Some("Linux".to_owned()),
"the segment names the stack behind it"
);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Attached);
listener = listener.detecting_os(OsDetection::Off);
listener.read(&frame());
let host = ctx.hosts_snapshot().remove(0);
assert!(
host.os().is_none(),
"`off` means nothing looked, and a listener disobeying it for free is \
still disobeying it"
);
assert_eq!(
host.status(),
HostStatus::Up,
"and the frame still proves its sender is there"
);
}
#[tokio::test]
async fn a_watch_that_runs_out_of_time_was_not_interrupted() {
let (_session, ctx) = ScanSession::new();
let (_tx, rx) = tokio::sync::mpsc::channel(16);
let mut listener = PassiveListener::over(
rx,
capture::CaptureGuard::noop(),
Recording::Everything,
OnLink::default(),
ctx.clone(),
)
.stopping_after(std::time::Duration::ZERO);
listener.observe().await.expect("the watch runs to its end");
assert!(
!ctx.handle.should_stop(),
"nobody asked it to stop, so nothing may say they did"
);
}
#[test]
fn one_machine_answering_at_several_addresses_is_one_host() {
use crate::protocols::tcp::flags;
const MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
let peer = Ipv4Addr::new(198, 51, 100, 9);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Everything);
let first = Ipv4Addr::new(198, 51, 100, 5);
let second = Ipv4Addr::new(198, 51, 100, 6);
listener.read(&captured(tcp_frame_from(
MAC,
first,
443,
peer,
51234,
flags::SYN | flags::ACK,
)));
listener.read(&captured(tcp_frame_from(
MAC,
second,
22,
peer,
51235,
flags::SYN | flags::ACK,
)));
let hosts = ctx.hosts_snapshot();
assert_eq!(hosts.len(), 1, "one machine, one record: {hosts:#?}");
let host = &hosts[0];
assert!(
host.ips().contains(&IpAddr::V4(first)) && host.ips().contains(&IpAddr::V4(second)),
"both addresses are on it: {:?}",
host.ips()
);
assert_eq!(
host.zone().map(|zone| zone.name().to_owned()),
Some("sim0".to_owned()),
"the link it was heard on, without which a link-local names nothing"
);
assert_eq!(
host.ports().count(),
2,
"and both endpoints landed on it rather than one being stranded"
);
}
#[test]
fn a_listener_never_lowers_a_claim_already_on_the_record() {
let (mut listener, ctx) = listening(Recording::Everything);
let address = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2));
let mut known = Host::new(address);
known.set_status(HostStatus::Up);
known.set_hostname(Some("already-known".to_owned()));
ctx.write_host(known.scoped_ip(), |host| {
host.merge(known);
true
});
listener.read(&captured(arp_reply_frame(Ipv4Addr::new(198, 51, 100, 2))));
let host = ctx
.hosts_snapshot()
.into_iter()
.find(|host| host.primary_ip() == address)
.expect("the host is still there");
assert_eq!(host.status(), HostStatus::Up);
assert_eq!(
host.hostname(),
Some("already-known"),
"a listener added to the record and took nothing off it"
);
}
#[test]
fn a_machine_restored_from_an_earlier_sitting_is_not_recorded_twice() {
use crate::protocols::tcp::flags;
const MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
let peer = Ipv4Addr::new(198, 51, 100, 9);
let first = Ipv4Addr::new(198, 51, 100, 5);
let second = Ipv4Addr::new(198, 51, 100, 6);
let (_session, ctx) = ScanSession::new();
let mut earlier = Host::new(IpAddr::V4(first));
earlier.record_mac(MAC.into_core());
earlier.set_zone(zone());
earlier.record_evidence(
HostStatus::Up,
StatusReason::new(StatusProtocol::Tcp, "heard last night"),
);
ctx.restore_hosts(&[earlier]);
assert_eq!(ctx.host_count(), 1, "the sitting starts with one machine");
let (_tx, rx) = tokio::sync::mpsc::channel(16);
let mut ranges = IpSet::new();
ranges.insert_range("198.51.100.0/24".parse().expect("a valid range"));
let mut listener = PassiveListener::over(
rx,
capture::CaptureGuard::noop(),
Recording::Everything,
OnLink::of(ranges),
ctx.clone(),
);
listener.read(&captured(tcp_frame_from(
MAC,
second,
22,
peer,
51235,
flags::SYN | flags::ACK,
)));
let hosts = ctx.hosts_snapshot();
assert_eq!(
hosts.len(),
1,
"one machine across two sittings, not one per sitting: {hosts:#?}"
);
let host = &hosts[0];
assert!(
host.ips().contains(&IpAddr::V4(first)) && host.ips().contains(&IpAddr::V4(second)),
"tonight's address joined the record rather than opening one: {:?}",
host.ips()
);
}
#[test]
fn seeding_the_pairing_skips_a_restored_host_with_no_hardware_address() {
let (_session, ctx) = ScanSession::new();
let mut off_link = Host::new(IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34)));
off_link.record_evidence(
HostStatus::Up,
StatusReason::new(StatusProtocol::Tcp, "heard through a router"),
);
ctx.restore_hosts(&[off_link]);
assert!(
PassiveListener::paired_with_known_hosts(&ctx).is_empty(),
"a host with no hardware address pairs with nothing"
);
}
#[test]
fn a_machine_that_spoke_from_an_excluded_address_is_still_recorded_at_its_others() {
use crate::model::exclusion::Exclusions;
use crate::protocols::tcp::flags;
const MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
let excluded = Ipv4Addr::new(198, 51, 100, 5);
let ordinary = Ipv4Addr::new(198, 51, 100, 6);
let peer = Ipv4Addr::new(198, 51, 100, 9);
let mut forbidden = IpSet::new();
forbidden.insert(IpAddr::V4(excluded));
let (_session, ctx) = ScanSession::builder()
.excluding(Exclusions::new(forbidden))
.build();
let (_tx, rx) = tokio::sync::mpsc::channel(16);
let mut ranges = IpSet::new();
ranges.insert_range("198.51.100.0/24".parse().expect("a valid range"));
let mut listener = PassiveListener::over(
rx,
capture::CaptureGuard::noop(),
Recording::Everything,
OnLink::of(ranges),
ctx.clone(),
);
listener.read(&captured(tcp_frame_from(
MAC,
excluded,
443,
peer,
51234,
flags::SYN | flags::ACK,
)));
assert_eq!(
ctx.host_count(),
0,
"the excluded address is not recorded, which is the policy working"
);
listener.read(&captured(tcp_frame_from(
MAC,
ordinary,
22,
peer,
51235,
flags::SYN | flags::ACK,
)));
let hosts = ctx.hosts_snapshot();
assert_eq!(
hosts.len(),
1,
"the machine's other address is its own host"
);
assert_eq!(hosts[0].primary_ip(), IpAddr::V4(ordinary));
assert!(
!hosts[0].ips().contains(&IpAddr::V4(excluded)),
"and the excluded address did not ride in on the merge: {:?}",
hosts[0].ips()
);
}
#[test]
fn a_machine_heard_at_an_excluded_address_second_does_not_carry_it_into_the_record() {
use crate::model::exclusion::Exclusions;
use crate::protocols::tcp::flags;
const MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
let excluded = Ipv4Addr::new(198, 51, 100, 5);
let ordinary = Ipv4Addr::new(198, 51, 100, 6);
let peer = Ipv4Addr::new(198, 51, 100, 9);
let mut forbidden = IpSet::new();
forbidden.insert(IpAddr::V4(excluded));
let (_session, ctx) = ScanSession::builder()
.excluding(Exclusions::new(forbidden))
.build();
let (_tx, rx) = tokio::sync::mpsc::channel(16);
let mut ranges = IpSet::new();
ranges.insert_range("198.51.100.0/24".parse().expect("a valid range"));
let mut listener = PassiveListener::over(
rx,
capture::CaptureGuard::noop(),
Recording::Everything,
OnLink::of(ranges),
ctx.clone(),
);
for (from, port, client) in [(ordinary, 22, 51235), (excluded, 443, 51234)] {
listener.read(&captured(tcp_frame_from(
MAC,
from,
port,
peer,
client,
flags::SYN | flags::ACK,
)));
}
let hosts = ctx.hosts_snapshot();
assert_eq!(hosts.len(), 1, "one machine, one record");
assert_eq!(hosts[0].primary_ip(), IpAddr::V4(ordinary));
assert!(
!hosts[0].ips().contains(&IpAddr::V4(excluded)),
"the excluded address rode in on the merge: {:?}",
hosts[0].ips()
);
}
#[test]
fn a_watch_at_its_ceiling_stops_taking_machines_and_keeps_enriching_the_ones_it_has() {
use crate::protocols::tcp::flags;
const HELD_MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xAA);
const STRANGER_MAC: pnet_base::MacAddr = pnet_base::MacAddr(2, 0, 0, 0, 0, 0xBB);
let (mut listener, ctx) = listening_on_a_known_link(Recording::Everything);
let peer = Ipv4Addr::new(198, 51, 100, 9);
let known = Ipv4Addr::new(198, 51, 100, 5);
listener.read(&captured(tcp_frame_from(
HELD_MAC,
known,
22,
peer,
51234,
flags::SYN | flags::ACK,
)));
assert_eq!(ctx.host_count(), 1);
listener.held = MAX_RECORDED_HOSTS;
listener.read(&captured(tcp_frame_from(
STRANGER_MAC,
Ipv4Addr::new(198, 51, 100, 200),
22,
peer,
51235,
flags::SYN | flags::ACK,
)));
assert_eq!(
ctx.host_count(),
1,
"a machine heard at the ceiling is not recorded"
);
listener.read(&captured(tcp_frame_from(
HELD_MAC,
known,
443,
peer,
51236,
flags::SYN | flags::ACK,
)));
let host = ctx.hosts_snapshot().remove(0);
let mut open: Vec<u16> = host.ports().map(Port::number).collect();
open.sort_unstable();
assert_eq!(
open,
vec![22, 443],
"a record already held goes on taking what it is told"
);
let failures = ctx.failures_snapshot();
assert_eq!(
failures.len(),
1,
"the ceiling is reported once, not once per frame: {failures:#?}"
);
}
#[test]
fn both_announcement_protocols_land_in_the_same_four_fields() {
use crate::protocols::{cdp, lldp};
for (spoken, frame, source, device_mac) in [
(
"LLDP",
lldp::tests::switch_announcement(),
AttachmentSource::Lldp,
lldp::tests::SWITCH_MAC,
),
(
"CDP",
cdp::tests::switch_announcement(),
AttachmentSource::Cdp,
cdp::tests::SWITCH_MAC,
),
] {
let (mut listener, ctx) = listening(Recording::Everything);
listener.read(&captured(frame));
let attachments = ctx.take_attachments();
assert_eq!(attachments.len(), 1, "{spoken}: one frame, one attachment");
let attachment = &attachments[0];
assert_eq!(attachment.source(), source, "{spoken}: whose word it is");
assert_eq!(
attachment.device_mac(),
Some(device_mac.into_core()),
"{spoken}: the machine that sent it"
);
assert_eq!(
attachment.device_name(),
Some("core-sw-02"),
"{spoken}: what the device calls itself"
);
assert_eq!(
attachment.port(),
Some("GigabitEthernet1/0/14"),
"{spoken}: the port this machine is plugged into"
);
assert_eq!(
attachment.native_vlan(),
Some(40),
"{spoken}: the VLAN untagged traffic lands in"
);
assert_eq!(
attachment.management_address(),
Some(IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2))),
"{spoken}: where the device is managed"
);
let host = ctx
.hosts_snapshot()
.into_iter()
.find(|host| host.primary_ip() == IpAddr::V4(Ipv4Addr::new(198, 51, 100, 2)))
.unwrap_or_else(|| panic!("{spoken}: the device named an address of its own"));
let roles = host.network_roles();
assert!(
roles.contains(&NetworkRole::Switch) && roles.contains(&NetworkRole::Router),
"{spoken}: both enabled capabilities reached the host: {roles:?}"
);
}
}
}