use crate::model::ip::scoped::{ScopedIp, Zone};
use crate::model::mac::MacAddr;
use crate::model::port::{Port, Protocol};
use std::{
collections::{BTreeMap, BTreeSet, HashSet},
net::IpAddr,
time::SystemTime,
};
pub mod hardware;
pub mod os;
pub mod status;
pub mod telemetry;
pub use hardware::HardwareInfo;
pub use os::OsFingerprint;
pub use status::{HostStatus, StatusProtocol, StatusReason};
pub use telemetry::HostTelemetry;
pub const MAX_PORTS_PER_HOST: usize = 1000;
#[non_exhaustive]
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum NetworkRole {
Tarpit,
}
#[derive(Debug, Clone)]
pub struct Host {
primary_ip: IpAddr,
ips: BTreeSet<IpAddr>,
hostname: Option<String>,
status: HostStatus,
reasons: HashSet<StatusReason>,
os: Option<Box<OsFingerprint>>,
hardware: Option<HardwareInfo>,
zone: Option<Zone>,
telemetry: HostTelemetry,
network_roles: HashSet<NetworkRole>,
first_seen: SystemTime,
last_seen: SystemTime,
ports: BTreeMap<(u16, Protocol), Port>,
}
fn identity_rank(ip: &IpAddr) -> u8 {
match ip {
IpAddr::V4(_) => 0,
IpAddr::V6(v6) if crate::model::ip::is_global_unicast(v6) || is_unique_local(v6) => 1,
IpAddr::V6(_) => 2,
}
}
fn is_unique_local(addr: &std::net::Ipv6Addr) -> bool {
addr.octets()[0] & 0xfe == 0xfc
}
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,
hardware: None,
zone: None,
telemetry: HostTelemetry::default(),
network_roles: HashSet::new(),
first_seen: now,
last_seen: now,
ports: BTreeMap::new(),
}
}
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 network_roles(&self) -> &HashSet<NetworkRole> {
&self.network_roles
}
pub fn first_seen(&self) -> SystemTime {
self.first_seen
}
pub fn last_seen(&self) -> SystemTime {
self.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 set_os(&mut self, os: OsFingerprint) {
self.os = Some(Box::new(os));
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_segment_wide_rtt(&mut self, rtt: std::time::Duration) {
self.telemetry.add_segment_wide_rtt(rtt);
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) {
self.network_roles.insert(role);
self.last_seen = SystemTime::now();
}
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());
if self.ports.len() >= MAX_PORTS_PER_HOST && !self.ports.contains_key(&key) {
self.network_roles.insert(NetworkRole::Tarpit);
return false;
}
self.ports
.entry(key)
.and_modify(|p| p.merge(new_port.clone()))
.or_insert(new_port);
self.last_seen = SystemTime::now();
true
}
pub fn merge(&mut self, other: Host) {
let first_seen = self.first_seen.min(other.first_seen);
let last_seen = self.last_seen.max(other.last_seen);
let other_primary = other.primary_ip;
self.ips.extend(other.ips);
self.consider_primary_ip(other_primary);
if self.hostname.is_none() {
self.hostname = other.hostname;
}
if other.status > self.status {
self.status = other.status;
}
self.reasons.extend(other.reasons);
if let Some(other_os) = other.os {
if let Some(ref mut self_os) = self.os {
self_os.merge(*other_os);
} else {
self.os = Some(other_os);
}
}
if let Some(other_hw) = other.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) = other.zone {
self.zone.get_or_insert(other_zone);
}
self.telemetry.merge(other.telemetry);
self.network_roles.extend(other.network_roles);
for port in other.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)?;
}
if self.network_roles.contains(&NetworkRole::Tarpit) {
write!(f, " [TARPIT]")?;
} else {
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_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 add_port_reports_whether_the_finding_was_recorded() {
let mut host = Host::new(IP_ADDR);
for i in 0..MAX_PORTS_PER_HOST {
assert!(host.add_port(Port::new(i as u16, Protocol::Tcp, PortState::Open)));
}
assert!(!host.add_port(Port::new(9999, Protocol::Tcp, PortState::Open)));
assert!(host.network_roles().contains(&NetworkRole::Tarpit));
}
#[test]
fn the_tarpit_marking_appears_only_once_a_port_is_refused() {
let mut host = Host::new(IP_ADDR);
for i in 0..MAX_PORTS_PER_HOST {
host.add_port(Port::new(i as u16, Protocol::Tcp, PortState::Open));
}
assert!(!host.network_roles.contains(&NetworkRole::Tarpit));
host.add_port(Port::new(9999, Protocol::Tcp, PortState::Open));
assert!(host.network_roles.contains(&NetworkRole::Tarpit));
assert_eq!(host.port_count(), MAX_PORTS_PER_HOST);
}
#[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 merge_tarpit_collision_test() {
let mut h1 = Host::new(IP_ADDR);
for i in 0..600 {
h1.add_port(Port::new(i, Protocol::Tcp, PortState::Open));
}
let mut h2 = Host::new(IP_ADDR);
for i in 500..1100 {
h2.add_port(Port::new(i, Protocol::Tcp, PortState::Open));
}
h1.merge(h2);
assert_eq!(h1.port_count(), MAX_PORTS_PER_HOST);
assert!(h1.network_roles.contains(&NetworkRole::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"
);
}
}