Skip to main content

zond_engine/model/host/
status.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//! # Whether a host is there, and what says so
10//!
11//! [`HostStatus`] is the verdict and [`StatusReason`] is the evidence behind
12//! it: which protocol produced it, which address sent it, and what it said.
13//!
14//! A scan promotes along `HostStatus`'s ordering and never lowers, so the verdict does
15//! not depend on arrival order.
16//!
17//! A host keeps every reason it collected, so "up" can be checked.
18//!
19//! Who sent a reason is [`EvidenceSource`]: the host, a named middlebox, or a middlebox
20//! the scan's [`Exclusions`](crate::model::exclusion::Exclusions) forbid it to name, as
21//! with [`Hop::withheld`](crate::model::host::Hop::withheld).
22
23use std::net::IpAddr;
24use std::sync::Arc;
25
26/// The high-level reachability state of a network host.
27///
28/// Ordered by how strong the evidence is: `Unknown < Down < Blocked < Up`.
29///
30/// [`Host::merge`](crate::model::host::Host::merge) and
31/// [`Host::record_evidence`](crate::model::host::Host::record_evidence) promote along
32/// it and never lower, so a router's late ICMP unreachable cannot overwrite the host's
33/// own ARP reply.
34///
35/// The ordering depends on one rule every producer obeys: **silence never moves the
36/// status.** Every variant but `Unknown` is backed by a received packet, so ranking by
37/// aliveness also ranks by strength of evidence.
38#[non_exhaustive]
39#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
40pub enum HostStatus {
41    /// Nothing was received about this host. A timeout means this, not
42    /// [`HostStatus::Down`]: silence cannot tell a dead host from an unreachable one.
43    Unknown,
44    /// An intermediary reported this address unreachable, by an ICMP host
45    /// unreachable, no route, or address unreachable quoting a probe this scan
46    /// sent. Never inferred from silence.
47    Down,
48    /// An intermediary explicitly rejected traffic to this address by policy, so a
49    /// perimeter is enforced around it though the host has not answered.
50    Blocked,
51    /// The host answered for itself. Any packet sourced by the host proves this,
52    /// including ones that are negative about the port they report on: a TCP RST
53    /// and an ICMP port unreachable each require a live stack to produce.
54    Up,
55}
56
57impl HostStatus {
58    /// Every reachability verdict, in declaration order, which is least
59    /// definitive first.
60    ///
61    /// The wire round trip and the exported schema are checked against this list.
62    pub const ALL: &'static [Self] = &[Self::Unknown, Self::Down, Self::Blocked, Self::Up];
63}
64
65/// Known protocols or events that provide evidence of host reachability.
66///
67/// Probe types are added as the engine learns them.
68#[derive(Debug, Clone, PartialEq, Eq, Hash)]
69#[non_exhaustive]
70pub enum StatusProtocol {
71    /// Discovered via Address Resolution Protocol (Layer 2). Usually confirms local adjacency.
72    Arp,
73    /// Discovered via IPv6 Neighbor Discovery at layer 2: a neighbor
74    /// advertisement, solicited or in answer to an all-nodes solicitation. The
75    /// IPv6 counterpart of [`StatusProtocol::Arp`], and equally conclusive,
76    /// since the reply came off the local segment.
77    Ndp,
78    /// Discovered via ICMP Echo Request/Reply.
79    IcmpEcho,
80    /// Answered an ICMP timestamp request (RFC 792), which is a different
81    /// question from an echo and is answered by hosts that drop one.
82    ///
83    /// IPv4 only: RFC 4443 defines no timestamp message. The reply also carries the
84    /// target's clock.
85    IcmpTimestamp,
86    /// Discovered via an ICMP Destination Unreachable quoting one of this scan's
87    /// probes. What it proves depends on who sent it and which code it carried,
88    /// which is why [`StatusReason::source`] exists.
89    IcmpUnreachable,
90    /// Discovered via the SYN+ACK or RST a half-open SYN probe drew.
91    TcpSyn,
92    /// Discovered via a TCP connection the scanning host's own stack made:
93    /// a handshake it completed, or a reset it surfaced as a refused
94    /// connection.
95    ///
96    /// Separate from [`TcpSyn`](Self::TcpSyn) because it is more visible: a completed
97    /// connection reaches the service, which may log it.
98    TcpConnect,
99    /// Discovered via a TCP segment answering a raw probe that was not a SYN.
100    ///
101    /// A RST answering a FIN, a flagless segment or a bare ACK says only that the stack
102    /// is alive. Which probe drew it is in
103    /// [`StatusReason::details`](super::StatusReason::details).
104    Tcp,
105    /// Discovered via a DHCP server reply overheard on the segment.
106    ///
107    /// Separate from [`Udp`](Self::Udp) because it names what answered.
108    ///
109    /// Unsolicited, unlike everything else here: a DHCP server answers the segment's
110    /// traffic while a sweep is listening.
111    ///
112    /// Proves only that the sender is there; whether it is a
113    /// [`NetworkRole::DhcpServer`](crate::model::host::NetworkRole::DhcpServer) is a
114    /// separate question a relay can confuse. See `DhcpProtocol`.
115    Dhcp,
116    /// Discovered via a valid application-level response over UDP.
117    ///
118    /// Names only the transport. Where the engine can name what answered, it has a
119    /// variant for it.
120    Udp,
121    /// Discovered via an SCTP chunk answering an INIT probe.
122    ///
123    /// Either answer proves the host is there: an INIT-ACK is an endpoint
124    /// willing to open an association, and an ABORT is the same stack refusing
125    /// one. Which of the two arrived is named in
126    /// [`StatusReason::details`](super::StatusReason::details), as it is for
127    /// [`Tcp`](Self::Tcp).
128    Sctp,
129    /// A custom discovery method initiated by a specialized scanning script.
130    Custom(Arc<str>),
131}
132
133impl StatusProtocol {
134    /// Every protocol event this build names, in declaration order.
135    ///
136    /// [`Custom`](Self::Custom) carries a strategy-chosen name, so it is written with a
137    /// `custom:` prefix that the exported schema matches on.
138    ///
139    /// The schema holds the rest as a closed list, and the export conformance suite
140    /// checks it against this.
141    pub const ALL: &'static [Self] = &[
142        Self::Arp,
143        Self::Ndp,
144        Self::IcmpEcho,
145        Self::IcmpTimestamp,
146        Self::IcmpUnreachable,
147        Self::TcpSyn,
148        Self::TcpConnect,
149        Self::Tcp,
150        Self::Dhcp,
151        Self::Udp,
152        Self::Sctp,
153    ];
154}
155
156/// A structured rationale for a host's reachability state.
157///
158/// `StatusReason` pairs a protocol event with optional human-readable or machine-parsable
159/// details to provide a transparent "audit trail" for host discovery.
160#[must_use]
161#[derive(Debug, Clone, PartialEq, Eq, Hash)]
162#[non_exhaustive]
163pub struct StatusReason {
164    /// The specific protocol-level event that triggered this status.
165    pub protocol: StatusProtocol,
166
167    /// Who sent this evidence: the host it is about, or something in the path
168    /// speaking for it.
169    ///
170    /// An ICMP error names two addresses: its sender and the destination of the
171    /// datagram it quotes. A port unreachable from the target proves it alive; from a
172    /// middlebox it proves only that something in the path speaks for the address, as
173    /// a NAT may.
174    pub source: EvidenceSource,
175
176    /// Extended details about the response (e.g., "Received TCP RST", "TTL Exceeded in transit").
177    ///
178    /// An `Arc<str>`, since thousands of hosts report identical rationales.
179    pub details: Option<Arc<str>>,
180}
181
182impl StatusReason {
183    /// Creates a new `StatusReason` with the specified protocol and details.
184    pub fn new(protocol: StatusProtocol, details: impl Into<Arc<str>>) -> Self {
185        Self {
186            protocol,
187            source: EvidenceSource::Host,
188            details: Some(details.into()),
189        }
190    }
191
192    /// Creates a new `StatusReason` containing only protocol-level evidence without extra details.
193    pub fn basic(protocol: StatusProtocol) -> Self {
194        Self {
195            protocol,
196            source: EvidenceSource::Host,
197            details: None,
198        }
199    }
200
201    /// Attributes this evidence to the address that actually sent it.
202    ///
203    /// Only when `source` is not the host the reason is recorded against.
204    pub fn from_source(mut self, source: IpAddr) -> Self {
205        self.source = EvidenceSource::Intermediary(source);
206        self
207    }
208}
209
210/// Who sent a piece of evidence about a host.
211///
212/// One value, so a withheld sender carrying an address cannot be built, as with
213/// [`Hop`](crate::model::host::Hop).
214///
215/// Not `#[non_exhaustive]`: the three variants partition the cases, and a reader must
216/// handle each without a wildcard arm.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
218pub enum EvidenceSource {
219    /// The host the evidence is about sent it, which is the strongest claim a
220    /// reason can make.
221    Host,
222    /// Something in the path sent it about the host, from this address: a
223    /// router or firewall reporting the host unreachable, or a NAT answering on
224    /// its behalf.
225    Intermediary(IpAddr),
226    /// Something in the path sent it about the host, from an address the
227    /// scan's exclusions forbid it to report.
228    ///
229    /// Second-hand evidence whose sender the scan will not name. The finding about the
230    /// host is kept.
231    ///
232    /// For reading a record back; a scan records evidence as it arrived and withholds
233    /// the sender afterwards.
234    Withheld,
235}
236
237impl EvidenceSource {
238    /// The address that sent the evidence, or `None` where the host sent it
239    /// or the sender is [withheld](Self::is_withheld).
240    pub fn address(&self) -> Option<IpAddr> {
241        match self {
242            Self::Intermediary(address) => Some(*address),
243            Self::Host | Self::Withheld => None,
244        }
245    }
246
247    /// Whether the evidence came second-hand from an address the scan may not
248    /// report.
249    ///
250    /// The one case where [`address`](Self::address) is `None` but the host did not
251    /// answer for itself.
252    pub fn is_withheld(&self) -> bool {
253        *self == Self::Withheld
254    }
255
256    /// Withholds the sender if `keep` refuses its address, and returns whether
257    /// it did.
258    pub(crate) fn withhold(&mut self, keep: impl Fn(&IpAddr) -> bool) -> bool {
259        match self {
260            Self::Intermediary(address) if !keep(address) => {
261                *self = Self::Withheld;
262                true
263            }
264            Self::Host | Self::Intermediary(_) | Self::Withheld => false,
265        }
266    }
267}
268
269impl HostStatus {
270    /// Returns `true` if the host is confirmed to be fully online and responding.
271    #[inline]
272    pub fn is_up(&self) -> bool {
273        matches!(self, HostStatus::Up)
274    }
275
276    /// Returns `true` if the host is explicitly confirmed to be offline.
277    #[inline]
278    pub fn is_down(&self) -> bool {
279        matches!(self, HostStatus::Down)
280    }
281
282    /// Returns `true` if there is evidence the host is present on the network,
283    /// even if communication is restricted by a firewall.
284    #[inline]
285    pub fn is_alive(&self) -> bool {
286        matches!(self, HostStatus::Up | HostStatus::Blocked)
287    }
288}
289
290impl std::fmt::Display for HostStatus {
291    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
292        match self {
293            HostStatus::Unknown => write!(f, "Unknown"),
294            HostStatus::Down => write!(f, "Down"),
295            HostStatus::Blocked => write!(f, "Blocked"),
296            HostStatus::Up => write!(f, "Up"),
297        }
298    }
299}
300
301// ╔════════════════════════════════════════════╗
302// ║ ████████╗███████╗███████╗████████╗███████╗ ║
303// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
304// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
305// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
306// ║    ██║   ███████╗███████║   ██║   ███████║ ║
307// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
308// ╚════════════════════════════════════════════╝
309
310#[cfg(test)]
311mod tests {
312    use super::*;
313
314    /// The declaration order is the promotion rule `Host::record_evidence` follows.
315    #[test]
316    fn the_variant_order_ranks_evidence_from_weakest_to_strongest() {
317        assert!(HostStatus::Unknown < HostStatus::Down);
318        assert!(HostStatus::Down < HostStatus::Blocked);
319        assert!(HostStatus::Blocked < HostStatus::Up);
320    }
321
322    /// A `Blocked` host is alive, so it is carried into a port scan.
323    #[test]
324    fn a_blocked_host_counts_as_alive_and_an_unanswered_one_does_not() {
325        assert!(HostStatus::Up.is_alive());
326        assert!(HostStatus::Blocked.is_alive());
327        assert!(!HostStatus::Down.is_alive());
328        assert!(!HostStatus::Unknown.is_alive());
329    }
330
331    /// Every variant renders distinctly.
332    #[test]
333    fn every_status_renders_under_its_own_name() {
334        let rendered: Vec<String> = [
335            HostStatus::Unknown,
336            HostStatus::Down,
337            HostStatus::Blocked,
338            HostStatus::Up,
339        ]
340        .iter()
341        .map(ToString::to_string)
342        .collect();
343
344        assert_eq!(rendered, ["Unknown", "Down", "Blocked", "Up"]);
345    }
346
347    /// A reason carries its protocol and, when someone other than the host sent it,
348    /// the sender's address.
349    #[test]
350    fn a_reason_records_its_protocol_and_who_it_came_from() {
351        let unattributed = StatusReason::new(
352            StatusProtocol::Custom(Arc::from("dns-probe")),
353            "Resolved A record successfully",
354        );
355
356        assert_eq!(
357            unattributed.protocol,
358            StatusProtocol::Custom(Arc::from("dns-probe"))
359        );
360        assert_eq!(
361            unattributed.details.as_deref(),
362            Some("Resolved A record successfully")
363        );
364        assert_eq!(
365            unattributed.source,
366            EvidenceSource::Host,
367            "unqualified means the host answered for itself"
368        );
369
370        let router: IpAddr = "192.0.2.1".parse().expect("a valid address");
371        let attributed = StatusReason::basic(StatusProtocol::IcmpUnreachable).from_source(router);
372
373        assert_eq!(attributed.source, EvidenceSource::Intermediary(router));
374        assert_eq!(attributed.details, None);
375    }
376
377    /// Withholding reaches only a named sender the policy refuses, never the host's
378    /// own evidence.
379    #[test]
380    fn only_a_refused_sender_is_withheld() {
381        let refused: IpAddr = "198.51.100.1".parse().expect("a valid address");
382        let allowed: IpAddr = "192.0.2.1".parse().expect("a valid address");
383        let keep = |address: &IpAddr| *address != refused;
384
385        let mut named = EvidenceSource::Intermediary(refused);
386        assert!(named.withhold(keep));
387        assert_eq!(named, EvidenceSource::Withheld);
388        assert_eq!(named.address(), None);
389
390        for mut untouched in [
391            EvidenceSource::Host,
392            EvidenceSource::Intermediary(allowed),
393            EvidenceSource::Withheld,
394        ] {
395            let before = untouched;
396            assert!(!untouched.withhold(keep), "{before:?}");
397            assert_eq!(untouched, before);
398        }
399    }
400}