zond_engine/model/host.rs
1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Hosts
10//!
11//! A [`Host`] is everything a scan learned about a single device, filled in piece by
12//! piece: an ARP reply establishes it is there and gives it a MAC, a neighbour
13//! solicitation adds an IPv6 address, a port scan adds ports, and service detection
14//! names what is behind them, in no fixed order.
15//!
16//! So the type accumulates evidence under one rule: later is not better. Status is
17//! promoted and never lowered ([`Host::record_evidence`]). The reported address is
18//! ranked ([`Host::consider_primary_ip`]). MACs accumulate ([`Host::record_mac`]).
19//! Between equally good findings, the one already recorded wins. The one exception is
20//! [`Host::set_hostname`].
21//!
22//! This keeps a report independent of which probe finished last. [`Host::merge`]
23//! applies the same rules between two records of one host, so folding one phase into
24//! another gives what a single phase would.
25
26use crate::model::finding::{ClaimId, Finding, MAX_FINDINGS_PER_SUBJECT};
27use crate::model::ip::scoped::{ScopedIp, Zone};
28use crate::model::mac::MacAddr;
29use crate::model::port::{Port, PortSet, PortState, Protocol};
30use std::{
31 collections::{BTreeMap, BTreeSet, HashSet},
32 net::IpAddr,
33 time::SystemTime,
34};
35
36pub mod hardware;
37pub mod name;
38pub mod os;
39pub mod path;
40pub mod protocol;
41pub mod status;
42pub mod telemetry;
43
44/// How many times this thread has read a host's addresses, for a test that has
45/// to know a walk over a report read them only where it needed to.
46///
47/// Counted per thread, so the tests running beside one never move its count.
48#[cfg(test)]
49pub(crate) mod address_reads {
50 use std::cell::Cell;
51
52 thread_local! {
53 static READS: Cell<usize> = const { Cell::new(0) };
54 }
55
56 /// Counts one read.
57 pub(super) fn note() {
58 READS.with(|reads| reads.set(reads.get() + 1));
59 }
60
61 /// How many reads this thread has made.
62 pub(crate) fn so_far() -> usize {
63 READS.with(Cell::get)
64 }
65}
66
67pub use hardware::{HardwareDescription, HardwareInfo};
68pub use name::{HostName, NameKind, NameSource};
69pub use os::{OsEvidence, OsFingerprint, OsSource};
70pub use path::{Hop, NetworkPath};
71pub use protocol::{IpProtocolState, ip_protocol_name};
72pub use status::{EvidenceSource, HostStatus, StatusProtocol, StatusReason};
73pub use telemetry::HostTelemetry;
74
75/// The most ports one host will have recorded against it.
76///
77/// Every endpoint this build can probe: one whole port space for each transport in
78/// [`Protocol::ALL`], so a new transport widens it.
79///
80/// Anything lower would truncate a scan somebody asked for: `1-1024` on a host that
81/// answers records a thousand ports, closed ones included, and `1-65535,u:1-65535` is
82/// one specification covering two port spaces.
83///
84/// A host that reaches it is marked [`NetworkRole::Truncated`] and further ports are
85/// dropped. **No scan can reach it**, since the map's key space is exactly this size;
86/// the check guards against a `Protocol` variant missing from [`Protocol::ALL`].
87///
88/// The key space is what bounds allocation per target. [`NetworkRole::Tarpit`] is the
89/// separate claim about the host.
90pub const MAX_PORTS_PER_HOST: usize = (u16::MAX as usize + 1) * Protocol::ALL.len();
91
92/// How many **open** ports make a host implausible as a host.
93///
94/// No machine runs a thousand listening services. A tarpit answering every SYN, or a
95/// middlebox doing it by accident, does, and every port it reports is a finding nobody
96/// should act on.
97///
98/// Counts open ports only: sixty thousand *closed* ports is the ordinary result of a
99/// wide scan against a live machine.
100pub const TARPIT_OPEN_PORTS: usize = 1_000;
101
102/// What a host turned out to be, beyond an address with ports on it.
103///
104/// Most variants name a function the network depends on (forwarding, naming,
105/// addressing); the last three are claims about the record. A reader can act on either
106/// without reading anything else about the host.
107///
108/// A role is never a port number restated: an open port 80 is
109/// [`Port::service`](crate::model::port::Port::service), which carries a confidence.
110/// Every role is concluded from evidence in its own protocol (an advertisement that
111/// says it forwards, a DNS message that parses as a response, a DHCP server naming
112/// itself), so it needs no confidence of its own.
113///
114/// A variant nothing assigns yet says so in its documentation, since an empty `roles`
115/// array would otherwise read as "checked, none".
116///
117/// [`ALL`](Self::ALL) is the list to iterate.
118#[non_exhaustive]
119#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
120pub enum NetworkRole {
121 /// Forwards traffic on behalf of other hosts.
122 ///
123 /// Three independent proofs, since no one of them covers a whole network:
124 ///
125 /// 1. A **neighbour advertisement with the R flag** set (RFC 4861 ยง4.4).
126 /// The host is answering an ordinary discovery probe and saying, in the
127 /// same message, that it routes.
128 /// 2. A **router advertisement** (ICMPv6 type 134), sent unprompted every few
129 /// minutes while a segment sweep is listening.
130 /// 3. **This machine's own routing table.** The address is a default gateway of
131 /// an interface the scan runs on. The only proof on an IPv4-only segment.
132 ///
133 /// Not called a gateway: a gateway is somebody's next hop, which is relational.
134 /// These proofs establish only that the box forwards.
135 Router,
136
137 /// Answered a query on port 53 with a message that parses as a DNS
138 /// response.
139 ///
140 /// The reply is the evidence, not the open port. The engine's UDP probe for port 53
141 /// carries a real question, so a resolver ordinarily answers.
142 ///
143 /// mDNS and LLMNR (5353, 5355) do not count: nearly every laptop and printer
144 /// answers them.
145 DnsServer,
146
147 /// Answered a DHCP message as a server.
148 ///
149 /// The engine sends a `DHCPINFORM`, which asks for configuration without asking for
150 /// an address, and reads the server identifier (option 54) from the reply. The role
151 /// goes on that address only when the reply also came from it; behind a relay agent
152 /// the two differ.
153 ///
154 /// Port state cannot show it: UDP/67 is `OpenOrNoReply` on silence like any UDP
155 /// port.
156 DhcpServer,
157
158 /// Answered with a valid NTP response, so it serves time.
159 ///
160 /// Nothing assigns this yet: the probe for port 123 goes out, but the reply is not
161 /// yet read as NTP.
162 NtpServer,
163
164 /// Answered SNMP, so it is managed over it.
165 ///
166 /// Nothing assigns this yet: the reply to the probe for port 161 is parsed for
167 /// operating-system evidence, but no strategy concludes the role from it.
168 SnmpAgent,
169
170 /// Answered a NetBIOS node-status request with a name table holding a
171 /// suffix only a domain controller registers.
172 ///
173 /// `<1C>` is registered as a group name by every controller in a domain and nothing
174 /// else, and `<1B>` as a unique name by the domain master browser. Either identifies
175 /// the machine from one unauthenticated datagram.
176 ///
177 /// The reply is the evidence, as for [`DnsServer`](Self::DnsServer). A role because
178 /// it is a fact about the machine, which also speaks SMB, LDAP and Kerberos as
179 /// separate services.
180 ///
181 /// `<20>` (the server service) and `<00>` (every NetBIOS host) do not count.
182 DomainController,
183
184 /// Switches frames on behalf of the machines attached to it.
185 ///
186 /// Concluded from the device's own announcement (LLDP's bridge capability, or CDP's
187 /// switch, transparent-bridge or source-route-bridge bits), and only where the
188 /// capability is *enabled*. A switch with an unconfigured routing licence advertises
189 /// routing as supported but not enabled; reading the wrong half would put a router
190 /// on every access switch.
191 ///
192 /// Testimony, like [`DhcpServer`](Self::DhcpServer), where [`Router`](Self::Router)
193 /// and [`DnsServer`](Self::DnsServer) are observed behaviour. Anything on a segment
194 /// can send either, so neither is evidence about a distant machine; see
195 /// [`crate::protocols::lldp`].
196 ///
197 /// Still worth having: a switch usually presents no open port and often holds no
198 /// address, so a scan otherwise cannot see it.
199 Switch,
200
201 /// The machine this scan is running from.
202 ///
203 /// A sweep of the scanner's own segment reaches it, and its record is unusual:
204 /// services answer over loopback, latency is not a network measurement, and no
205 /// probe crossed a wire.
206 ///
207 /// Read from this machine's interface addresses, without sending anything.
208 Origin,
209
210 /// Reported more ports **open** than any machine plausibly runs services on.
211 ///
212 /// Past [`TARPIT_OPEN_PORTS`] the host is answering everything, so its open ports
213 /// are not findings to act on. A deliberate tarpit and a middlebox answering by
214 /// accident look the same from here.
215 Tarpit,
216
217 /// Answered on more ports than this record will hold, so the port list is
218 /// incomplete.
219 ///
220 /// A claim about the *scan*: [`MAX_PORTS_PER_HOST`] was reached and later ports were
221 /// dropped. Separate from [`Tarpit`](Self::Tarpit), which is about the host.
222 ///
223 /// No scan this build can run assigns it; see [`MAX_PORTS_PER_HOST`].
224 Truncated,
225}
226
227impl NetworkRole {
228 /// How a role is written for a person to read.
229 ///
230 /// Separate from [`network_role_name`](crate::record::wire::network_role_name), the
231 /// wire spelling: this may be reworded, that may not.
232 ///
233 /// Acronyms are capitals and words are not, so a list reads `router, DNS, DHCP`.
234 pub const fn label(self) -> &'static str {
235 match self {
236 Self::Router => "router",
237 Self::DnsServer => "DNS",
238 Self::DhcpServer => "DHCP",
239 Self::NtpServer => "NTP",
240 Self::SnmpAgent => "SNMP",
241 // One token: roles are drawn into a space-separated list.
242 Self::DomainController => "domain-controller",
243 Self::Switch => "switch",
244 Self::Origin => "origin",
245 Self::Tarpit => "tarpit",
246 Self::Truncated => "truncated",
247 }
248 }
249
250 /// Every role this build knows, in declaration order, which is the order
251 /// [`label`](Self::label) spells them in.
252 ///
253 /// Every round trip through [`wire`](crate::record::wire) is tested over this, so a
254 /// new variant fails those tests until it is spelled everywhere.
255 pub const ALL: &'static [Self] = &[
256 Self::Router,
257 Self::DnsServer,
258 Self::DhcpServer,
259 Self::NtpServer,
260 Self::SnmpAgent,
261 Self::DomainController,
262 Self::Switch,
263 Self::Origin,
264 Self::Tarpit,
265 Self::Truncated,
266 ];
267}
268
269/// What the filter in front of a host was shown to be doing.
270///
271/// A conclusion about the *path to* a host, so separate from [`NetworkRole`]. Like a
272/// role, each member is a proven fact, drawn from what a shaped probe demonstrated.
273///
274/// Positive claims only: the absence of a filter cannot be established.
275#[non_exhaustive]
276#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
277pub enum Filtering {
278 /// An inline device answered on the host's behalf.
279 ///
280 /// Proven by a reply to a probe with a wrong TCP checksum. A conformant host drops
281 /// such a segment unread, so the reply came from something in the path that did not
282 /// validate: a firewall, an IPS, a transparent proxy, a load balancer. One reply is
283 /// proof.
284 InlineMiddlebox,
285
286 /// A stateful filter: it passes a bare ACK but drops a SYN.
287 ///
288 /// Proven by an ACK probe drawing a RST ([`PortState::Reachable`]) from a port a SYN
289 /// did not reach: the filter keeps connection state and admits no new connections.
290 /// The SYN's fate is the port state already recorded; only the ACK is sent.
291 StatefulFilter,
292
293 /// A filter that trusts a source port.
294 ///
295 /// Proven by a SYN from a port such as 53, 20 or 88 reaching a port a SYN from an
296 /// ephemeral port did not: an ACL written to let return traffic in. Compared
297 /// against recorded port state, like [`StatefulFilter`](Self::StatefulFilter).
298 PortTrustingAcl,
299
300 /// A stateless filter: it matches on the first fragment and passes the rest.
301 ///
302 /// Proven by a *fragmented* SYN drawing an answer from a port a whole SYN did not
303 /// reach: the filter judged only the first fragment, which holds the ports but not
304 /// the flags, and does not reassemble. Compared against recorded port state, like
305 /// [`StatefulFilter`](Self::StatefulFilter). Fragmented probes need a self-built
306 /// Ethernet frame, so only hosts that path reaches are tested.
307 StatelessFilter,
308}
309
310impl Filtering {
311 /// Every conclusion this build knows, in declaration order, which is the
312 /// order they are reported in.
313 ///
314 /// Sets are rendered in this order and the exported schema is built from it, so a
315 /// conclusion missing here would vanish on the way to the report. A variant without
316 /// a wire name in [`record::wire`](crate::record::wire) fails to compile, and that
317 /// round trip is driven by this list; `model`'s test holds the order.
318 pub const ALL: &'static [Self] = &[
319 Self::InlineMiddlebox,
320 Self::StatefulFilter,
321 Self::PortTrustingAcl,
322 Self::StatelessFilter,
323 ];
324}
325
326/// What one source concluded, reduced to the parts that make it a *distinct*
327/// claim.
328///
329/// Two readings saying the same thing are one claim, whatever produced them; two saying
330/// different things are two, even from one kind of source.
331///
332/// Excludes the confidence (which varies with rule weighting) and the evidence line
333/// (prose), so one claim cannot enter under several spellings.
334type OsClaim = (
335 OsSource,
336 Option<String>,
337 Option<String>,
338 Option<String>,
339 Option<String>,
340 Option<String>,
341 Option<String>,
342);
343
344/// The most distinct operating-system claims one host retains.
345///
346/// A host running many identifiable services can offer one claim each, and enough of
347/// them combined approach a certainty none stated. Eight is above any host seen so far.
348const MAX_OS_EVIDENCE: usize = 8;
349
350/// The most names one host will have recorded against it.
351///
352/// A host states at most five names over NTLM, three over LDAP, a realm over Kerberos,
353/// a domain over SMB1 and two in its NetBIOS table, the same way every time, so only a
354/// peer inventing names per connection reaches this. Past it, new names are turned away
355/// and held ones stay.
356const MAX_NAMES: usize = 16;
357
358/// The most addresses one host will have recorded against it.
359///
360/// A machine holds an IPv4 address or two, a global IPv6 address per prefix and a
361/// temporary one for each day it is up, and a proxy-ARP router answers for a subnet, so
362/// only a sender inventing source addresses reaches this. Past it, a new address is
363/// turned away unless it [ranks](Host::consider_primary_ip) above one held, which it
364/// displaces, so a flood of link-locals cannot keep out the address a person would use.
365const MAX_IPS: usize = 1024;
366
367/// The most names one host will hold [set aside](Host::set_aside_names).
368///
369/// Above [`MAX_NAMES`], since a fold sets aside every name a record knew the host by
370/// that it does not keep. Only a peer naming itself afresh each time reaches it; past
371/// it, a new name is turned away, and redaction cannot mask it in folded-in text.
372const MAX_SET_ASIDE_NAMES: usize = 64;
373
374/// A single machine, and what a scan established about it.
375///
376/// Identity first: the addresses it answers at, its name and its hardware. Then
377/// what was found on it.
378///
379/// A host holds every address it is known by: a dual-stack machine answering at three
380/// is one device. See [`consider_primary_ip`](Self::consider_primary_ip) for which
381/// address leads.
382#[must_use]
383#[derive(Debug, Clone)]
384pub struct Host {
385 /// The primary IP address used to target or identify this host.
386 primary_ip: IpAddr,
387
388 /// All known IP addresses for this host (multi-homed support). Bounded by
389 /// [`MAX_IPS`].
390 ips: BTreeSet<IpAddr>,
391
392 /// The resolved hostname (FQDN or local network name).
393 hostname: Option<String>,
394
395 /// The names the host gave for itself through its own services, each with the
396 /// protocol it was given in. Separate from [`hostname`](Self::hostname); see
397 /// [`name`]. Bounded by [`MAX_NAMES`].
398 names: BTreeSet<HostName>,
399
400 /// Names this record's text may contain without stating them as names: names a
401 /// folded-in record knew the host by that the fold did not keep, such as a renamed
402 /// machine's former name or one the ceiling turned away.
403 ///
404 /// For redaction only, which masks them in that text. Nothing exports, compares
405 /// or writes them. Bounded by [`MAX_SET_ASIDE_NAMES`].
406 set_aside_names: BTreeSet<String>,
407
408 /// The current reachability status.
409 status: HostStatus,
410
411 /// Aggregated evidence explaining the current reachability status.
412 reasons: HashSet<StatusReason>,
413
414 /// Identified operating system metadata.
415 ///
416 /// Boxed: [`OsFingerprint`] is large and most hosts never get one.
417 os: Option<Box<OsFingerprint>>,
418
419 /// What each source concluded about this host's operating system, kept so a later
420 /// source can **corroborate** an earlier one.
421 ///
422 /// Independent sources agreeing on a family are worth more than either; see
423 /// [`resolve`](crate::fingerprint::os::resolve). Keeping only the resulting
424 /// [`OsFingerprint`] would discard a later banner that scores lower on its own,
425 /// along with the release only it could name.
426 ///
427 /// One item per distinct claim, not per source: an SSH banner naming `Debian 12`
428 /// and an SNMP agent naming `kernel 6.1.0` are both `ServiceBanner` but two claims,
429 /// while a stack read forty times (forty open ports) is one. Repeating an
430 /// observation must never look like corroboration.
431 ///
432 /// Bounded by [`MAX_OS_EVIDENCE`].
433 os_evidence: BTreeMap<OsClaim, OsEvidence>,
434
435 /// Physical hardware (MAC) and vendor information.
436 hardware: Option<HardwareInfo>,
437
438 /// The interface this host was observed through, when one is known.
439 ///
440 /// Recorded by the link-layer strategies, the only ones that know it.
441 ///
442 /// An IPv6 link-local address needs it: `fe80::1` names a different machine on
443 /// every segment, and a socket to one needs the interface's scope id. See
444 /// [`ScopedIp`].
445 zone: Option<Zone>,
446
447 /// Network performance and path telemetry.
448 telemetry: HostTelemetry,
449
450 /// The routers between this machine and this host, when a trace ran.
451 ///
452 /// Empty unless a trace was asked for; see
453 /// [`ZondConfig::traceroute`](crate::config::ZondConfig::traceroute).
454 ///
455 /// Not part of [`HostTelemetry`]: a path is a sequence of findings about *other*
456 /// machines, each with its own provenance.
457 path: NetworkPath,
458
459 /// Inferred roles based on network location or discovered services.
460 network_roles: HashSet<NetworkRole>,
461
462 /// What the filter in front of this host was shown to be doing, if anything.
463 filtering: HashSet<Filtering>,
464
465 /// Which IP protocols the host's stack was shown to take delivery of.
466 ///
467 /// Empty unless a scan asked; see
468 /// [`ZondConfig::ip_protocols`](crate::config::ZondConfig::ip_protocols). A protocol
469 /// number is not a port; see [`protocol`].
470 ip_protocols: BTreeMap<u8, IpProtocolState>,
471
472 /// What a detection concluded was wrong with this host, keyed on the claim so
473 /// that the same finding reached twice records once.
474 ///
475 /// Host-level findings are cross-cutting: a weakness inferred from several ports,
476 /// or a correlation over the whole host. Per-port findings are on [`Port`]. Bounded
477 /// by [`MAX_FINDINGS_PER_SUBJECT`], and keyed so a detection re-firing corroborates.
478 findings: BTreeMap<ClaimId, Finding>,
479
480 /// The timestamp of the first discovery event for this host.
481 first_seen: SystemTime,
482
483 /// The timestamp of the most recent discovery or update event.
484 last_seen: SystemTime,
485
486 /// The ports found on this host, in a stable order, bounded by
487 /// [`MAX_PORTS_PER_HOST`].
488 ///
489 /// Keyed on number and protocol, since a number names one endpoint per transport
490 /// and the TCP and UDP scanners report independently. Ordered by number first, so
491 /// both transports of one number are adjacent.
492 ports: BTreeMap<(u16, Protocol), Port>,
493
494 /// How many of [`ports`](Self::ports) are [`PortState::Open`], maintained as
495 /// they are recorded.
496 ///
497 /// [`add_port`](Self::add_port) is the only way a port enters or changes, and port
498 /// state only promotes, so the count is kept incrementally; counting on demand
499 /// would be quadratic on a wide scan.
500 open_ports: usize,
501
502 /// The ports recorded or given a finding since
503 /// [`take_touched_ports`](Self::take_touched_ports) last emptied this.
504 ///
505 /// Lets a journal write down only what changed: a host scanned on every port holds
506 /// tens of thousands, and a pass may touch a few. [`add_port`](Self::add_port) and
507 /// [`add_port_finding`](Self::add_port_finding) are the only ways a port changes,
508 /// so this sees every change.
509 ///
510 /// Bookkeeping, never written or read back. `None` until
511 /// [`track_touched_ports`](Self::track_touched_ports) asks for it, which a scan's
512 /// store does for its hosts.
513 touched: Option<BTreeSet<(u16, Protocol)>>,
514}
515
516/// How well an address identifies the host holding it: lower leads.
517///
518/// The ordering behind [`Host::consider_primary_ip`].
519///
520/// Rank 1 is globally scoped: [`is_global_unicast`](crate::model::ip::is_global_unicast)
521/// or unique-local, tested directly, since "not link-local" would also admit loopback,
522/// multicast and the unspecified address.
523fn identity_rank(ip: &IpAddr) -> u8 {
524 match ip {
525 IpAddr::V4(_) => 0,
526 IpAddr::V6(v6) if crate::model::ip::is_globally_scoped(v6) => 1,
527 IpAddr::V6(_) => 2,
528 }
529}
530
531impl Host {
532 /// Creates a new `Host` centered around a primary IP address.
533 ///
534 /// The initial status is always [`HostStatus::Unknown`].
535 pub fn new(primary_ip: IpAddr) -> Self {
536 let mut ips = BTreeSet::new();
537 ips.insert(primary_ip);
538 let now = SystemTime::now();
539
540 Self {
541 primary_ip,
542 ips,
543 hostname: None,
544 names: BTreeSet::new(),
545 set_aside_names: BTreeSet::new(),
546 status: HostStatus::Unknown,
547 reasons: HashSet::new(),
548 os: None,
549 os_evidence: BTreeMap::new(),
550 hardware: None,
551 zone: None,
552 telemetry: HostTelemetry::default(),
553 path: NetworkPath::new(),
554 network_roles: HashSet::new(),
555 filtering: HashSet::new(),
556 ip_protocols: BTreeMap::new(),
557 findings: BTreeMap::new(),
558 first_seen: now,
559 last_seen: now,
560 ports: BTreeMap::new(),
561 open_ports: 0,
562 touched: None,
563 }
564 }
565
566 /// Returns the primary IP address for this host.
567 pub fn primary_ip(&self) -> IpAddr {
568 self.primary_ip
569 }
570
571 /// Returns all known IP addresses for this host.
572 pub fn ips(&self) -> &BTreeSet<IpAddr> {
573 #[cfg(test)]
574 address_reads::note();
575 &self.ips
576 }
577
578 /// Returns the resolved hostname, if any.
579 ///
580 /// What name resolution answered for the address, and the name a host is displayed
581 /// under. The names a host gives for itself are [`names`](Self::names); see
582 /// [`name`].
583 ///
584 /// As the network stated it, so it can hold control characters. Untrusted; escape
585 /// before display.
586 pub fn hostname(&self) -> Option<&str> {
587 self.hostname.as_deref()
588 }
589
590 /// The names this host gave for itself, the machine's before its domain's.
591 pub fn names(&self) -> impl Iterator<Item = &HostName> {
592 self.names.iter()
593 }
594
595 /// Returns the current reachability status.
596 pub fn status(&self) -> HostStatus {
597 self.status
598 }
599
600 /// Returns all aggregated evidence for the current status.
601 pub fn reasons(&self) -> &HashSet<StatusReason> {
602 &self.reasons
603 }
604
605 /// Returns the identified operating system, if any.
606 pub fn os(&self) -> Option<&OsFingerprint> {
607 self.os.as_deref()
608 }
609
610 /// Returns physical hardware information, if any.
611 pub fn hardware(&self) -> Option<&HardwareInfo> {
612 self.hardware.as_ref()
613 }
614
615 /// Returns the interface this host was observed through, if known.
616 pub fn zone(&self) -> Option<&Zone> {
617 self.zone.as_ref()
618 }
619
620 /// Records the interface this host was observed through.
621 ///
622 /// Only the first is kept, so the result does not depend on which strategy
623 /// finished last.
624 pub fn set_zone(&mut self, zone: Zone) {
625 self.zone.get_or_insert(zone);
626 self.last_seen = SystemTime::now();
627 }
628
629 /// This host's primary address, carrying the interface it is valid on.
630 ///
631 /// The address to use to *reach* the host: [`ScopedIp::to_socket_addr`] refuses to
632 /// build a socket address that cannot be connected to.
633 pub fn scoped_ip(&self) -> ScopedIp {
634 match &self.zone {
635 Some(zone) => ScopedIp::scoped(self.primary_ip, zone.clone()),
636 None => ScopedIp::unscoped(self.primary_ip),
637 }
638 }
639
640 /// Returns network performance and path telemetry.
641 pub fn telemetry(&self) -> &HostTelemetry {
642 &self.telemetry
643 }
644
645 /// The routers between this machine and this host. Empty unless a trace ran.
646 pub fn path(&self) -> &NetworkPath {
647 &self.path
648 }
649
650 /// Records the hop counter a reply from this host arrived with.
651 ///
652 /// Every captured reply carries one, so keeping it saves a later probe.
653 pub fn record_hop_counter(&mut self, arrived: u8) {
654 self.telemetry.record_hop_counter(arrived);
655 }
656
657 /// Records one router on the way here.
658 ///
659 /// Additive and idempotent, as [`NetworkPath::record`] describes, so replies out of
660 /// order or twice converge on the same path.
661 pub fn record_hop(&mut self, hop: Hop) {
662 self.path.record(hop);
663 self.last_seen = SystemTime::now();
664 }
665
666 /// Returns inferred roles based on network location or discovered services.
667 pub fn network_roles(&self) -> &HashSet<NetworkRole> {
668 &self.network_roles
669 }
670
671 /// What the filter in front of this host was shown to be doing.
672 pub fn filtering(&self) -> &HashSet<Filtering> {
673 &self.filtering
674 }
675
676 /// What a scan concluded about each IP protocol it asked this host about,
677 /// ascending by number.
678 ///
679 /// Empty for a scan that did not ask. A protocol at [`IpProtocolState::Unasked`]
680 /// was named but not reached.
681 pub fn ip_protocols(&self) -> &BTreeMap<u8, IpProtocolState> {
682 &self.ip_protocols
683 }
684
685 /// Returns the timestamp of the first discovery event.
686 pub fn first_seen(&self) -> SystemTime {
687 self.first_seen
688 }
689
690 /// Returns the timestamp of the most recent discovery or update event.
691 pub fn last_seen(&self) -> SystemTime {
692 self.last_seen
693 }
694
695 /// Restores the times this host was first and last seen.
696 ///
697 /// For a host rebuilt from a record, whose times [`new`](Self::new) would otherwise
698 /// stamp as now.
699 ///
700 /// Swapped if `first_seen` is after `last_seen`.
701 pub fn restore_seen(&mut self, first_seen: SystemTime, last_seen: SystemTime) {
702 let (first_seen, last_seen) = if first_seen <= last_seen {
703 (first_seen, last_seen)
704 } else {
705 (last_seen, first_seen)
706 };
707 self.first_seen = first_seen;
708 self.last_seen = last_seen;
709 }
710
711 /// Offers `candidate` as the address this host is reported under, taking it
712 /// only if it identifies the host better than the current one.
713 ///
714 /// Returns whether the primary address changed.
715 ///
716 /// A dual-stack host answers at several addresses. Left to whichever probe replied
717 /// first, the same machine would be reported under different addresses on
718 /// different runs, which in an inventory looks like two devices. So addresses are
719 /// ranked, and the ranking only moves upward:
720 ///
721 /// 1. **IPv4**, because it is what a person recognises and types.
722 /// 2. **Globally scoped IPv6** (global unicast or unique-local), usable from
723 /// anywhere.
724 /// 3. **Link-local IPv6**, meaningless without the zone
725 /// [`scoped_ip`](Self::scoped_ip) supplies.
726 ///
727 /// Ties keep the incumbent. Every address stays in [`ips`](Self::ips); this only
728 /// decides which leads.
729 pub fn consider_primary_ip(&mut self, candidate: IpAddr) -> bool {
730 self.add_ip(candidate);
731
732 // Turned away at the ceiling, so it cannot lead.
733 if !self.ips.contains(&candidate) {
734 return false;
735 }
736 if identity_rank(&candidate) >= identity_rank(&self.primary_ip) {
737 return false;
738 }
739
740 self.primary_ip = candidate;
741 self.last_seen = SystemTime::now();
742 true
743 }
744
745 /// Adds a new IP address to the host's record and bumps `last_seen`.
746 /// Returns `true` if the IP was newly added.
747 ///
748 /// Past a ceiling of 1024 addresses, a new one is turned away unless it ranks above
749 /// one held, as [`consider_primary_ip`](Self::consider_primary_ip) ranks them.
750 pub fn add_ip(&mut self, ip: IpAddr) -> bool {
751 let is_new = self.admit_ip(ip);
752 self.last_seen = SystemTime::now();
753 is_new
754 }
755
756 /// Adds multiple IP addresses to the host's record and bumps `last_seen`.
757 ///
758 /// Each is admitted as [`add_ip`](Self::add_ip) admits it.
759 pub fn extend_ips(&mut self, ips: impl IntoIterator<Item = IpAddr>) {
760 for ip in ips {
761 self.admit_ip(ip);
762 }
763 self.last_seen = SystemTime::now();
764 }
765
766 /// Records `ip` unless [`MAX_IPS`] turns it away, returning whether it is new.
767 ///
768 /// At the ceiling it displaces the lowest-ranked address held other than the
769 /// primary, if it ranks above that one.
770 fn admit_ip(&mut self, ip: IpAddr) -> bool {
771 if self.ips.len() < MAX_IPS || self.ips.contains(&ip) {
772 return self.ips.insert(ip);
773 }
774 let lowest = self
775 .ips
776 .iter()
777 .copied()
778 .filter(|held| *held != self.primary_ip)
779 .max_by_key(identity_rank);
780 match lowest {
781 Some(lowest) if identity_rank(&lowest) > identity_rank(&ip) => {
782 self.ips.remove(&lowest);
783 self.ips.insert(ip)
784 }
785 _ => false,
786 }
787 }
788
789 /// Joins `ips`, a set built elsewhere, to the host's addresses, leaving
790 /// `last_seen` where it is.
791 ///
792 /// For a reader that parsed a document's address list into a set, so the host holds
793 /// that set and the document's timestamps stand.
794 #[cfg(feature = "import-json")]
795 pub(crate) fn adopt_ips(&mut self, ips: BTreeSet<IpAddr>) {
796 for ip in ips {
797 self.admit_ip(ip);
798 }
799 }
800
801 /// Drops every address `keep` refuses, and returns whether any is left.
802 ///
803 /// For the exclusion policy, which covers every address a host is known by. A
804 /// refused primary is replaced by the best remaining address, ranked as in
805 /// [`consider_primary_ip`](Self::consider_primary_ip).
806 ///
807 /// If every address is refused the host is left as it was and this returns
808 /// `false`; the caller decides what to do with it.
809 pub(crate) fn retain_ips(&mut self, keep: impl Fn(&IpAddr) -> bool) -> bool {
810 if self.ips.iter().all(&keep) {
811 return true;
812 }
813 let kept: BTreeSet<IpAddr> = self.ips.iter().copied().filter(&keep).collect();
814 let Some(best) = kept.iter().copied().min_by_key(identity_rank) else {
815 return false;
816 };
817 if !kept.contains(&self.primary_ip) {
818 self.primary_ip = best;
819 }
820 self.ips = kept;
821 true
822 }
823
824 /// Withholds the address of every router or middlebox this host's record
825 /// names that `keep` refuses, and returns whether it withheld any.
826 ///
827 /// The exclusion policy's other half beside [`retain_ips`](Self::retain_ips). A
828 /// refused intermediary goes unnamed but its finding stays, since it is a fact
829 /// about this host: a router on the path keeps its distance ([`Hop::withheld`]),
830 /// and the sender of second-hand evidence keeps its reason
831 /// ([`EvidenceSource::Withheld`]).
832 pub(crate) fn withhold_intermediaries(&mut self, keep: impl Fn(&IpAddr) -> bool) -> bool {
833 let routers = self.path.withhold(&keep);
834
835 // A reason is its own hash key, so one whose sender changes is taken out
836 // and put back. Checked first because this runs on every finding and
837 // nothing usually needs to move.
838 let refused = |reason: &StatusReason| {
839 reason
840 .source
841 .address()
842 .is_some_and(|address| !keep(&address))
843 };
844 let senders = self.reasons.iter().any(refused);
845 if senders {
846 self.reasons = std::mem::take(&mut self.reasons)
847 .into_iter()
848 .map(|mut reason| {
849 reason.source.withhold(&keep);
850 reason
851 })
852 .collect();
853 }
854
855 routers || senders
856 }
857
858 /// Drops every port of this record that `ports` holds.
859 ///
860 /// For a record restored into a sitting that excludes those ports; kept, a port
861 /// would be handed to every later pass, which would connect to it.
862 pub(crate) fn withhold_ports(&mut self, ports: &PortSet) {
863 if ports.is_empty() {
864 return;
865 }
866 self.ports
867 .retain(|&(number, protocol), _| !ports.contains(number, protocol));
868 self.open_ports = self
869 .ports
870 .values()
871 .filter(|port| port.state() == PortState::Open)
872 .count();
873 }
874
875 /// Records the name this host resolved to, replacing any already recorded.
876 ///
877 /// The one field that is overwritten: a hostname has no ordering that says which
878 /// answer knows more, and `None` clears the name. [`merge`](Self::merge) keeps the
879 /// incumbent instead.
880 pub fn set_hostname(&mut self, hostname: Option<String>) {
881 self.hostname = hostname;
882 self.last_seen = SystemTime::now();
883 }
884
885 /// Records a name the host gave for itself, returning whether it is one not
886 /// already held.
887 ///
888 /// Accumulates: two services stating different names are two claims. Past a ceiling
889 /// of sixteen names, a new one is turned away. Bumps `last_seen` either way.
890 pub fn record_name(&mut self, name: HostName) -> bool {
891 self.last_seen = SystemTime::now();
892 self.admit_name(name).unwrap_or(false)
893 }
894
895 /// Records `name` unless the ceiling turns it away, returning whether it
896 /// is new, or handing it back when it was turned away.
897 fn admit_name(&mut self, name: HostName) -> Result<bool, HostName> {
898 if self.names.len() >= MAX_NAMES && !self.names.contains(&name) {
899 return Err(name);
900 }
901 Ok(self.names.insert(name))
902 }
903
904 /// The names this record's text may hold without stating them as names,
905 /// which a fold of the host's records set aside, for redaction to mask
906 /// there too.
907 pub(crate) fn set_aside_names(&self) -> impl Iterator<Item = &str> {
908 self.set_aside_names.iter().map(String::as_str)
909 }
910
911 /// Sets aside every name `account`, another record of this host whose text
912 /// a fold keeps, knew the host by and this record does not state.
913 pub(crate) fn set_aside_names_of(&mut self, account: &Host) {
914 for name in account
915 .hostname()
916 .into_iter()
917 .chain(account.names().map(HostName::name))
918 .chain(account.set_aside_names())
919 {
920 self.set_aside(name);
921 }
922 }
923
924 /// Sets `name` aside, unless this record states it or [`MAX_SET_ASIDE_NAMES`]
925 /// turns it away.
926 fn set_aside(&mut self, name: &str) {
927 let stated = self.hostname.as_deref() == Some(name)
928 || self.names.iter().any(|held| held.name() == name);
929 if !stated
930 && self.set_aside_names.len() < MAX_SET_ASIDE_NAMES
931 && !self.set_aside_names.contains(name)
932 {
933 self.set_aside_names.insert(name.to_owned());
934 }
935 }
936
937 /// Raises the reachability status to `status`, if that is an improvement.
938 ///
939 /// Promotes and never lowers, like [`record_evidence`](Self::record_evidence). For a
940 /// caller with no [`StatusReason`]; otherwise prefer `record_evidence`, which keeps
941 /// the audit trail.
942 pub fn set_status(&mut self, status: HostStatus) {
943 if status > self.status {
944 self.status = status;
945 }
946 self.last_seen = SystemTime::now();
947 }
948
949 /// Adds a status reason and bumps `last_seen`.
950 pub fn add_reason(&mut self, reason: StatusReason) {
951 self.reasons.insert(reason);
952 self.last_seen = SystemTime::now();
953 }
954
955 /// Records one piece of liveness evidence: the status it establishes, and
956 /// the reason it establishes it.
957 ///
958 /// How a scanner reports what it saw: verdict and evidence together.
959 /// ([`set_status`](Self::set_status) and [`add_reason`](Self::add_reason) do each
960 /// half separately.) The status is **promoted, never lowered**, on the ordering of
961 /// [`HostStatus`], as [`Host::merge`](Host::merge) does too: an ICMP unreachable
962 /// from a router landing after an ARP reply must not overwrite proof the host
963 /// answered.
964 ///
965 /// The reason is kept whether or not the status moved, so an `Up` host still gains
966 /// the audit trail.
967 ///
968 /// Callers must only pass evidence backed by a received packet. Silence is
969 /// not evidence and has no status to record; see [`HostStatus::Unknown`].
970 pub fn record_evidence(&mut self, status: HostStatus, reason: StatusReason) {
971 if status > self.status {
972 self.status = status;
973 }
974 self.reasons.insert(reason);
975 self.last_seen = SystemTime::now();
976 }
977
978 /// What each source has concluded about this host's operating system.
979 ///
980 /// The input [`resolve`](crate::fingerprint::os::resolve) runs over, so a late
981 /// source can raise a verdict.
982 pub fn os_evidence(&self) -> impl Iterator<Item = &OsEvidence> {
983 self.os_evidence.values()
984 }
985
986 /// This host's findings, in a stable order.
987 ///
988 /// Weaknesses of the host as a whole; a port's findings are on the [`Port`]. Ordered
989 /// by claim.
990 pub fn findings(&self) -> impl Iterator<Item = &Finding> {
991 self.findings.values()
992 }
993
994 /// Files what one source concluded, keeping the strongest reading per
995 /// source.
996 ///
997 /// Returns whether this changed what is on record, so a caller can tell a
998 /// genuine new finding from the same one arriving again.
999 ///
1000 /// One entry per claim, so a stack read forty times (forty open ports) counts once
1001 /// and cannot turn one observation into certainty.
1002 pub fn record_os_evidence(&mut self, evidence: OsEvidence) -> bool {
1003 let claim: OsClaim = (
1004 evidence.source,
1005 evidence.family.clone(),
1006 evidence.device.clone(),
1007 evidence.vendor.clone(),
1008 evidence.product.clone(),
1009 evidence.version.clone(),
1010 evidence.kernel.clone(),
1011 );
1012
1013 // Read before borrowing the map; a claim already on record needs no room.
1014 let full = self.os_evidence.len() >= MAX_OS_EVIDENCE;
1015
1016 match self.os_evidence.get_mut(&claim) {
1017 // The same claim, possibly by a different route (one reply versus a
1018 // series). Keep the strongest confidence and every distinct line.
1019 Some(existing) => {
1020 let joined = os::join_readings(&existing.evidence, &evidence.evidence);
1021 let changed = joined != existing.evidence;
1022
1023 existing.evidence = joined;
1024 existing.confidence = existing.confidence.max(evidence.confidence);
1025 changed
1026 }
1027 // The ceiling only turns away something new.
1028 None if full => false,
1029 None => {
1030 self.os_evidence.insert(claim, evidence);
1031 true
1032 }
1033 }
1034 }
1035
1036 /// Records a finding about this host, and reports whether it was new
1037 /// information: a claim not seen before, or a stronger reading of one that
1038 /// was.
1039 ///
1040 /// A finding reached again folds into the one on record through
1041 /// [`Finding::corroborate`]. The ceiling turns away only new claims, so a subject at
1042 /// the limit still updates what it holds.
1043 pub fn add_finding(&mut self, finding: Finding) -> bool {
1044 let claim = finding.claim_id();
1045
1046 // Read before borrowing the map; a claim already on record needs no room.
1047 let full = self.findings.len() >= MAX_FINDINGS_PER_SUBJECT;
1048
1049 match self.findings.get_mut(&claim) {
1050 Some(existing) => existing.corroborate(finding),
1051 None if full => false,
1052 None => {
1053 self.findings.insert(claim, finding);
1054 true
1055 }
1056 }
1057 }
1058
1059 /// Records a finding about one of this host's ports, and reports whether it was
1060 /// new.
1061 ///
1062 /// For a report-level pass such as CVE correlation, which reads a port's service
1063 /// identification and hands a finding back to that port by number and protocol.
1064 ///
1065 /// `None` where this host has no such port; `Some(false)` where the port already
1066 /// has the claim or is at [`MAX_FINDINGS_PER_SUBJECT`].
1067 pub fn add_port_finding(
1068 &mut self,
1069 number: u16,
1070 protocol: Protocol,
1071 finding: Finding,
1072 ) -> Option<bool> {
1073 let key = (number, protocol);
1074 let port = self.ports.get_mut(&key)?;
1075 if let Some(touched) = &mut self.touched {
1076 touched.insert(key);
1077 }
1078 Some(port.add_finding(finding))
1079 }
1080
1081 /// Replaces every correlation `detection` drew on the port at `number` and
1082 /// `protocol` with `findings`. See [`Port::replace_correlations`].
1083 ///
1084 /// `None` where this host has no such port, `Some(false)` where the port
1085 /// already held exactly these.
1086 pub(crate) fn replace_port_correlations(
1087 &mut self,
1088 number: u16,
1089 protocol: Protocol,
1090 detection: &str,
1091 findings: Vec<Finding>,
1092 ) -> Option<bool> {
1093 let key = (number, protocol);
1094 let port = self.ports.get_mut(&key)?;
1095 let changed = port.replace_correlations(detection, findings);
1096 if changed && let Some(touched) = &mut self.touched {
1097 touched.insert(key);
1098 }
1099 Some(changed)
1100 }
1101
1102 /// Replaces this host's operating-system fingerprint outright, whatever was
1103 /// there before, and stamps the host as seen now.
1104 ///
1105 /// For a caller holding a complete [`OsFingerprint`], such as one read back from a
1106 /// report. To fold in a second opinion, use [`merge`](Self::merge).
1107 pub fn set_os(&mut self, os: OsFingerprint) {
1108 self.os = Some(Box::new(os));
1109 self.last_seen = SystemTime::now();
1110 }
1111
1112 /// Withdraws this host's operating-system fingerprint.
1113 ///
1114 /// For a caller that re-resolved the evidence and found it no longer supports what
1115 /// is on record. A scan should not clear a finding just because a later phase did
1116 /// not re-derive it.
1117 pub fn clear_os(&mut self) {
1118 self.os = None;
1119 self.last_seen = SystemTime::now();
1120 }
1121
1122 /// Replaces this host's hardware record wholesale.
1123 ///
1124 /// For a caller holding a complete [`HardwareInfo`], such as one read back from a
1125 /// report. A single sighting goes through [`record_mac`](Self::record_mac).
1126 pub fn set_hardware(&mut self, hardware: HardwareInfo) {
1127 self.hardware = Some(hardware);
1128 self.last_seen = SystemTime::now();
1129 }
1130
1131 /// Builder method to record a MAC sighting and return Self.
1132 pub fn with_mac(mut self, mac: MacAddr) -> Self {
1133 self.record_mac(mac);
1134 self
1135 }
1136
1137 /// Records a sighting of `mac` for this host, keeping every address seen.
1138 ///
1139 /// Adds to the history [`HardwareInfo`] keeps: a device with two interfaces on one
1140 /// segment, or one randomizing its MAC, answers under several addresses and is one
1141 /// host. [`most_recent_mac`] and [`prune_stale_macs`] rely on the history.
1142 ///
1143 /// Repeating a MAC already on record refreshes its last-seen time.
1144 ///
1145 /// Bounded by [`MAX_MACS_PER_HOST`](hardware::MAX_MACS_PER_HOST), since a source
1146 /// address is just a field in a frame.
1147 ///
1148 /// [`most_recent_mac`]: HardwareInfo::most_recent_mac
1149 /// [`prune_stale_macs`]: HardwareInfo::prune_stale_macs
1150 pub fn record_mac(&mut self, mac: MacAddr) {
1151 match &mut self.hardware {
1152 Some(hardware) => hardware.add_mac(mac),
1153 None => self.hardware = Some(HardwareInfo::new(mac)),
1154 }
1155 self.last_seen = SystemTime::now();
1156 }
1157
1158 /// Adds a single RTT measurement and bumps `last_seen`.
1159 pub fn add_rtt(&mut self, rtt: std::time::Duration) {
1160 self.telemetry.add_rtt(rtt);
1161 self.last_seen = SystemTime::now();
1162 }
1163
1164 /// The same, from a caller that knows which probe drew the reply.
1165 ///
1166 /// The probe decides what the figure measures: an ARP reply comes off the link
1167 /// layer, a SYN/ACK crosses the target's IP and TCP stacks.
1168 pub fn add_rtt_from(&mut self, rtt: std::time::Duration, protocol: StatusProtocol) {
1169 self.telemetry.add_rtt_from(rtt, protocol);
1170 self.last_seen = SystemTime::now();
1171 }
1172
1173 /// Which probe this host's round trips were measured from, where they agree
1174 /// on one.
1175 ///
1176 /// See [`HostTelemetry::rtt_protocol`](crate::model::host::telemetry::HostTelemetry::rtt_protocol).
1177 #[must_use]
1178 pub fn rtt_protocol(&self) -> Option<StatusProtocol> {
1179 self.telemetry.rtt_protocol()
1180 }
1181
1182 /// Adds a round trip measured against a probe the whole segment was asked,
1183 /// which this host will report only if it produced no better sample.
1184 ///
1185 /// See [`RttSource`](crate::model::host::telemetry::RttSource).
1186 pub fn add_segment_wide_rtt(&mut self, rtt: std::time::Duration) {
1187 self.telemetry.add_segment_wide_rtt(rtt);
1188 self.last_seen = SystemTime::now();
1189 }
1190
1191 /// The same, from a caller that knows which probe drew the reply.
1192 pub fn add_segment_wide_rtt_from(
1193 &mut self,
1194 rtt: std::time::Duration,
1195 protocol: StatusProtocol,
1196 ) {
1197 self.telemetry.add_segment_wide_rtt_from(rtt, protocol);
1198 self.last_seen = SystemTime::now();
1199 }
1200
1201 /// Adds a round trip timed from the first probe sent to a neighbour,
1202 /// which this host will report only if it produced no better sample: the
1203 /// probe may have waited on the neighbour's address resolution.
1204 ///
1205 /// See [`RttSource`](crate::model::host::telemetry::RttSource).
1206 pub fn add_first_to_neighbour_rtt_from(
1207 &mut self,
1208 rtt: std::time::Duration,
1209 protocol: StatusProtocol,
1210 ) {
1211 self.telemetry
1212 .add_first_to_neighbour_rtt_from(rtt, protocol);
1213 self.last_seen = SystemTime::now();
1214 }
1215
1216 /// Builder method to add a single RTT measurement and return Self.
1217 pub fn with_rtt(mut self, rtt: std::time::Duration) -> Self {
1218 self.add_rtt(rtt);
1219 self
1220 }
1221
1222 /// Adds a round-trip sample read back from a record; see
1223 /// [`HostTelemetry::restore_rtt`](crate::model::host::telemetry::HostTelemetry::restore_rtt).
1224 pub(crate) fn restore_rtt(
1225 &mut self,
1226 rtt: std::time::Duration,
1227 source: crate::model::host::telemetry::RttSource,
1228 protocol: Option<StatusProtocol>,
1229 ) {
1230 self.telemetry.restore_rtt(rtt, source, protocol);
1231 }
1232
1233 /// Records several round-trip measurements at once.
1234 pub fn add_rtts(&mut self, rtts: impl IntoIterator<Item = std::time::Duration>) {
1235 for rtt in rtts {
1236 self.telemetry.add_rtt(rtt);
1237 }
1238 self.last_seen = SystemTime::now();
1239 }
1240
1241 /// Records a role for this host, returning whether it is one the record did
1242 /// not already carry.
1243 ///
1244 /// The same evidence recurs (a router advertises on a timer, a name server answers
1245 /// every lookup), so the return says whether this is news. Bumps `last_seen` either
1246 /// way.
1247 pub fn add_network_role(&mut self, role: NetworkRole) -> bool {
1248 let is_new = self.network_roles.insert(role);
1249 self.last_seen = SystemTime::now();
1250 is_new
1251 }
1252
1253 /// Records a filtering conclusion drawn about the path to this host,
1254 /// returning whether it is one not already held.
1255 ///
1256 /// Bumps `last_seen`, as [`add_network_role`](Self::add_network_role) does.
1257 pub fn add_filtering(&mut self, filtering: Filtering) -> bool {
1258 let is_new = self.filtering.insert(filtering);
1259 self.last_seen = SystemTime::now();
1260 is_new
1261 }
1262
1263 /// Raises what is recorded about `number` to `state`, if that establishes
1264 /// more, and returns whether the record changed.
1265 ///
1266 /// Promotes and never lowers, on [`IpProtocolState`]'s ordering, as
1267 /// [`Port::set_state`] does. So [`Unasked`](IpProtocolState::Unasked) stands only
1268 /// where nothing else was recorded.
1269 ///
1270 /// Bumps `last_seen` only where the host itself answered, not on silence or a
1271 /// router's refusal.
1272 pub fn record_ip_protocol(&mut self, number: u8, state: IpProtocolState) -> bool {
1273 let recorded = match self.ip_protocols.get_mut(&number) {
1274 Some(held) if state > *held => {
1275 *held = state;
1276 true
1277 }
1278 Some(_) => false,
1279 // Recorded even at `Unasked`: named but not reached.
1280 None => {
1281 self.ip_protocols.insert(number, state);
1282 true
1283 }
1284 };
1285
1286 if matches!(state, IpProtocolState::Open | IpProtocolState::Closed) {
1287 self.last_seen = SystemTime::now();
1288 }
1289 recorded
1290 }
1291
1292 /// Returns the minimum recorded RTT.
1293 pub fn min_rtt(&self) -> Option<std::time::Duration> {
1294 self.telemetry.min_rtt()
1295 }
1296
1297 /// Returns the maximum recorded RTT.
1298 pub fn max_rtt(&self) -> Option<std::time::Duration> {
1299 self.telemetry.max_rtt()
1300 }
1301
1302 /// Returns the average recorded RTT.
1303 pub fn average_rtt(&self) -> Option<std::time::Duration> {
1304 self.telemetry.average_rtt()
1305 }
1306
1307 /// Returns the median recorded RTT, a summary of typical latency that is
1308 /// robust against outliers. See [`HostTelemetry::median_rtt`].
1309 pub fn median_rtt(&self) -> Option<std::time::Duration> {
1310 self.telemetry.median_rtt()
1311 }
1312
1313 /// Returns the most recent MAC address, if hardware info is available.
1314 pub fn mac(&self) -> Option<MacAddr> {
1315 self.hardware.as_ref().and_then(|h| h.most_recent_mac())
1316 }
1317
1318 /// Returns the hardware vendor, if hardware info is available.
1319 pub fn vendor(&self) -> Option<&str> {
1320 self.hardware.as_ref().and_then(HardwareInfo::vendor)
1321 }
1322
1323 /// Returns `true` if this host is confirmed to be on the network
1324 /// (either responding for itself or blocked on its behalf).
1325 pub fn is_alive(&self) -> bool {
1326 self.status.is_alive()
1327 }
1328
1329 /// Returns an iterator over all discovered ports in sorted order.
1330 pub fn ports(&self) -> impl Iterator<Item = &Port> {
1331 self.ports.values()
1332 }
1333
1334 /// Returns the total number of recorded ports for this host.
1335 pub fn port_count(&self) -> usize {
1336 self.ports.len()
1337 }
1338
1339 /// Records a port finding, merging it with what is already known about that
1340 /// port.
1341 ///
1342 /// Returns whether the finding was recorded. `false` means the host is at
1343 /// [`MAX_PORTS_PER_HOST`] and has been marked [`NetworkRole::Truncated`], which no
1344 /// scan reaches (see [`Truncated`](NetworkRole::Truncated)).
1345 ///
1346 /// A host past [`TARPIT_OPEN_PORTS`] open ports is marked [`NetworkRole::Tarpit`]
1347 /// and keeps recording, so a caller can still discard the ports itself.
1348 pub fn add_port(&mut self, new_port: Port) -> bool {
1349 let key = (new_port.number(), new_port.protocol());
1350 let existing = self.ports.get(&key);
1351
1352 if existing.is_none() && self.ports.len() >= MAX_PORTS_PER_HOST {
1353 self.network_roles.insert(NetworkRole::Truncated);
1354 return false;
1355 }
1356
1357 let was_open = existing.is_some_and(|port| port.state() == PortState::Open);
1358
1359 // A match on the entry avoids cloning `new_port`, which `and_modify` with
1360 // `or_insert` would need; a `Port` is not cheap to copy.
1361 let recorded = match self.ports.entry(key) {
1362 std::collections::btree_map::Entry::Occupied(slot) => {
1363 let recorded = slot.into_mut();
1364 recorded.merge(new_port);
1365 recorded
1366 }
1367 std::collections::btree_map::Entry::Vacant(slot) => slot.insert(new_port),
1368 };
1369 if let Some(touched) = &mut self.touched {
1370 touched.insert(key);
1371 }
1372
1373 // State only promotes, so this only counts up; see `open_ports`.
1374 if !was_open && recorded.state() == PortState::Open {
1375 self.open_ports += 1;
1376 if self.open_ports >= TARPIT_OPEN_PORTS {
1377 self.network_roles.insert(NetworkRole::Tarpit);
1378 }
1379 }
1380
1381 self.last_seen = SystemTime::now();
1382 true
1383 }
1384
1385 /// How many of this host's ports are open.
1386 pub fn open_port_count(&self) -> usize {
1387 self.open_ports
1388 }
1389
1390 /// Starts keeping which ports are recorded or given a finding, for
1391 /// [`take_touched_ports`](Self::take_touched_ports) to hand over. Keeps
1392 /// what is kept already.
1393 pub(crate) fn track_touched_ports(&mut self) {
1394 self.touched.get_or_insert_with(BTreeSet::new);
1395 }
1396
1397 /// The ports recorded or given a finding since this was last called,
1398 /// leaving none marked; `None` for a host nothing asked to track them.
1399 ///
1400 /// Touched, not changed: a port re-recorded with nothing new is still named. See
1401 /// `touched`.
1402 pub(crate) fn take_touched_ports(&mut self) -> Option<BTreeSet<(u16, Protocol)>> {
1403 self.touched.as_mut().map(std::mem::take)
1404 }
1405
1406 /// A copy of this host carrying only the ports `keys` name, of those it
1407 /// holds, and tracking none.
1408 ///
1409 /// What a journal writes when a few ports of a wide host changed. Only ever
1410 /// written down, where its ports fold into what the file already holds.
1411 #[cfg(feature = "journal-format")]
1412 pub(crate) fn with_only_ports(&self, keys: &BTreeSet<(u16, Protocol)>) -> Self {
1413 // Destructured, so a new field fails to compile until it is copied.
1414 let Self {
1415 primary_ip,
1416 ips,
1417 hostname,
1418 names,
1419 set_aside_names,
1420 status,
1421 reasons,
1422 os,
1423 os_evidence,
1424 hardware,
1425 zone,
1426 telemetry,
1427 path,
1428 network_roles,
1429 filtering,
1430 ip_protocols,
1431 findings,
1432 first_seen,
1433 last_seen,
1434 ports,
1435 open_ports,
1436 touched: _,
1437 } = self;
1438 // Every port named (the first checkpoint after a wide port scan) copies
1439 // the map whole. Ports are never removed, so equal counts mean all.
1440 let (ports, open_ports) = if keys.len() == ports.len() {
1441 (ports.clone(), *open_ports)
1442 } else {
1443 let ports: BTreeMap<_, _> = keys
1444 .iter()
1445 .filter_map(|key| ports.get_key_value(key))
1446 .map(|(key, port)| (*key, port.clone()))
1447 .collect();
1448 let open = ports
1449 .values()
1450 .filter(|port| port.state() == PortState::Open)
1451 .count();
1452 (ports, open)
1453 };
1454 Self {
1455 primary_ip: *primary_ip,
1456 ips: ips.clone(),
1457 hostname: hostname.clone(),
1458 names: names.clone(),
1459 set_aside_names: set_aside_names.clone(),
1460 status: *status,
1461 reasons: reasons.clone(),
1462 os: os.clone(),
1463 os_evidence: os_evidence.clone(),
1464 hardware: hardware.clone(),
1465 zone: zone.clone(),
1466 telemetry: telemetry.clone(),
1467 path: path.clone(),
1468 network_roles: network_roles.clone(),
1469 filtering: filtering.clone(),
1470 ip_protocols: ip_protocols.clone(),
1471 findings: findings.clone(),
1472 first_seen: *first_seen,
1473 last_seen: *last_seen,
1474 ports,
1475 open_ports,
1476 touched: None,
1477 }
1478 }
1479
1480 /// Folds `later`, an account of this host written after the one this
1481 /// holds, its round trips replacing these.
1482 ///
1483 /// For a journal record, which carries the whole window of round trips as it stood:
1484 /// a later one repeats every earlier sample, which would otherwise count twice. A
1485 /// later account with no round trips leaves these. Everything else folds as
1486 /// [`merge`](Self::merge) does.
1487 pub(crate) fn merge_later_account(&mut self, later: Host) {
1488 let window = later.telemetry.clone();
1489 self.merge(later);
1490 self.telemetry.take_window(window);
1491 }
1492
1493 /// Folds another record of this host into this one.
1494 ///
1495 /// How findings from separate scan stages become one record. Status is promoted and
1496 /// never lowered, telemetry and OS data merge by their own rules, and the port cap
1497 /// still applies.
1498 ///
1499 /// The leading address is decided by
1500 /// [`consider_primary_ip`](Self::consider_primary_ip), whichever record is `self`.
1501 pub fn merge(&mut self, other: Host) {
1502 // Destructured, so a new field fails to compile until it is merged.
1503 let Host {
1504 primary_ip: other_primary,
1505 ips,
1506 hostname,
1507 names,
1508 set_aside_names,
1509 status,
1510 reasons,
1511 os,
1512 os_evidence,
1513 hardware,
1514 zone,
1515 telemetry,
1516 path,
1517 network_roles,
1518 filtering,
1519 ip_protocols,
1520 findings,
1521 first_seen: other_first_seen,
1522 last_seen: other_last_seen,
1523 ports,
1524 // Derived, and maintained by `add_port` as the ports below arrive.
1525 open_ports: _,
1526 // `add_port` marks the ports a merge touches; `other`'s marks do not
1527 // apply here.
1528 touched: _,
1529 } = other;
1530
1531 // Taken first and restored at the end: the mutators below stamp
1532 // `last_seen` with now, but a merge is not a sighting.
1533 let first_seen = self.first_seen.min(other_first_seen);
1534 let last_seen = self.last_seen.max(other_last_seen);
1535
1536 for ip in ips {
1537 self.admit_ip(ip);
1538 }
1539 self.consider_primary_ip(other_primary);
1540
1541 // A name the fold does not keep is set aside, since the text folded in
1542 // below can hold it.
1543 if self.hostname.is_none() {
1544 self.hostname = hostname;
1545 } else if let Some(offered) = hostname {
1546 self.set_aside(&offered);
1547 }
1548 for name in names {
1549 if let Err(turned_away) = self.admit_name(name) {
1550 self.set_aside(turned_away.name());
1551 }
1552 }
1553 for name in &set_aside_names {
1554 self.set_aside(name);
1555 }
1556
1557 if status > self.status {
1558 self.status = status;
1559 }
1560 self.reasons.extend(reasons);
1561
1562 if let Some(other_os) = os {
1563 if let Some(ref mut self_os) = self.os {
1564 self_os.merge(*other_os);
1565 } else {
1566 self.os = Some(other_os);
1567 }
1568 }
1569
1570 // Through `record_os_evidence`, so one claim keeps the strongest confidence
1571 // and every distinct line, and the ceiling turns away only what is new.
1572 for evidence in os_evidence.into_values() {
1573 self.record_os_evidence(evidence);
1574 }
1575
1576 if let Some(other_hw) = hardware {
1577 if let Some(ref mut self_hw) = self.hardware {
1578 self_hw.merge(other_hw);
1579 } else {
1580 self.hardware = Some(other_hw);
1581 }
1582 }
1583
1584 if let Some(other_zone) = zone {
1585 self.zone.get_or_insert(other_zone);
1586 }
1587
1588 self.telemetry.merge(telemetry);
1589
1590 // Hop by hop, so `NetworkPath::record` decides each distance: a
1591 // measurement beats an inference, an answer beats silence. A port scan
1592 // folds a liveness snapshot taken before the trace with one taken after,
1593 // so the earlier record has no path.
1594 for hop in path.hops() {
1595 self.path.record(*hop);
1596 }
1597
1598 self.network_roles.extend(network_roles);
1599
1600 // Only one of the two records may have run the comparative probe.
1601 self.filtering.extend(filtering);
1602
1603 // Through the recorder, so a sitting cut short at `Unasked` cannot lower
1604 // a verdict another sitting reached.
1605 for (number, state) in ip_protocols {
1606 self.record_ip_protocol(number, state);
1607 }
1608
1609 // A claim missing from one record is a detection that did not run there,
1610 // so a fold only adds. A claim on both corroborates through `add_finding`.
1611 for finding in findings.into_values() {
1612 self.add_finding(finding);
1613 }
1614
1615 for port in ports.into_values() {
1616 self.add_port(port);
1617 }
1618
1619 self.first_seen = first_seen;
1620 self.last_seen = last_seen;
1621 }
1622}
1623
1624impl std::fmt::Display for Host {
1625 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1626 write!(f, "{} ({})", self.primary_ip, self.status)?;
1627 if let Some(ref os) = self.os {
1628 write!(f, " - {}", os)?;
1629 }
1630
1631 // In `NetworkRole::ALL` order, since a `HashSet`'s order is not stable.
1632 let mut roles = NetworkRole::ALL
1633 .iter()
1634 .filter(|role| self.network_roles.contains(role))
1635 .peekable();
1636 if roles.peek().is_some() {
1637 write!(f, " [")?;
1638 for (n, role) in roles.enumerate() {
1639 if n > 0 {
1640 write!(f, ", ")?;
1641 }
1642 write!(f, "{}", role.label())?;
1643 }
1644 write!(f, "]")?;
1645 }
1646
1647 // For a tarpit or truncated host, the marking replaces the latency.
1648 if !self.network_roles.contains(&NetworkRole::Tarpit)
1649 && !self.network_roles.contains(&NetworkRole::Truncated)
1650 {
1651 write!(f, " [{}]", self.telemetry)?;
1652 }
1653 Ok(())
1654 }
1655}
1656
1657// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1658// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
1659// โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
1660// โ โโโ โโโโโโ โโโโโโโโ โโโ โโโโโโโโ โ
1661// โ โโโ โโโโโโ โโโโโโโโ โโโ โโโโโโโโ โ
1662// โ โโโ โโโโโโโโโโโโโโโโ โโโ โโโโโโโโ โ
1663// โ โโโ โโโโโโโโโโโโโโโโ โโโ โโโโโโโโ โ
1664// โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
1665
1666#[cfg(test)]
1667mod tests {
1668 use super::*;
1669 use crate::model::port::{Port, PortState, Protocol};
1670 use std::net::Ipv4Addr;
1671
1672 static IP_ADDR: IpAddr = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 100));
1673
1674 /// Refusing the leading address hands the lead to the best remaining one, by the
1675 /// same ranking.
1676 #[test]
1677 fn a_refused_lead_passes_to_the_best_address_left() {
1678 let v4: IpAddr = "192.0.2.60".parse().expect("literal");
1679 let global: IpAddr = "2001:db8::5".parse().expect("literal");
1680 let link_local: IpAddr = "fe80::10".parse().expect("literal");
1681
1682 let mut host = Host::new(link_local);
1683 host.add_ip(global);
1684 host.consider_primary_ip(v4);
1685 assert_eq!(host.primary_ip(), v4, "test premise");
1686
1687 assert!(host.retain_ips(|ip| *ip != v4));
1688 assert_eq!(host.primary_ip(), global);
1689 assert_eq!(
1690 host.ips().iter().copied().collect::<Vec<_>>(),
1691 vec![global, link_local]
1692 );
1693 }
1694
1695 /// A host with every address refused is handed back as it was.
1696 #[test]
1697 fn a_host_every_address_of_which_is_refused_is_left_as_it_was() {
1698 let mut host = Host::new(IP_ADDR);
1699 host.add_ip("192.0.2.61".parse().expect("literal"));
1700 let before = host.ips().clone();
1701
1702 assert!(!host.retain_ips(|_| false));
1703 assert_eq!(host.primary_ip(), IP_ADDR);
1704 assert_eq!(*host.ips(), before);
1705 }
1706
1707 /// A pass that only named a protocol cannot lower one that was reached.
1708 #[test]
1709 fn a_protocol_verdict_is_promoted_and_never_lowered() {
1710 use crate::model::host::IpProtocolState;
1711
1712 let mut host = Host::new(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1)));
1713
1714 assert!(host.record_ip_protocol(47, IpProtocolState::Unasked));
1715 assert_eq!(
1716 host.ip_protocols().get(&47),
1717 Some(&IpProtocolState::Unasked)
1718 );
1719
1720 assert!(host.record_ip_protocol(47, IpProtocolState::Closed));
1721 assert!(
1722 !host.record_ip_protocol(47, IpProtocolState::OpenOrNoReply),
1723 "a weaker verdict is not news"
1724 );
1725 assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Closed));
1726
1727 assert!(host.record_ip_protocol(47, IpProtocolState::Open));
1728 assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
1729 }
1730
1731 /// The same rule across a fold.
1732 #[test]
1733 fn merging_keeps_the_stronger_protocol_verdict_from_either_side() {
1734 use crate::model::host::IpProtocolState;
1735
1736 let ip = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1));
1737
1738 let mut reached = Host::new(ip);
1739 reached.record_ip_protocol(47, IpProtocolState::Open);
1740 reached.record_ip_protocol(89, IpProtocolState::Unasked);
1741
1742 let mut cut_short = Host::new(ip);
1743 cut_short.record_ip_protocol(47, IpProtocolState::Unasked);
1744 cut_short.record_ip_protocol(89, IpProtocolState::Closed);
1745 cut_short.record_ip_protocol(50, IpProtocolState::OpenOrNoReply);
1746
1747 let mut folded = reached.clone();
1748 folded.merge(cut_short.clone());
1749 let mut other_way = cut_short;
1750 other_way.merge(reached);
1751
1752 for host in [&folded, &other_way] {
1753 assert_eq!(host.ip_protocols().get(&47), Some(&IpProtocolState::Open));
1754 assert_eq!(host.ip_protocols().get(&89), Some(&IpProtocolState::Closed));
1755 assert_eq!(
1756 host.ip_protocols().get(&50),
1757 Some(&IpProtocolState::OpenOrNoReply),
1758 "a protocol only one side asked about survives the fold"
1759 );
1760 }
1761 }
1762
1763 /// `filtering` and `os_evidence` from the record folded in survive the merge.
1764 #[test]
1765 fn a_merge_keeps_every_field_of_the_record_it_folds_in() {
1766 let ip: IpAddr = "192.0.2.1".parse().expect("an address");
1767 let mut incumbent = Host::new(ip);
1768 let mut arriving = Host::new(ip);
1769
1770 arriving.add_filtering(Filtering::StatefulFilter);
1771 arriving.add_filtering(Filtering::InlineMiddlebox);
1772 arriving.record_os_evidence(OsEvidence {
1773 source: OsSource::ServiceBanner,
1774 family: Some("Linux".to_string()),
1775 device: None,
1776 vendor: None,
1777 product: None,
1778 version: None,
1779 kernel: Some("6.1.0".to_string()),
1780 arch: None,
1781 cpe: None,
1782 confidence: 0.9,
1783 evidence: "ssh banner".to_string(),
1784 });
1785
1786 incumbent.merge(arriving);
1787
1788 assert_eq!(
1789 incumbent.filtering().len(),
1790 2,
1791 "a filtering conclusion is drawn by a comparative probe only one \
1792 record will have run, so dropping it loses the whole finding"
1793 );
1794 assert_eq!(
1795 incumbent.os_evidence().count(),
1796 1,
1797 "os evidence is what corroboration is computed over, and the \
1798 fold is where a second source's reading arrives"
1799 );
1800 }
1801
1802 /// A host's own names accumulate across a merge, and a peer inventing names is held
1803 /// to [`MAX_NAMES`] without displacing those already held.
1804 #[test]
1805 fn names_accumulate_across_a_merge_up_to_the_ceiling() {
1806 let name = |kind, text: &str| HostName::new(kind, NameSource::Ntlm, text).expect("a name");
1807
1808 let mut earlier = Host::new(IP_ADDR);
1809 earlier.record_name(name(NameKind::Host, "dc01.corp.example"));
1810 let mut later = Host::new(IP_ADDR);
1811 later.record_name(name(NameKind::Host, "dc01.corp.example"));
1812 later.record_name(name(NameKind::Domain, "corp.example"));
1813 earlier.merge(later);
1814 assert_eq!(
1815 earlier.names().map(HostName::name).collect::<Vec<_>>(),
1816 ["dc01.corp.example", "corp.example"],
1817 "the same name from both records is one claim"
1818 );
1819
1820 let mut flooded = Host::new(IP_ADDR);
1821 for n in 0..MAX_NAMES {
1822 assert!(flooded.record_name(name(NameKind::NetbiosHost, &format!("HOST{n:02}"))));
1823 }
1824 assert!(!flooded.record_name(name(NameKind::NetbiosHost, "ONE-MORE")));
1825 assert!(
1826 !flooded.record_name(name(NameKind::NetbiosHost, "HOST00")),
1827 "a name already held is not news"
1828 );
1829 assert_eq!(flooded.names().count(), MAX_NAMES);
1830 }
1831
1832 /// A server's own words reach a terminal through `Display` as text, not as
1833 /// control sequences: a banner-filled OS field carrying an escape prints it
1834 /// escaped.
1835 #[test]
1836 fn display_escapes_control_characters_a_server_chose() {
1837 let mut host = Host::new(IP_ADDR);
1838 host.set_os(
1839 OsFingerprint::new("Linux\x1b]0;owned\x07", 90)
1840 .with_family("Linux")
1841 .with_kernel("6.1\x1b[2J\r\n"),
1842 );
1843
1844 let shown = host.to_string();
1845 assert!(!shown.contains(char::is_control), "raw: {shown:?}");
1846 assert!(
1847 shown.contains("Linux\\x1b]0;owned\\x07") && shown.contains("6.1\\x1b[2J\\r\\n"),
1848 "escaped, so it can still be read: {shown}"
1849 );
1850 }
1851
1852 /// A sender inventing source addresses is held to [`MAX_IPS`], and an address that
1853 /// outranks the flood still gets in and leads.
1854 #[test]
1855 fn a_host_holds_at_most_max_ips_and_keeps_room_for_a_better_one() {
1856 let link_local = |n: usize| {
1857 IpAddr::V6(std::net::Ipv6Addr::new(
1858 0xfe80,
1859 0,
1860 0,
1861 0,
1862 0,
1863 0,
1864 (n >> 16) as u16,
1865 n as u16,
1866 ))
1867 };
1868
1869 let mut flooded = Host::new(link_local(0));
1870 for n in 1..MAX_IPS + 100 {
1871 flooded.add_ip(link_local(n));
1872 }
1873 let mut merged = Host::new(link_local(0));
1874 merged.merge(flooded.clone());
1875 assert_eq!(flooded.ips().len(), MAX_IPS, "one by one");
1876 assert_eq!(merged.ips().len(), MAX_IPS, "through a merge");
1877
1878 let ipv4 = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
1879 assert!(flooded.consider_primary_ip(ipv4), "the IPv4 address leads");
1880 assert!(flooded.ips().contains(&ipv4));
1881 assert!(
1882 flooded.ips().contains(&link_local(0)),
1883 "the address the record was keyed by stays"
1884 );
1885 assert_eq!(flooded.ips().len(), MAX_IPS);
1886 }
1887
1888 /// A machine renaming itself on every request is held to [`MAX_SET_ASIDE_NAMES`]
1889 /// across the merges that set the names aside.
1890 #[test]
1891 fn set_aside_names_stop_at_their_ceiling() {
1892 let mut host = Host::new(IP_ADDR);
1893 host.set_hostname(Some("first.example".to_owned()));
1894 for n in 0..MAX_SET_ASIDE_NAMES + 10 {
1895 let mut renamed = Host::new(IP_ADDR);
1896 renamed.set_hostname(Some(format!("host{n}.example")));
1897 host.merge(renamed);
1898 }
1899 assert_eq!(host.set_aside_names().count(), MAX_SET_ASIDE_NAMES);
1900 assert!(
1901 host.set_aside_names().any(|name| name == "host0.example"),
1902 "the ceiling turns new names away and keeps held ones"
1903 );
1904 }
1905
1906 /// A merge keeps what only the later record knows, such as a path and hop counter
1907 /// measured after the liveness snapshot. Asserted with the lacking record on the
1908 /// left, as the port scan merges.
1909 #[test]
1910 fn a_merge_keeps_what_only_the_other_record_learned() {
1911 let mut earlier = Host::new(IP_ADDR);
1912 earlier.set_status(HostStatus::Up);
1913
1914 let mut later = Host::new(IP_ADDR);
1915 later.record_hop_counter(59);
1916 later.record_hop(path::Hop::answered(
1917 1,
1918 IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1)),
1919 None,
1920 ));
1921 later.record_hop(path::Hop::silent(2));
1922
1923 earlier.merge(later);
1924
1925 assert_eq!(
1926 earlier.path().hops().len(),
1927 2,
1928 "the trace ran between the two snapshots and only the later one has it"
1929 );
1930 assert_eq!(earlier.path().length(), Some(2));
1931 assert_eq!(earlier.telemetry().hop_counter(), Some(59));
1932 }
1933
1934 /// Merging two paths settles each distance on its own terms.
1935 ///
1936 /// Two records can each know a different half, and an inferred distance yields to a
1937 /// measured one.
1938 #[test]
1939 fn merging_paths_keeps_the_stronger_claim_at_every_distance() {
1940 let router = IpAddr::V4(Ipv4Addr::new(203, 0, 113, 1));
1941
1942 let mut inherited = Host::new(IP_ADDR);
1943 inherited.record_hop(path::Hop::answered(1, router, None).as_inferred());
1944 inherited.record_hop(path::Hop::silent(2));
1945
1946 let mut measured = Host::new(IP_ADDR);
1947 measured.record_hop(path::Hop::answered(
1948 1,
1949 router,
1950 Some(std::time::Duration::from_millis(3)),
1951 ));
1952
1953 inherited.merge(measured);
1954
1955 let hops = inherited.path().hops();
1956 assert_eq!(hops.len(), 2, "the distance only one side knew survives");
1957 assert!(!hops[0].inferred(), "a measurement replaces an inference");
1958 assert_eq!(hops[0].rtt(), Some(std::time::Duration::from_millis(3)));
1959 }
1960
1961 /// A status only improves, through every entry point that sets one.
1962 #[test]
1963 fn a_status_is_never_lowered_by_the_plain_setter() {
1964 let mut host = Host::new(IP_ADDR);
1965
1966 host.set_status(HostStatus::Up);
1967 host.set_status(HostStatus::Down);
1968 assert_eq!(host.status(), HostStatus::Up);
1969
1970 let mut climbing = Host::new(IP_ADDR);
1971 climbing.set_status(HostStatus::Down);
1972 climbing.set_status(HostStatus::Up);
1973 assert_eq!(climbing.status(), HostStatus::Up);
1974 }
1975
1976 /// A port number names one endpoint per transport, and the two are kept apart.
1977 #[test]
1978 fn a_port_number_holds_one_endpoint_per_protocol() {
1979 let mut host = Host::new(IP_ADDR);
1980 host.add_port(Port::new(53, Protocol::Tcp, PortState::Closed));
1981 host.add_port(Port::new(53, Protocol::Udp, PortState::Open));
1982
1983 let ports: Vec<_> = host.ports().collect();
1984 assert_eq!(ports.len(), 2, "TCP/53 and UDP/53 are two endpoints");
1985 assert_eq!(
1986 (ports[0].protocol(), ports[0].state()),
1987 (Protocol::Tcp, PortState::Closed)
1988 );
1989 assert_eq!(
1990 (ports[1].protocol(), ports[1].state()),
1991 (Protocol::Udp, PortState::Open),
1992 "neither finding was folded into the other"
1993 );
1994
1995 // A repeat still merges with its own protocol.
1996 host.add_port(Port::new(53, Protocol::Tcp, PortState::Open));
1997 assert_eq!(host.port_count(), 2);
1998 assert_eq!(
1999 host.ports().next().expect("tcp/53").state(),
2000 PortState::Open
2001 );
2002 }
2003
2004 /// The role line is in a stable order, unlike the `HashSet` that holds the roles.
2005 #[test]
2006 fn a_host_prints_its_roles_in_one_order_however_they_were_recorded() {
2007 let expected = "203.0.113.100 (Up) [router, DNS, origin]";
2008
2009 for order in [
2010 [
2011 NetworkRole::Router,
2012 NetworkRole::DnsServer,
2013 NetworkRole::Origin,
2014 ],
2015 [
2016 NetworkRole::Origin,
2017 NetworkRole::Router,
2018 NetworkRole::DnsServer,
2019 ],
2020 [
2021 NetworkRole::DnsServer,
2022 NetworkRole::Origin,
2023 NetworkRole::Router,
2024 ],
2025 ] {
2026 let mut host = Host::new(IP_ADDR);
2027 host.set_status(HostStatus::Up);
2028 for role in order {
2029 host.add_network_role(role);
2030 }
2031
2032 let line = host.to_string();
2033 let (roles, _telemetry) = line.rsplit_once(" [").expect("telemetry follows the roles");
2034 assert_eq!(roles, expected, "recorded as {order:?}");
2035 }
2036 }
2037
2038 /// For a tarpit or truncated host, the marking replaces the latency.
2039 #[test]
2040 fn a_tarpit_prints_the_marking_where_the_latency_would_be() {
2041 let mut host = Host::new(IP_ADDR);
2042 host.set_status(HostStatus::Up);
2043 host.add_network_role(NetworkRole::Tarpit);
2044
2045 assert_eq!(host.to_string(), "203.0.113.100 (Up) [tarpit]");
2046 }
2047
2048 /// The largest scan a person can write, recorded whole.
2049 ///
2050 /// `1-65535,u:1-65535` against a host answering on all of it is
2051 /// `MAX_PORTS_PER_HOST` endpoints, all kept, and the record is complete.
2052 #[test]
2053 fn a_full_scan_of_both_transports_is_recorded_whole() {
2054 let mut host = Host::new(IP_ADDR);
2055
2056 for &protocol in Protocol::ALL {
2057 for port in u16::MIN..=u16::MAX {
2058 assert!(
2059 host.add_port(Port::new(port, protocol, PortState::Closed)),
2060 "{protocol:?}/{port} was refused by a scan that asked for it"
2061 );
2062 }
2063 }
2064
2065 assert_eq!(host.port_count(), MAX_PORTS_PER_HOST);
2066 assert!(
2067 !host.network_roles().contains(&NetworkRole::Truncated),
2068 "a complete port list was reported as truncated"
2069 );
2070 }
2071
2072 /// The cap sits exactly at what the map can hold, so no scan reaches it.
2073 ///
2074 /// The map is keyed on port number and transport, and the cap is derived from the
2075 /// same two.
2076 #[test]
2077 fn the_cap_is_what_the_port_map_can_hold() {
2078 let endpoints = (usize::from(u16::MAX) + 1) * Protocol::ALL.len();
2079 assert_eq!(MAX_PORTS_PER_HOST, endpoints);
2080 }
2081
2082 /// A wide scan of an ordinary host is neither truncated nor a tarpit.
2083 #[test]
2084 fn a_wide_scan_of_an_ordinary_host_is_neither_truncated_nor_a_tarpit() {
2085 let mut host = Host::new(IP_ADDR);
2086 for port in 1..=1024u16 {
2087 let state = match port {
2088 53 | 80 => PortState::Open,
2089 _ => PortState::Closed,
2090 };
2091 assert!(host.add_port(Port::new(port, Protocol::Tcp, state)));
2092 }
2093
2094 assert_eq!(host.port_count(), 1024, "every finding was kept");
2095 assert!(host.network_roles().is_empty(), "and nothing was inferred");
2096 }
2097
2098 /// A thousand *open* ports marks a tarpit, and recording continues.
2099 #[test]
2100 fn a_host_answering_open_on_everything_is_called_what_it_is() {
2101 let mut host = Host::new(IP_ADDR);
2102 for port in 0..TARPIT_OPEN_PORTS {
2103 host.add_port(Port::new(port as u16, Protocol::Tcp, PortState::Open));
2104 }
2105
2106 assert!(host.network_roles().contains(&NetworkRole::Tarpit));
2107 assert!(!host.network_roles().contains(&NetworkRole::Truncated));
2108 assert_eq!(host.open_port_count(), TARPIT_OPEN_PORTS);
2109 }
2110
2111 /// The count follows promotions, not insertions. A port first met with silence
2112 /// and later answered is one more open port, and a second reply about a port
2113 /// already open is not.
2114 #[test]
2115 fn the_open_count_follows_what_the_ports_became() {
2116 let mut host = Host::new(IP_ADDR);
2117
2118 host.add_port(Port::new(22, Protocol::Tcp, PortState::NoReply));
2119 assert_eq!(host.open_port_count(), 0);
2120
2121 host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
2122 assert_eq!(host.open_port_count(), 1, "promoted");
2123
2124 host.add_port(Port::new(22, Protocol::Tcp, PortState::Open));
2125 assert_eq!(host.open_port_count(), 1, "and counted once");
2126 }
2127
2128 /// A merge is not a sighting, so it does not move `last_seen`.
2129 ///
2130 /// Stamped by hand: on Windows two constructions can land on the same
2131 /// `SystemTime` tick.
2132 #[test]
2133 fn merging_two_records_keeps_the_span_they_were_observed_over() {
2134 let epoch = SystemTime::UNIX_EPOCH;
2135 let at = |secs| epoch + std::time::Duration::from_secs(secs);
2136
2137 let mut early = Host::new(IP_ADDR);
2138 early.first_seen = at(10);
2139 early.last_seen = at(20);
2140
2141 let mut late = Host::new(IP_ADDR);
2142 late.first_seen = at(30);
2143 late.last_seen = at(40);
2144
2145 early.merge(late);
2146
2147 assert_eq!(early.first_seen(), at(10), "the earlier sighting");
2148 assert_eq!(early.last_seen(), at(40), "and the later one");
2149 }
2150
2151 /// Merge promotes on the same ordering the setters use, so folding one
2152 /// phase into another gives what a single phase would.
2153 #[test]
2154 fn merging_promotes_the_status_without_lowering_it() {
2155 let mut h1 = Host::new(IP_ADDR);
2156 h1.set_status(HostStatus::Down);
2157
2158 let mut h2 = Host::new(IP_ADDR);
2159 h2.set_status(HostStatus::Blocked);
2160
2161 h1.merge(h2);
2162 assert_eq!(h1.status(), HostStatus::Blocked);
2163 }
2164
2165 /// The leading address after a merge follows [`Host::consider_primary_ip`],
2166 /// whichever record is `self`.
2167 #[test]
2168 fn merging_two_records_of_one_host_applies_the_same_address_ranking() {
2169 let v4: IpAddr = "192.0.2.10".parse().unwrap();
2170 let lla: IpAddr = "fe80::10".parse().unwrap();
2171
2172 let mut into_link_local = Host::new(lla);
2173 into_link_local.merge(Host::new(v4));
2174 assert_eq!(into_link_local.primary_ip(), v4);
2175
2176 let mut into_v4 = Host::new(v4);
2177 into_v4.merge(Host::new(lla));
2178 assert_eq!(
2179 into_v4.primary_ip(),
2180 v4,
2181 "and the ranking never moves back down"
2182 );
2183
2184 assert_eq!(into_link_local.ips().len(), 2, "nothing is discarded");
2185 assert_eq!(into_v4.ips().len(), 2);
2186 }
2187
2188 /// MACs accumulate into a history, so [`HardwareInfo::most_recent_mac`] reports a
2189 /// timeline.
2190 #[test]
2191 fn every_mac_a_host_answers_under_stays_on_its_record() {
2192 let first = MacAddr::new(0x02, 0, 0, 0, 0, 1);
2193 let second = MacAddr::new(0x02, 0, 0, 0, 0, 2);
2194
2195 let mut host = Host::new(IP_ADDR);
2196 host.record_mac(first);
2197 host.record_mac(second);
2198
2199 let hardware = host.hardware().expect("a sighting was recorded");
2200 assert_eq!(hardware.macs().len(), 2);
2201 assert!(hardware.macs().contains_key(&first));
2202 assert!(hardware.macs().contains_key(&second));
2203 assert_eq!(
2204 host.mac(),
2205 Some(second),
2206 "and the newest is the one the host leads with"
2207 );
2208 }
2209
2210 /// A host kept by a scan's store names the ports each edit recorded or
2211 /// gave a finding, and a host built anywhere else keeps no such list.
2212 ///
2213 /// A journal copies these ports of a wide host, so a missed one would never be
2214 /// written.
2215 #[test]
2216 fn a_tracked_host_names_the_ports_an_edit_touched() {
2217 let mut host = Host::new(IP_ADDR);
2218 host.add_port(Port::new(22, Protocol::Tcp, PortState::Closed));
2219 assert_eq!(host.take_touched_ports(), None, "nothing asked to track");
2220
2221 host.track_touched_ports();
2222 host.add_port(Port::new(80, Protocol::Tcp, PortState::Open));
2223 let touched = host.take_touched_ports().expect("tracked");
2224 assert_eq!(
2225 touched.into_iter().collect::<Vec<_>>(),
2226 [(80, Protocol::Tcp)]
2227 );
2228
2229 let _ = host.add_port_finding(22, Protocol::Tcp, a_finding("det-a"));
2230 let touched = host.take_touched_ports().expect("tracked");
2231 assert_eq!(
2232 touched.into_iter().collect::<Vec<_>>(),
2233 [(22, Protocol::Tcp)]
2234 );
2235 assert_eq!(host.take_touched_ports(), Some(BTreeSet::new()), "taken");
2236
2237 let copy = host.with_only_ports(&[(80, Protocol::Tcp)].into_iter().collect());
2238 assert_eq!(copy.port_count(), 1);
2239 assert_eq!(copy.open_port_count(), 1);
2240 assert_eq!(copy.primary_ip(), host.primary_ip());
2241 }
2242
2243 /// A merge folds one record's ports into another's through the same entry
2244 /// point, so an overlap is not two ports and an endpoint on the other
2245 /// transport is not a collision.
2246 ///
2247 /// A UDP endpoint folded into a record holding all of TCP is accepted.
2248 #[test]
2249 fn merging_two_records_keeps_the_union_of_their_ports() {
2250 // The whole of TCP, half of what the map can hold.
2251 let mut h1 = Host::new(IP_ADDR);
2252 for port in u16::MIN..=u16::MAX {
2253 h1.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
2254 }
2255 assert_eq!(h1.port_count(), usize::from(u16::MAX) + 1);
2256 assert!(!h1.network_roles.contains(&NetworkRole::Truncated));
2257
2258 // An overlapping thousand adds nothing; one UDP endpoint adds one.
2259 let mut h2 = Host::new(IP_ADDR);
2260 for port in 0..1_000u16 {
2261 h2.add_port(Port::new(port, Protocol::Tcp, PortState::Closed));
2262 }
2263 h2.add_port(Port::new(53, Protocol::Udp, PortState::Open));
2264
2265 h1.merge(h2);
2266
2267 assert_eq!(
2268 h1.port_count(),
2269 usize::from(u16::MAX) + 2,
2270 "the union: the whole of TCP and one UDP endpoint"
2271 );
2272 assert!(
2273 !h1.network_roles.contains(&NetworkRole::Truncated),
2274 "nothing was dropped, so nothing here is truncated"
2275 );
2276 assert!(
2277 !h1.network_roles.contains(&NetworkRole::Tarpit),
2278 "one open port is not a tarpit"
2279 );
2280 }
2281
2282 /// The address a dual-stack host is reported under does not depend on which probe
2283 /// answered first.
2284 #[test]
2285 fn the_address_a_host_leads_with_does_not_depend_on_reply_order() {
2286 let v4: IpAddr = "192.0.2.10".parse().unwrap();
2287 let gua: IpAddr = "2001:db8::10".parse().unwrap();
2288 let lla: IpAddr = "fe80::10".parse().unwrap();
2289
2290 // Every order the three replies could arrive in.
2291 for order in [
2292 [v4, gua, lla],
2293 [v4, lla, gua],
2294 [gua, v4, lla],
2295 [gua, lla, v4],
2296 [lla, v4, gua],
2297 [lla, gua, v4],
2298 ] {
2299 let mut host = Host::new(order[0]);
2300 for ip in order {
2301 host.consider_primary_ip(ip);
2302 }
2303
2304 assert_eq!(
2305 host.primary_ip(),
2306 v4,
2307 "arrival order {order:?} must not change which address leads"
2308 );
2309 assert_eq!(host.ips().len(), 3, "and none of them is discarded");
2310 }
2311 }
2312
2313 /// Loopback, multicast and the unspecified address do not rank above a link-local
2314 /// address.
2315 #[test]
2316 fn only_a_globally_scoped_address_outranks_a_link_local_one() {
2317 let lla: IpAddr = "fe80::10".parse().unwrap();
2318
2319 for scoped in ["2001:db8::10", "fd00::10"] {
2320 let mut host = Host::new(lla);
2321 host.consider_primary_ip(scoped.parse().unwrap());
2322 assert_eq!(
2323 host.primary_ip().to_string(),
2324 scoped,
2325 "{scoped} names the host"
2326 );
2327 }
2328
2329 for useless in ["::1", "::", "ff02::1"] {
2330 let mut host = Host::new(lla);
2331 host.consider_primary_ip(useless.parse().unwrap());
2332 assert_eq!(
2333 host.primary_ip(),
2334 lla,
2335 "{useless} does not identify the host to anyone"
2336 );
2337 }
2338 }
2339
2340 /// Without IPv4, a globally scoped address leads over a link-local one.
2341 #[test]
2342 fn a_global_address_leads_over_a_link_local_one() {
2343 let gua: IpAddr = "2001:db8::10".parse().unwrap();
2344 let lla: IpAddr = "fe80::10".parse().unwrap();
2345
2346 let mut from_lla = Host::new(lla);
2347 from_lla.consider_primary_ip(gua);
2348 assert_eq!(from_lla.primary_ip(), gua);
2349
2350 let mut from_gua = Host::new(gua);
2351 from_gua.consider_primary_ip(lla);
2352 assert_eq!(
2353 from_gua.primary_ip(),
2354 gua,
2355 "and the ranking never moves back down"
2356 );
2357 }
2358
2359 /// A tie keeps the incumbent, so a host with several equally good addresses
2360 /// does not flip between them as replies arrive.
2361 #[test]
2362 fn an_equally_good_address_does_not_displace_the_current_one() {
2363 let first: IpAddr = "2001:db8::1".parse().unwrap();
2364 let second: IpAddr = "2001:db8::2".parse().unwrap();
2365
2366 let mut host = Host::new(first);
2367 assert!(!host.consider_primary_ip(second));
2368 assert_eq!(host.primary_ip(), first);
2369 assert!(
2370 host.ips().contains(&second),
2371 "it is still an address it has"
2372 );
2373 }
2374
2375 fn a_finding(detection_id: &str) -> Finding {
2376 use crate::model::confidence::Confidence;
2377 use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
2378 Finding::new(
2379 DetectionId::new(detection_id, Version::new(1, 0, 0), "hash").unwrap(),
2380 "A host-level finding",
2381 Severity::High,
2382 Confidence::Certain,
2383 DetectionClass::ActiveBenign,
2384 )
2385 .unwrap()
2386 }
2387
2388 #[test]
2389 fn the_same_finding_recorded_twice_is_one() {
2390 let mut host = Host::new(IP_ADDR);
2391 assert!(host.add_finding(a_finding("det-a")), "the first is new");
2392 assert!(
2393 !host.add_finding(a_finding("det-a")),
2394 "an identical re-firing is not new information"
2395 );
2396 assert_eq!(host.findings().count(), 1);
2397 }
2398
2399 #[test]
2400 fn a_merge_keeps_both_hosts_findings() {
2401 // A merge that forgot findings would report a clean host.
2402 let mut base = Host::new(IP_ADDR);
2403 base.add_finding(a_finding("det-a"));
2404
2405 let mut other = Host::new(IP_ADDR);
2406 other.add_finding(a_finding("det-b"));
2407
2408 base.merge(other);
2409
2410 let ids: Vec<String> = base
2411 .findings()
2412 .map(|f| f.detection().id().to_string())
2413 .collect();
2414 assert_eq!(ids.len(), 2, "a merge must not drop the other's findings");
2415 assert!(ids.contains(&"det-a".to_string()));
2416 assert!(ids.contains(&"det-b".to_string()));
2417 }
2418}