Skip to main content

zond_engine/diff/
significance.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//! # How much a change is worth somebody's attention
10//!
11//! Two scans of a live network always differ: reverse names move, a load balancer
12//! hands out a different certificate, a service reports a newer patch level. Among
13//! that is what a person needs to see: a port that opened, a certificate that
14//! lapsed, a host that started answering DNS. [`Significance`] grades changes to
15//! tell them apart, and every ranking in the crate lives in this module, so the
16//! policy reads as one table.
17//!
18//! ## What it does not rank
19//!
20//! Whether the change happened at all. That is
21//! [`Presence::is_confirmed`](crate::diff::Presence): a port that appeared on
22//! ground the earlier scan never walked is not a finding. The two axes are kept
23//! apart the way a [`Finding`] keeps its severity apart from its confidence.
24//!
25//! They meet in one place. A delta's own grade is the number a caller sorts by, so
26//! [`PortDelta::significance`](crate::diff::PortDelta::significance) and
27//! [`HostDelta::significance`](crate::diff::HostDelta::significance) answer
28//! [`Routine`](Significance::Routine) for an appearance or disappearance the other
29//! scan cannot be shown to have looked for. Each change's own grade, and the
30//! presence, remain readable.
31//!
32//! ## What it does not know
33//!
34//! Which host matters. A new listener on a payment terminal and on a spare laptop
35//! are the same change here, since nothing in two scan reports says which is
36//! which. The grade is what a change means on any network. Policy about one
37//! particular network, such as which hosts may serve DHCP or which segments are
38//! production, is the caller's to apply on top.
39//!
40//! ## The table
41//!
42//! [`Urgent`](Significance::Urgent) is a short list:
43//!
44//! - an endpoint that is accepting connections and was not,
45//! - a certificate that has lapsed,
46//! - a finding at [`High`](crate::model::finding::Severity::High) or
47//!   [`Critical`](crate::model::finding::Severity::Critical).
48//!
49//! [`Notable`](Significance::Notable) is what a person reads in the morning: an
50//! endpoint that stopped accepting connections, a host that appeared or went
51//! away, a service that changed name or version, an operating system that changed
52//! under an address, a hardware address, an inferred role, a conclusion about the
53//! filter in front of a host, an IP protocol its stack started or stopped taking
54//! delivery of, a negotiated TLS version, a certificate presented, withdrawn or
55//! newly inside its expiry threshold, and a finding at
56//! [`Medium`](crate::model::finding::Severity::Medium).
57//!
58//! [`Routine`](Significance::Routine) is everything else, which is most of a diff:
59//! reverse names, address lists, hardware vendors, platform identifiers, product
60//! and version detail below the version itself, cipher suites, offered application
61//! protocols, a certificate rotated onto a fresh one, a service identified where
62//! the earlier scan had not asked, a port state moving between two verdicts that
63//! are neither of them open, and a finding that was resolved or graded down.
64
65use crate::diff::ScanDiff;
66use crate::diff::change::{Change, Presence};
67use crate::diff::host::{HostChange, HostDelta, Reassessment};
68use crate::diff::port::{CertificateChange, PortChange, PortDelta, SecurityChange, ServiceChange};
69use crate::model::finding::{Finding, Severity};
70use crate::model::host::HostStatus;
71use crate::model::port::PortState;
72
73/// How much a change is worth somebody's attention.
74///
75/// Three grades, ordered, so a caller can sort a change list or filter it with a
76/// comparison. The module documentation lists which change lands where.
77///
78/// ```
79/// use zond_engine::diff::{ScanDiff, Significance};
80/// # use zond_engine::report::ScanReport;
81/// # fn example(last_night: &ScanReport, tonight: &ScanReport) {
82/// let diff = ScanDiff::between(last_night, tonight);
83///
84/// for host in diff.hosts() {
85///     if host.significance() >= Significance::Notable {
86///         println!("{} {}", host.address(), host.significance().label());
87///     }
88/// }
89/// # }
90/// ```
91#[non_exhaustive]
92#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
93pub enum Significance {
94    /// A change a live network makes on its own, and the grade of anything the
95    /// comparison cannot vouch for.
96    Routine,
97    /// Worth a person reading.
98    Notable,
99    /// Worth a person acting on.
100    Urgent,
101}
102
103impl Significance {
104    /// Every grade, least first, which is the order [`Ord`] ranks by.
105    ///
106    /// The export conformance suite checks this against the exported comparison
107    /// schema.
108    pub const ALL: &'static [Self] = &[Self::Routine, Self::Notable, Self::Urgent];
109
110    /// The human label, capitalised for a report a person reads.
111    ///
112    /// Separate from the wire name: the label may be reworded, the wire name may
113    /// not.
114    pub const fn label(self) -> &'static str {
115        match self {
116            Self::Routine => "Routine",
117            Self::Notable => "Notable",
118            Self::Urgent => "Urgent",
119        }
120    }
121
122    /// What a finding of this severity amounts to as a change.
123    ///
124    /// Read off the detection's own severity, since the detection has already
125    /// judged how bad its claim is.
126    pub const fn of_severity(severity: Severity) -> Self {
127        match severity {
128            Severity::Info | Severity::Low => Self::Routine,
129            Severity::Medium => Self::Notable,
130            Severity::High | Severity::Critical => Self::Urgent,
131        }
132    }
133
134    /// The stronger of two grades.
135    const fn max(self, other: Self) -> Self {
136        if (self as u8) >= (other as u8) {
137            self
138        } else {
139            other
140        }
141    }
142}
143
144impl HostChange {
145    /// How much this change is worth somebody's attention.
146    ///
147    /// Matched with no wildcard, so a new kind of change fails to compile here
148    /// until somebody decides what it is worth.
149    pub fn significance(&self) -> Significance {
150        match self {
151            // Only there-or-not is graded. Blocked to up means the host answered
152            // for itself where something else had, which `Filtering` reports.
153            HostChange::Status(status) => match answers(status.before) == answers(status.after) {
154                true => Significance::Routine,
155                false => Significance::Notable,
156            },
157
158            // Each is somebody changing the machine or its path. A name the
159            // machine states is set on the machine; a reverse name is DNS's.
160            HostChange::Os(_)
161            | HostChange::Macs { .. }
162            | HostChange::Names { .. }
163            | HostChange::Roles { .. }
164            | HostChange::Filtering { .. }
165            | HostChange::IpProtocols { .. } => Significance::Notable,
166
167            // A reverse name is DNS, an address list is DHCP, and a vendor follows
168            // from the hardware address.
169            HostChange::Hostname(_) | HostChange::Addresses { .. } | HostChange::Vendor(_) => {
170                Significance::Routine
171            }
172
173            HostChange::Findings {
174                appeared,
175                resolved,
176                reassessed,
177            } => of_findings(appeared, resolved, reassessed),
178        }
179    }
180}
181
182impl PortChange {
183    /// How much this change is worth somebody's attention.
184    ///
185    /// Matched with no wildcard, like [`HostChange::significance`].
186    pub fn significance(&self) -> Significance {
187        match self {
188            PortChange::State(state) => of_state(state),
189            PortChange::Service(service) => of_service(service),
190            PortChange::Security(security) => of_security(security),
191            // An unsettled claim says how far the scan got, so it grades as
192            // nothing moved, like an unreached port.
193            PortChange::Findings {
194                appeared,
195                resolved,
196                unsettled: _,
197                reassessed,
198            } => of_findings(appeared, resolved, reassessed),
199        }
200    }
201}
202
203impl PortDelta {
204    /// How much this endpoint is worth somebody's attention.
205    ///
206    /// The strongest of what moved, and [`Routine`](Significance::Routine) for an
207    /// endpoint whose appearance or disappearance the other scan cannot be shown
208    /// to have looked for; [`presence`](Self::presence) keeps the reason.
209    pub fn significance(&self) -> Significance {
210        // For an endpoint that changed state this repeats its `State` grade. It
211        // matters for one that appeared or went away, which carries no changes.
212        let presence = if !self.presence().is_confirmed() {
213            Significance::Routine
214        } else if self.is_opened() {
215            Significance::Urgent
216        } else if self.is_closed() {
217            Significance::Notable
218        } else {
219            Significance::Routine
220        };
221
222        self.changes()
223            .iter()
224            .map(PortChange::significance)
225            .fold(presence, Significance::max)
226    }
227}
228
229impl HostDelta {
230    /// How much this host is worth somebody's attention.
231    ///
232    /// The strongest of what moved on the host and on any of its endpoints. An
233    /// unconfirmed appearance or disappearance contributes
234    /// [`Routine`](Significance::Routine) of its own, as an endpoint's does.
235    ///
236    /// Its endpoints are still folded in, each answering the coverage question for
237    /// itself, since a scope places addresses and port sets separately.
238    pub fn significance(&self) -> Significance {
239        let presence = match self.presence() {
240            Presence::Both => Significance::Routine,
241            presence if !presence.is_confirmed() => Significance::Routine,
242            Presence::Added { .. } | Presence::Removed { .. } => Significance::Notable,
243        };
244
245        let own = self
246            .changes()
247            .iter()
248            .map(HostChange::significance)
249            .fold(presence, Significance::max);
250
251        self.ports()
252            .iter()
253            .map(PortDelta::significance)
254            .fold(own, Significance::max)
255    }
256}
257
258impl ScanDiff {
259    /// How much this comparison is worth somebody's attention: the grade of the
260    /// host that carries the strongest change.
261    ///
262    /// [`Routine`](Significance::Routine) for a comparison that found nothing;
263    /// [`is_empty`](Self::is_empty) tells that apart from only routine changes.
264    pub fn significance(&self) -> Significance {
265        self.hosts()
266            .iter()
267            .map(HostDelta::significance)
268            .fold(Significance::Routine, Significance::max)
269    }
270}
271
272/// Whether a status means the host is there.
273///
274/// [`Blocked`](HostStatus::Blocked) counts: something is enforcing a perimeter
275/// around the address.
276const fn answers(status: HostStatus) -> bool {
277    matches!(status, HostStatus::Up | HostStatus::Blocked)
278}
279
280/// What a port's verdict moving amounts to.
281///
282/// Only openness is graded, since only openness says what the network offers. The
283/// other verdicts differ in what the probe could establish, which is down to a
284/// firewall or a retry budget.
285fn of_state(state: &Change<PortState>) -> Significance {
286    let was_open = state.before == PortState::Open;
287    let is_open = state.after == PortState::Open;
288
289    match (was_open, is_open) {
290        (false, true) => Significance::Urgent,
291        (true, false) => Significance::Notable,
292        _ => Significance::Routine,
293    }
294}
295
296/// What a change to the thing listening amounts to.
297fn of_service(change: &ServiceChange) -> Significance {
298    match change {
299        // Something else is listening, or the same thing at a different release
300        // or build, which is how a patch or rollback looks from outside.
301        ServiceChange::Name(_) | ServiceChange::Version(_) | ServiceChange::Build(_) => {
302            Significance::Notable
303        }
304
305        // An identification appearing or going away usually means the scans
306        // asked differently (`service_detection` is recorded per phase). The rest
307        // is detail under an identity that did not move.
308        ServiceChange::Identified(_)
309        | ServiceChange::Unidentified(_)
310        | ServiceChange::Product(_)
311        | ServiceChange::Vendor(_)
312        | ServiceChange::ExtraInfo(_)
313        | ServiceChange::Cpes { .. } => Significance::Routine,
314    }
315}
316
317/// What a change to an endpoint's transport security amounts to.
318fn of_security(change: &SecurityChange) -> Significance {
319    match change {
320        SecurityChange::TlsVersion(_) => Significance::Notable,
321        SecurityChange::CipherSuite(_) | SecurityChange::Alpn { .. } => Significance::Routine,
322        SecurityChange::Certificate(certificate) => match certificate {
323            // An expired certificate is breaking clients right now.
324            CertificateChange::Expired { .. } => Significance::Urgent,
325            CertificateChange::Expiring { .. }
326            | CertificateChange::Presented(_)
327            | CertificateChange::Withdrawn(_) => Significance::Notable,
328            // Renewal, which a well-run endpoint does every ninety days or so.
329            CertificateChange::Rotated { .. } => Significance::Routine,
330        },
331    }
332}
333
334/// What a subject's findings moving amounts to.
335///
336/// Graded by the findings' own severities. A resolved or downgraded claim is
337/// good news and grades routine.
338fn of_findings(
339    appeared: &[Finding],
340    _resolved: &[Finding],
341    reassessed: &[Reassessment],
342) -> Significance {
343    let raised = reassessed
344        .iter()
345        .filter(|shift| shift.severity.after > shift.severity.before)
346        .map(|shift| Significance::of_severity(shift.severity.after));
347
348    appeared
349        .iter()
350        .map(|finding| Significance::of_severity(finding.severity()))
351        .chain(raised)
352        .fold(Significance::Routine, Significance::max)
353}
354
355// ╔════════════════════════════════════════════╗
356// ║ ████████╗███████╗███████╗████████╗███████╗ ║
357// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
358// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
359// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
360// ║    ██║   ███████╗███████║   ██║   ███████║ ║
361// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
362// ╚════════════════════════════════════════════╝
363
364#[cfg(test)]
365mod tests {
366    use super::*;
367    use crate::model::confidence::Confidence;
368    use crate::model::finding::{DetectionClass, DetectionId, Version};
369
370    fn finding(severity: Severity) -> Finding {
371        Finding::new(
372            DetectionId::new("test", Version::new(1, 0, 0), "hash").expect("a detection id"),
373            "A finding",
374            severity,
375            Confidence::Certain,
376            DetectionClass::ActiveBenign,
377        )
378        .expect("a finding")
379    }
380
381    #[test]
382    fn the_grades_are_ordered_least_first() {
383        assert!(Significance::Routine < Significance::Notable);
384        assert!(Significance::Notable < Significance::Urgent);
385        assert_eq!(
386            Significance::ALL,
387            [
388                Significance::Routine,
389                Significance::Notable,
390                Significance::Urgent
391            ]
392        );
393    }
394
395    /// An opened port is urgent; a closed one is notable.
396    #[test]
397    fn a_port_that_opened_outranks_one_that_closed() {
398        let opened = PortChange::State(Change::new(PortState::NoReply, PortState::Open));
399        let closed = PortChange::State(Change::new(PortState::Open, PortState::NoReply));
400
401        assert_eq!(opened.significance(), Significance::Urgent);
402        assert_eq!(closed.significance(), Significance::Notable);
403        assert!(opened.significance() > closed.significance());
404    }
405
406    /// Two verdicts that are neither of them open differ only in what the probe
407    /// could establish.
408    #[test]
409    fn a_verdict_moving_between_two_closed_states_is_routine() {
410        for (before, after) in [
411            (PortState::NoReply, PortState::Closed),
412            (PortState::Closed, PortState::Reachable),
413            (PortState::ClosedOrNoReply, PortState::NoReply),
414        ] {
415            assert_eq!(
416                PortChange::State(Change::new(before, after)).significance(),
417                Significance::Routine,
418                "{before:?} to {after:?}"
419            );
420        }
421    }
422
423    #[test]
424    fn a_lapsed_certificate_is_the_one_urgent_thing_about_transport_security() {
425        use crate::model::port::security::CertificateInfo;
426        use std::time::{Duration, SystemTime};
427
428        let certificate = CertificateInfo::new(
429            "example.test",
430            "Test CA",
431            SystemTime::UNIX_EPOCH,
432            SystemTime::UNIX_EPOCH + Duration::from_secs(1),
433            "fingerprint",
434        );
435
436        let expired =
437            PortChange::Security(SecurityChange::Certificate(CertificateChange::Expired {
438                certificate: Box::new(certificate.clone()),
439                since: Duration::from_secs(60),
440            }));
441        let expiring =
442            PortChange::Security(SecurityChange::Certificate(CertificateChange::Expiring {
443                certificate: Box::new(certificate.clone()),
444                remaining: Duration::from_secs(60),
445            }));
446        let rotated =
447            PortChange::Security(SecurityChange::Certificate(CertificateChange::Rotated {
448                before: Box::new(certificate.clone()),
449                after: Box::new(certificate),
450            }));
451
452        assert_eq!(expired.significance(), Significance::Urgent);
453        assert_eq!(expiring.significance(), Significance::Notable);
454        assert_eq!(rotated.significance(), Significance::Routine);
455    }
456
457    /// A finding's grade follows the detection's own severity.
458    #[test]
459    fn a_finding_is_graded_by_its_own_severity() {
460        for (severity, expected) in [
461            (Severity::Info, Significance::Routine),
462            (Severity::Low, Significance::Routine),
463            (Severity::Medium, Significance::Notable),
464            (Severity::High, Significance::Urgent),
465            (Severity::Critical, Significance::Urgent),
466        ] {
467            let change = HostChange::Findings {
468                appeared: vec![finding(severity)],
469                resolved: Vec::new(),
470                reassessed: Vec::new(),
471            };
472            assert_eq!(change.significance(), expected, "{severity:?}");
473        }
474    }
475
476    /// A resolved or downgraded finding is routine, however bad the claim was.
477    #[test]
478    fn a_finding_that_went_away_or_was_graded_down_is_routine() {
479        let resolved = HostChange::Findings {
480            appeared: Vec::new(),
481            resolved: vec![finding(Severity::Critical)],
482            reassessed: Vec::new(),
483        };
484        assert_eq!(resolved.significance(), Significance::Routine);
485
486        let downgraded = HostChange::Findings {
487            appeared: Vec::new(),
488            resolved: Vec::new(),
489            reassessed: vec![Reassessment {
490                finding: finding(Severity::Low),
491                severity: Change::new(Severity::Critical, Severity::Low),
492            }],
493        };
494        assert_eq!(downgraded.significance(), Significance::Routine);
495
496        let raised = HostChange::Findings {
497            appeared: Vec::new(),
498            resolved: Vec::new(),
499            reassessed: vec![Reassessment {
500                finding: finding(Severity::Critical),
501                severity: Change::new(Severity::Low, Severity::Critical),
502            }],
503        };
504        assert_eq!(raised.significance(), Significance::Urgent);
505    }
506
507    /// A host that answers where it did not is the change; a host now answering
508    /// from behind a filter is the same host.
509    #[test]
510    fn a_status_change_is_graded_by_whether_the_host_is_there() {
511        let arrived = HostChange::Status(Change::new(HostStatus::Unknown, HostStatus::Up));
512        let went = HostChange::Status(Change::new(HostStatus::Up, HostStatus::Unknown));
513        let blocked = HostChange::Status(Change::new(HostStatus::Up, HostStatus::Blocked));
514        let quiet = HostChange::Status(Change::new(HostStatus::Unknown, HostStatus::Down));
515
516        assert_eq!(arrived.significance(), Significance::Notable);
517        assert_eq!(went.significance(), Significance::Notable);
518        assert_eq!(blocked.significance(), Significance::Routine);
519        assert_eq!(quiet.significance(), Significance::Routine);
520    }
521}