use crate::model::finding::{ClaimId, Finding, MAX_FINDINGS_PER_SUBJECT};
use crate::model::ip::scoped::{ScopedIp, Zone};
use crate::model::mac::MacAddr;
use crate::model::port::{Port, PortState, Protocol};
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
net::IpAddr,
time::SystemTime,
};
pub mod hardware;
pub mod os;
pub mod path;
pub mod protocol;
pub mod status;
pub mod telemetry;
pub use hardware::{HardwareDescription, HardwareInfo};
pub use os::{OsEvidence, OsFingerprint, OsSource};
pub use path::{Hop, NetworkPath};
pub use protocol::{IpProtocolState, ip_protocol_name};
pub use status::{HostStatus, StatusProtocol, StatusReason};
pub use telemetry::HostTelemetry;
pub const MAX_PORTS_PER_HOST: usize = (u16::MAX as usize + 1) * Protocol::ALL.len();
pub const TARPIT_OPEN_PORTS: usize = 1_000;
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum NetworkRole {
Router,
DnsServer,
DhcpServer,
NtpServer,
SnmpAgent,
DomainController,
Switch,
Origin,
Tarpit,
Truncated,
}
impl NetworkRole {
pub const fn label(self) -> &'static str {
match self {
Self::Router => "router",
Self::DnsServer => "DNS",
Self::DhcpServer => "DHCP",
Self::NtpServer => "NTP",
Self::SnmpAgent => "SNMP",
Self::DomainController => "domain-controller",
Self::Switch => "switch",
Self::Origin => "origin",
Self::Tarpit => "tarpit",
Self::Truncated => "truncated",
}
}
pub const ALL: [NetworkRole; 10] = [
Self::Router,
Self::DnsServer,
Self::DhcpServer,
Self::NtpServer,
Self::SnmpAgent,
Self::DomainController,
Self::Switch,
Self::Origin,
Self::Tarpit,
Self::Truncated,
];
}
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum Filtering {
InlineMiddlebox,
StatefulFilter,
PortTrustingAcl,
StatelessFilter,
}
impl Filtering {
pub const ALL: [Filtering; 4] = [
Self::InlineMiddlebox,
Self::StatefulFilter,
Self::PortTrustingAcl,
Self::StatelessFilter,
];
}
type OsClaim = (
OsSource,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
);
const MAX_OS_EVIDENCE: usize = 8;
#[must_use]
#[derive(Debug, Clone)]
pub struct Host {
primary_ip: IpAddr,
ips: BTreeSet<IpAddr>,
hostname: Option<String>,
status: HostStatus,
reasons: HashSet<StatusReason>,
os: Option<Box<OsFingerprint>>,
os_evidence: BTreeMap<OsClaim, OsEvidence>,
hardware: Option<HardwareInfo>,
zone: Option<Zone>,
telemetry: HostTelemetry,
path: NetworkPath,
network_roles: HashSet<NetworkRole>,
filtering: HashSet<Filtering>,
ip_protocols: BTreeMap<u8, IpProtocolState>,
findings: BTreeMap<ClaimId, Finding>,
first_seen: SystemTime,
last_seen: SystemTime,
ports: BTreeMap<(u16, Protocol), Port>,
open_ports: usize,
}
fn identity_rank(ip: &IpAddr) -> u8 {
match ip {
IpAddr::V4(_) => 0,
IpAddr::V6(v6) if crate::model::ip::is_globally_scoped(v6) => 1,
IpAddr::V6(_) => 2,
}
}
impl Host {
pub fn new(primary_ip: IpAddr) -> Self {
let mut ips = BTreeSet::new();
ips.insert(primary_ip);
let now = SystemTime::now();
Self {
primary_ip,
ips,
hostname: None,
status: HostStatus::Unknown,
reasons: HashSet::new(),
os: None,
os_evidence: BTreeMap::new(),
hardware: None,
zone: None,
telemetry: HostTelemetry::default(),
path: NetworkPath::new(),
network_roles: HashSet::new(),
filtering: HashSet::new(),
ip_protocols: BTreeMap::new(),
findings: BTreeMap::new(),
first_seen: now,
last_seen: now,
ports: BTreeMap::new(),
open_ports: 0,
}
}
pub fn primary_ip(&self) -> IpAddr {
self.primary_ip
}
pub fn ips(&self) -> &BTreeSet<IpAddr> {
&self.ips
}
pub fn hostname(&self) -> Option<&str> {
self.hostname.as_deref()
}
pub fn status(&self) -> HostStatus {
self.status
}
pub fn reasons(&self) -> &HashSet<StatusReason> {
&self.reasons
}
pub fn os(&self) -> Option<&OsFingerprint> {
self.os.as_deref()
}
pub fn hardware(&self) -> Option<&HardwareInfo> {
self.hardware.as_ref()
}
pub fn zone(&self) -> Option<&Zone> {
self.zone.as_ref()
}
pub fn set_zone(&mut self, zone: Zone) {
self.zone.get_or_insert(zone);
self.last_seen = SystemTime::now();
}
pub fn scoped_ip(&self) -> ScopedIp {
match &self.zone {
Some(zone) => ScopedIp::scoped(self.primary_ip, zone.clone()),
None => ScopedIp::unscoped(self.primary_ip),
}
}
pub fn telemetry(&self) -> &HostTelemetry {
&self.telemetry
}
pub fn path(&self) -> &NetworkPath {
&self.path
}
pub fn record_hop_counter(&mut self, arrived: u8) {
self.telemetry.record_hop_counter(arrived);
}
pub fn record_hop(&mut self, hop: Hop) {
self.path.record(hop);
self.last_seen = SystemTime::now();
}
pub fn network_roles(&self) -> &HashSet<NetworkRole> {
&self.network_roles
}
pub fn filtering(&self) -> &HashSet<Filtering> {
&self.filtering
}
pub fn ip_protocols(&self) -> &BTreeMap<u8, IpProtocolState> {
&self.ip_protocols
}
pub fn first_seen(&self) -> SystemTime {
self.first_seen
}
pub fn last_seen(&self) -> SystemTime {
self.last_seen
}
pub fn restore_seen(&mut self, first_seen: SystemTime, last_seen: SystemTime) {
let (first_seen, last_seen) = if first_seen <= last_seen {
(first_seen, last_seen)
} else {
(last_seen, first_seen)
};
self.first_seen = first_seen;
self.last_seen = last_seen;
}
pub fn consider_primary_ip(&mut self, candidate: IpAddr) -> bool {
self.add_ip(candidate);
if identity_rank(&candidate) >= identity_rank(&self.primary_ip) {
return false;
}
self.primary_ip = candidate;
self.last_seen = SystemTime::now();
true
}
pub fn add_ip(&mut self, ip: IpAddr) -> bool {
let is_new = self.ips.insert(ip);
self.last_seen = SystemTime::now();
is_new
}
pub fn extend_ips(&mut self, ips: impl IntoIterator<Item = IpAddr>) {
self.ips.extend(ips);
self.last_seen = SystemTime::now();
}
pub fn set_hostname(&mut self, hostname: Option<String>) {
self.hostname = hostname;
self.last_seen = SystemTime::now();
}
pub fn set_status(&mut self, status: HostStatus) {
if status > self.status {
self.status = status;
}
self.last_seen = SystemTime::now();
}
pub fn add_reason(&mut self, reason: StatusReason) {
self.reasons.insert(reason);
self.last_seen = SystemTime::now();
}
pub fn record_evidence(&mut self, status: HostStatus, reason: StatusReason) {
if status > self.status {
self.status = status;
}
self.reasons.insert(reason);
self.last_seen = SystemTime::now();
}
pub fn os_evidence(&self) -> impl Iterator<Item = &OsEvidence> {
self.os_evidence.values()
}
pub fn findings(&self) -> impl Iterator<Item = &Finding> {
self.findings.values()
}
pub fn record_os_evidence(&mut self, evidence: OsEvidence) -> bool {
let claim: OsClaim = (
evidence.source,
evidence.family.clone(),
evidence.device.clone(),
evidence.vendor.clone(),
evidence.product.clone(),
evidence.version.clone(),
evidence.kernel.clone(),
);
let full = self.os_evidence.len() >= MAX_OS_EVIDENCE;
match self.os_evidence.get_mut(&claim) {
Some(existing) => {
let joined = os::join_readings(&existing.evidence, &evidence.evidence);
let changed = joined != existing.evidence;
existing.evidence = joined;
existing.confidence = existing.confidence.max(evidence.confidence);
changed
}
None if full => false,
None => {
self.os_evidence.insert(claim, evidence);
true
}
}
}
pub fn add_finding(&mut self, finding: Finding) -> bool {
let claim = finding.claim_id();
let full = self.findings.len() >= MAX_FINDINGS_PER_SUBJECT;
match self.findings.get_mut(&claim) {
Some(existing) => existing.corroborate(finding),
None if full => false,
None => {
self.findings.insert(claim, finding);
true
}
}
}
pub fn add_port_finding(
&mut self,
number: u16,
protocol: Protocol,
finding: Finding,
) -> Option<bool> {
self.ports
.get_mut(&(number, protocol))
.map(|port| port.add_finding(finding))
}
pub fn set_os(&mut self, os: OsFingerprint) {
self.os = Some(Box::new(os));
self.last_seen = SystemTime::now();
}
pub fn clear_os(&mut self) {
self.os = None;
self.last_seen = SystemTime::now();
}
pub fn set_hardware(&mut self, hardware: HardwareInfo) {
self.hardware = Some(hardware);
self.last_seen = SystemTime::now();
}
pub fn with_mac(mut self, mac: MacAddr) -> Self {
self.record_mac(mac);
self
}
pub fn record_mac(&mut self, mac: MacAddr) {
match &mut self.hardware {
Some(hardware) => hardware.add_mac(mac),
None => self.hardware = Some(HardwareInfo::new(mac)),
}
self.last_seen = SystemTime::now();
}
pub fn add_rtt(&mut self, rtt: std::time::Duration) {
self.telemetry.add_rtt(rtt);
self.last_seen = SystemTime::now();
}
pub fn add_rtt_from(&mut self, rtt: std::time::Duration, protocol: StatusProtocol) {
self.telemetry.add_rtt_from(rtt, protocol);
self.last_seen = SystemTime::now();
}
#[must_use]
pub fn rtt_protocol(&self) -> Option<StatusProtocol> {
self.telemetry.rtt_protocol()
}
pub fn add_segment_wide_rtt(&mut self, rtt: std::time::Duration) {
self.telemetry.add_segment_wide_rtt(rtt);
self.last_seen = SystemTime::now();
}
pub fn add_segment_wide_rtt_from(
&mut self,
rtt: std::time::Duration,
protocol: StatusProtocol,
) {
self.telemetry.add_segment_wide_rtt_from(rtt, protocol);
self.last_seen = SystemTime::now();
}
pub fn with_rtt(mut self, rtt: std::time::Duration) -> Self {
self.add_rtt(rtt);
self
}
pub fn add_rtts(&mut self, rtts: impl IntoIterator<Item = std::time::Duration>) {
for rtt in rtts {
self.telemetry.add_rtt(rtt);
}
self.last_seen = SystemTime::now();
}
pub fn add_network_role(&mut self, role: NetworkRole) -> bool {
let is_new = self.network_roles.insert(role);
self.last_seen = SystemTime::now();
is_new
}
pub fn add_filtering(&mut self, filtering: Filtering) -> bool {
let is_new = self.filtering.insert(filtering);
self.last_seen = SystemTime::now();
is_new
}
pub fn record_ip_protocol(&mut self, number: u8, state: IpProtocolState) -> bool {
let recorded = match self.ip_protocols.get_mut(&number) {
Some(held) if state > *held => {
*held = state;
true
}
Some(_) => false,
None => {
self.ip_protocols.insert(number, state);
true
}
};
if matches!(state, IpProtocolState::Open | IpProtocolState::Closed) {
self.last_seen = SystemTime::now();
}
recorded
}
pub fn min_rtt(&self) -> Option<std::time::Duration> {
self.telemetry.min_rtt()
}
pub fn max_rtt(&self) -> Option<std::time::Duration> {
self.telemetry.max_rtt()
}
pub fn average_rtt(&self) -> Option<std::time::Duration> {
self.telemetry.average_rtt()
}
pub fn median_rtt(&self) -> Option<std::time::Duration> {
self.telemetry.median_rtt()
}
pub fn mac(&self) -> Option<MacAddr> {
self.hardware.as_ref().and_then(|h| h.most_recent_mac())
}
pub fn vendor(&self) -> Option<&str> {
self.hardware.as_ref().and_then(HardwareInfo::vendor)
}
pub fn is_alive(&self) -> bool {
self.status.is_alive()
}
pub fn ports(&self) -> impl Iterator<Item = &Port> {
self.ports.values()
}
pub fn port_count(&self) -> usize {
self.ports.len()
}
pub fn add_port(&mut self, new_port: Port) -> bool {
let key = (new_port.number(), new_port.protocol());
let existing = self.ports.get(&key);
if existing.is_none() && self.ports.len() >= MAX_PORTS_PER_HOST {
self.network_roles.insert(NetworkRole::Truncated);
return false;
}
let was_open = existing.is_some_and(|port| port.state() == PortState::Open);
let recorded = match self.ports.entry(key) {
std::collections::btree_map::Entry::Occupied(slot) => {
let recorded = slot.into_mut();
recorded.merge(new_port);
recorded
}
std::collections::btree_map::Entry::Vacant(slot) => slot.insert(new_port),
};
if !was_open && recorded.state() == PortState::Open {
self.open_ports += 1;
if self.open_ports >= TARPIT_OPEN_PORTS {
self.network_roles.insert(NetworkRole::Tarpit);
}
}
self.last_seen = SystemTime::now();
true
}
pub fn open_port_count(&self) -> usize {
self.open_ports
}
pub fn merge(&mut self, other: Host) {
let Host {
primary_ip: other_primary,
ips,
hostname,
status,
reasons,
os,
os_evidence,
hardware,
zone,
telemetry,
path,
network_roles,
filtering,
ip_protocols,
findings,
first_seen: other_first_seen,
last_seen: other_last_seen,
ports,
open_ports: _,
} = other;
let first_seen = self.first_seen.min(other_first_seen);
let last_seen = self.last_seen.max(other_last_seen);
self.ips.extend(ips);
self.consider_primary_ip(other_primary);
if self.hostname.is_none() {
self.hostname = hostname;
}
if status > self.status {
self.status = status;
}
self.reasons.extend(reasons);
if let Some(other_os) = os {
if let Some(ref mut self_os) = self.os {
self_os.merge(*other_os);
} else {
self.os = Some(other_os);
}
}
for evidence in os_evidence.into_values() {
self.record_os_evidence(evidence);
}
if let Some(other_hw) = hardware {
if let Some(ref mut self_hw) = self.hardware {
self_hw.merge(other_hw);
} else {
self.hardware = Some(other_hw);
}
}
if let Some(other_zone) = zone {
self.zone.get_or_insert(other_zone);
}
self.telemetry.merge(telemetry);
for hop in path.hops() {
self.path.record(*hop);
}
self.network_roles.extend(network_roles);
self.filtering.extend(filtering);
for (number, state) in ip_protocols {
self.record_ip_protocol(number, state);
}
for finding in findings.into_values() {
self.add_finding(finding);
}
for port in ports.into_values() {
self.add_port(port);
}
self.first_seen = first_seen;
self.last_seen = last_seen;
}
}
impl std::fmt::Display for Host {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.primary_ip, self.status)?;
if let Some(ref os) = self.os {
write!(f, " - {}", os)?;
}
let mut roles = NetworkRole::ALL
.iter()
.filter(|role| self.network_roles.contains(role))
.peekable();
if roles.peek().is_some() {
write!(f, " [")?;
for (n, role) in roles.enumerate() {
if n > 0 {
write!(f, ", ")?;
}
write!(f, "{}", role.label())?;
}
write!(f, "]")?;
}
if !self.network_roles.contains(&NetworkRole::Tarpit)
&& !self.network_roles.contains(&NetworkRole::Truncated)
{
write!(f, " [{}]", self.telemetry)?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::port::{Port, PortState, Protocol};
use std::net::Ipv4Addr;
static IP_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 100));
#[test]
fn a_protocol_verdict_is_promoted_and_never_lowered() {
use crate::model::host::IpProtocolState;
let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)));
assert!(host.record_ip_protocol(47, IpProtocolState::Unasked));
assert_eq!(
host.ip_protocols().get(&47),
Some(&IpProtocolState::Unasked)
);
assert!(host.record_ip_protocol(47, IpProtocolState::Closed));
assert!(
!host.record_ip_protocol(47, IpProtocolState::OpenFiltered),
"a weaker verdict is not news"
);
assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Closed));
assert!(host.record_ip_protocol(47, IpProtocolState::Open));
assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
}
#[test]
fn merging_keeps_the_stronger_protocol_verdict_from_either_side() {
use crate::model::host::IpProtocolState;
let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
let mut reached = Host::new(ip);
reached.record_ip_protocol(47, IpProtocolState::Open);
reached.record_ip_protocol(89, IpProtocolState::Unasked);
let mut cut_short = Host::new(ip);
cut_short.record_ip_protocol(47, IpProtocolState::Unasked);
cut_short.record_ip_protocol(89, IpProtocolState::Closed);
cut_short.record_ip_protocol(50, IpProtocolState::OpenFiltered);
let mut folded = reached.clone();
folded.merge(cut_short.clone());
let mut other_way = cut_short;
other_way.merge(reached);
for host in [&folded, &other_way] {
assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
assert_eq!(host.ip_protocols().get(&89), Some(&IpProtocolState::Closed));
assert_eq!(
host.ip_protocols().get(&50),
Some(&IpProtocolState::OpenFiltered),
"a protocol only one side asked about survives the fold"
);
}
}
#[test]
fn a_merge_keeps_every_field_of_the_record_it_folds_in() {
let ip: IpAddr = "192.0.2.1".parse().expect("an address");
let mut incumbent = Host::new(ip);
let mut arriving = Host::new(ip);
arriving.add_filtering(Filtering::StatefulFilter);
arriving.add_filtering(Filtering::InlineMiddlebox);
arriving.record_os_evidence(OsEvidence {
source: OsSource::ServiceBanner,
family: Some("Linux".to_string()),
device: None,
vendor: None,
product: None,
version: None,
kernel: Some("6.1.0".to_string()),
arch: None,
cpe: None,
confidence: 0.9,
evidence: "ssh banner".to_string(),
});
incumbent.merge(arriving);
assert_eq!(
incumbent.filtering().len(),
2,
"a filtering conclusion is drawn by a comparative probe only one \
record will have run, so dropping it loses the whole finding"
);
assert_eq!(
incumbent.os_evidence().count(),
1,
"os evidence is what corroboration is computed over, and the \
fold is where a second source's reading arrives"
);
}
#[test]
fn a_merge_keeps_what_only_the_other_record_learned() {
let mut earlier = Host::new(IP_ADDR);
earlier.set_status(HostStatus::Up);
let mut later = Host::new(IP_ADDR);
later.record_hop_counter(59);
later.record_hop(path::Hop::answered(
1,
IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1)),
None,
));
later.record_hop(path::Hop::silent(2));
earlier.merge(later);
assert_eq!(
earlier.path().hops().len(),
2,
"the trace ran between the two snapshots and only the later one has it"
);
assert_eq!(earlier.path().length(), Some(2));
assert_eq!(earlier.telemetry().hop_counter(), Some(59));
}
#[test]
fn merging_paths_keeps_the_stronger_claim_at_every_distance() {
let router = IpAddr::V4(Ipv4Addr::new(192, 168, 0, 1));
let mut inherited = Host::new(IP_ADDR);
inherited.record_hop(path::Hop::answered(1, router, None).as_inferred());
inherited.record_hop(path::Hop::silent(2));
let mut measured = Host::new(IP_ADDR);
measured.record_hop(path::Hop::answered(
1,
router,
Some(std::time::Duration::from_millis(3)),
));
inherited.merge(measured);
let hops = inherited.path().hops();
assert_eq!(hops.len(), 2, "the distance only one side knew survives");
assert!(!hops[0].inferred(), "a measurement replaces an inference");
assert_eq!(hops[0].rtt(), Some(std::time::Duration::from_millis(3)));
}
#[test]
fn a_status_is_never_lowered_by_the_plain_setter() {
let mut host = Host::new(IP_ADDR);
host.set_status(HostStatus::Up);
host.set_status(HostStatus::Down);
assert_eq!(host.status(), HostStatus::Up);
let mut climbing = Host::new(IP_ADDR);
climbing.set_status(HostStatus::Down);
climbing.set_status(HostStatus::Up);
assert_eq!(climbing.status(), HostStatus::Up);
}
#[test]
fn a_port_number_holds_one_endpoint_per_protocol() {
let mut host = Host::new(IP_ADDR);
host.add_port(Port::new(53, Protocol::Tcp, PortState::Closed));
host.add_port(Port::new(53, Protocol::Udp, PortState::Open));
let ports: Vec<_> = host.ports().collect();
assert_eq!(ports.len(), 2, "TCP/53 and UDP/53 are two endpoints");
assert_eq!(
(ports[0].protocol(), ports[0].state()),
(Protocol::Tcp, PortState::Closed)
);
assert_eq!(
(ports[1].protocol(), ports[1].state()),
(Protocol::Udp, PortState::Open),
"neither finding was folded into the other"
);
host.add_port(Port::new(53, Protocol::Tcp, PortState::Open));
assert_eq!(host.port_count(), 2);
assert_eq!(
host.ports().next().expect("tcp/53").state(),
PortState::Open
);
}
#[test]
fn a_host_prints_its_roles_in_one_order_however_they_were_recorded() {
let expected = "192.168.0.100 (Up) [router, DNS, origin]";
for order in [
[
NetworkRole::Router,
NetworkRole::DnsServer,
NetworkRole::Origin,
],
[
NetworkRole::Origin,
NetworkRole::Router,
NetworkRole::DnsServer,
],
[
NetworkRole::DnsServer,
NetworkRole::Origin,
NetworkRole::Router,
],
] {
let mut host = Host::new(IP_ADDR);
host.set_status(HostStatus::Up);
for role in order {
host.add_network_role(role);
}
let line = host.to_string();
let (roles, _telemetry) = line.rsplit_once(" [").expect("telemetry follows the roles");
assert_eq!(roles, expected, "recorded as {order:?}");
}
}
#[test]
fn a_tarpit_prints_the_marking_where_the_latency_would_be() {
let mut host = Host::new(IP_ADDR);
host.set_status(HostStatus::Up);
host.add_network_role(NetworkRole::Tarpit);
assert_eq!(host.to_string(), "192.168.0.100 (Up) [tarpit]");
}
#[test]
fn a_full_scan_of_both_transports_is_recorded_whole() {
let mut host = Host::new(IP_ADDR);
for protocol in Protocol::ALL {
for port in u16::MIN..=u16::MAX {
assert!(
host.add_port(Port::new(port, protocol, PortState::Closed)),
"{protocol:?}/{port} was refused by a scan that asked for it"
);
}
}
assert_eq!(host.port_count(), MAX_PORTS_PER_HOST);
assert!(
!host.network_roles().contains(&NetworkRole::Truncated),
"a complete port list was reported as truncated"
);
}
#[test]
fn the_cap_is_what_the_port_map_can_hold() {
let endpoints = (usize::from(u16::MAX) + 1) * Protocol::ALL.len();
assert_eq!(MAX_PORTS_PER_HOST, endpoints);
}
#[test]
fn a_wide_scan_of_an_ordinary_host_is_neither_truncated_nor_a_tarpit() {
let mut host = Host::new(IP_ADDR);
for port in 1..=1024u16 {
let state = match port {
53 | 80 => PortState::Open,
_ => PortState::Closed,
};
assert!(host.add_port(Port::new(port, Protocol::Tcp, state)));
}
assert_eq!(host.port_count(), 1024, "every finding was kept");
assert!(host.network_roles().is_empty(), "and nothing was inferred");
}
#[test]
fn a_host_answering_open_on_everything_is_called_what_it_is() {
let mut host = Host::new(IP_ADDR);
for port in 0..TARPIT_OPEN_PORTS {
host.add_port(Port::new(port as u16, Protocol::Tcp, PortState::Open));
}
assert!(host.network_roles().contains(&NetworkRole::Tarpit));
assert!(!host.network_roles().contains(&NetworkRole::Truncated));
assert_eq!(host.open_port_count(), TARPIT_OPEN_PORTS);
}
#[test]
fn the_open_count_follows_what_the_ports_became() {
let mut host = Host::new(IP_ADDR);
host.add_port(Port::new(22, Protocol::Tcp, PortState::Filtered));
assert_eq!(host.open_port_count(), 0);
host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
assert_eq!(host.open_port_count(), 1, "promoted");
host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
assert_eq!(host.open_port_count(), 1, "and counted once");
}
#[test]
fn merging_two_records_keeps_the_span_they_were_observed_over() {
let epoch = SystemTime::UNIX_EPOCH;
let at = |secs| epoch + std::time::Duration::from_secs(secs);
let mut early = Host::new(IP_ADDR);
early.first_seen = at(10);
early.last_seen = at(20);
let mut late = Host::new(IP_ADDR);
late.first_seen = at(30);
late.last_seen = at(40);
early.merge(late);
assert_eq!(early.first_seen(), at(10), "the earlier sighting");
assert_eq!(early.last_seen(), at(40), "and the later one");
}
#[test]
fn merging_promotes_the_status_without_lowering_it() {
let mut h1 = Host::new(IP_ADDR);
h1.set_status(HostStatus::Down);
let mut h2 = Host::new(IP_ADDR);
h2.set_status(HostStatus::Filtered);
h1.merge(h2);
assert_eq!(h1.status(), HostStatus::Filtered);
}
#[test]
fn merging_two_records_of_one_host_applies_the_same_address_ranking() {
let v4: IpAddr = "192.0.2.10".parse().unwrap();
let lla: IpAddr = "fe80::10".parse().unwrap();
let mut into_link_local = Host::new(lla);
into_link_local.merge(Host::new(v4));
assert_eq!(into_link_local.primary_ip(), v4);
let mut into_v4 = Host::new(v4);
into_v4.merge(Host::new(lla));
assert_eq!(
into_v4.primary_ip(),
v4,
"and the ranking never moves back down"
);
assert_eq!(into_link_local.ips().len(), 2, "nothing is discarded");
assert_eq!(into_v4.ips().len(), 2);
}
#[test]
fn every_mac_a_host_answers_under_stays_on_its_record() {
let first = MacAddr::new(0x02, 0, 0, 0, 0, 1);
let second = MacAddr::new(0x02, 0, 0, 0, 0, 2);
let mut host = Host::new(IP_ADDR);
host.record_mac(first);
host.record_mac(second);
let hardware = host.hardware().expect("a sighting was recorded");
assert_eq!(hardware.macs().len(), 2);
assert!(hardware.macs().contains_key(&first));
assert!(hardware.macs().contains_key(&second));
assert_eq!(
host.mac(),
Some(second),
"and the newest is the one the host leads with"
);
}
#[test]
fn merging_two_records_keeps_the_union_of_their_ports() {
let mut h1 = Host::new(IP_ADDR);
for port in u16::MIN..=u16::MAX {
h1.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
}
assert_eq!(h1.port_count(), usize::from(u16::MAX) + 1);
assert!(!h1.network_roles.contains(&NetworkRole::Truncated));
let mut h2 = Host::new(IP_ADDR);
for port in 0..1_000u16 {
h2.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
}
h2.add_port(Port::new(53, Protocol::Udp, PortState::Open));
h1.merge(h2);
assert_eq!(
h1.port_count(),
usize::from(u16::MAX) + 2,
"the union: the whole of TCP and one UDP endpoint"
);
assert!(
!h1.network_roles.contains(&NetworkRole::Truncated),
"nothing was dropped, so nothing here is truncated"
);
assert!(
!h1.network_roles.contains(&NetworkRole::Tarpit),
"one open port is not a tarpit"
);
}
#[test]
fn the_address_a_host_leads_with_does_not_depend_on_reply_order() {
let v4: IpAddr = "192.0.2.10".parse().unwrap();
let gua: IpAddr = "2001:db8::10".parse().unwrap();
let lla: IpAddr = "fe80::10".parse().unwrap();
for order in [
[v4, gua, lla],
[v4, lla, gua],
[gua, v4, lla],
[gua, lla, v4],
[lla, v4, gua],
[lla, gua, v4],
] {
let mut host = Host::new(order[0]);
for ip in order {
host.consider_primary_ip(ip);
}
assert_eq!(
host.primary_ip(),
v4,
"arrival order {order:?} must not change which address leads"
);
assert_eq!(host.ips().len(), 3, "and none of them is discarded");
}
}
#[test]
fn only_a_globally_scoped_address_outranks_a_link_local_one() {
let lla: IpAddr = "fe80::10".parse().unwrap();
for scoped in ["2001:db8::10", "fd00::10"] {
let mut host = Host::new(lla);
host.consider_primary_ip(scoped.parse().unwrap());
assert_eq!(
host.primary_ip().to_string(),
scoped,
"{scoped} names the host"
);
}
for useless in ["::1", "::", "ff02::1"] {
let mut host = Host::new(lla);
host.consider_primary_ip(useless.parse().unwrap());
assert_eq!(
host.primary_ip(),
lla,
"{useless} does not identify the host to anyone"
);
}
}
#[test]
fn a_global_address_leads_over_a_link_local_one() {
let gua: IpAddr = "2001:db8::10".parse().unwrap();
let lla: IpAddr = "fe80::10".parse().unwrap();
let mut from_lla = Host::new(lla);
from_lla.consider_primary_ip(gua);
assert_eq!(from_lla.primary_ip(), gua);
let mut from_gua = Host::new(gua);
from_gua.consider_primary_ip(lla);
assert_eq!(
from_gua.primary_ip(),
gua,
"and the ranking never moves back down"
);
}
#[test]
fn an_equally_good_address_does_not_displace_the_current_one() {
let first: IpAddr = "2001:db8::1".parse().unwrap();
let second: IpAddr = "2001:db8::2".parse().unwrap();
let mut host = Host::new(first);
assert!(!host.consider_primary_ip(second));
assert_eq!(host.primary_ip(), first);
assert!(
host.ips().contains(&second),
"it is still an address it has"
);
}
fn a_finding(detection_id: &str) -> Finding {
use crate::model::confidence::Confidence;
use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
Finding::new(
DetectionId::new(detection_id, Version::new(1, 0, 0), "hash").unwrap(),
"A host-level finding",
Severity::High,
Confidence::Certain,
DetectionClass::ActiveBenign,
)
.unwrap()
}
#[test]
fn the_same_finding_recorded_twice_is_one() {
let mut host = Host::new(IP_ADDR);
assert!(host.add_finding(a_finding("det-a")), "the first is new");
assert!(
!host.add_finding(a_finding("det-a")),
"an identical re-firing is not new information"
);
assert_eq!(host.findings().count(), 1);
}
#[test]
fn a_merge_keeps_both_hosts_findings() {
let mut base = Host::new(IP_ADDR);
base.add_finding(a_finding("det-a"));
let mut other = Host::new(IP_ADDR);
other.add_finding(a_finding("det-b"));
base.merge(other);
let ids: Vec<String> = base
.findings()
.map(|f| f.detection().id().to_string())
.collect();
assert_eq!(ids.len(), 2, "a merge must not drop the other's findings");
assert!(ids.contains(&"det-a".to_string()));
assert!(ids.contains(&"det-b".to_string()));
}
}