Skip to main content

zond_engine/diff/
port.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//! # What changed about one endpoint
10//!
11//! Ports pair by number and transport, which needs no policy: 443 over TCP is 443
12//! over TCP in both scans. This module holds the vocabulary for what moved: the
13//! state, what is listening, and what it presents at the TLS handshake.
14//!
15//! ## Only the verdicts
16//!
17//! A port carries its verdict and the evidence behind it, and only the verdict is
18//! compared. [`Discovery`](crate::model::port::Discovery) (which packet settled
19//! the state, when, how long it took, who sent it) changes whenever a reply is a
20//! millisecond slower or a different router answers for a blocked port. A
21//! service's confidence score is left out for the same reason.
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::time::Duration;
25use std::time::SystemTime;
26
27use crate::diff::change::{Change, Coverage, Presence};
28use crate::diff::host::Reassessment;
29use crate::model::finding::{Finding, Standing};
30use crate::model::port::security::CertificateInfo;
31use crate::model::port::{Build, Port, PortState, Protocol, Security, Service};
32
33/// One endpoint, as the two scans hold it.
34///
35/// The number and transport identify it in both. What moved is in
36/// [`changes`](Self::changes), and the whole record from each side is kept
37/// alongside for context.
38#[derive(Debug, Clone, PartialEq)]
39pub struct PortDelta {
40    number: u16,
41    protocol: Protocol,
42    presence: Presence,
43    baseline: Option<Port>,
44    current: Option<Port>,
45    changes: Vec<PortChange>,
46}
47
48impl PortDelta {
49    /// The port number, which is the same in both scans.
50    pub fn number(&self) -> u16 {
51        self.number
52    }
53
54    /// The transport, which is the same in both scans.
55    pub fn protocol(&self) -> Protocol {
56        self.protocol
57    }
58
59    /// Which scans hold a record for this endpoint, and what the other one says
60    /// about having looked.
61    pub fn presence(&self) -> Presence {
62        self.presence
63    }
64
65    /// The baseline scan's record, if it has one.
66    ///
67    /// [`None`] also where the baseline's record is [`PortState::Unasked`]: a
68    /// port nobody probed holds no finding. See [`diff`](crate::diff).
69    pub fn baseline(&self) -> Option<&Port> {
70        self.baseline.as_ref()
71    }
72
73    /// The current scan's record, if it has one, read the same way.
74    pub fn current(&self) -> Option<&Port> {
75        self.current.as_ref()
76    }
77
78    /// Everything that moved, in a fixed order: state, then service, then
79    /// transport security.
80    pub fn changes(&self) -> &[PortChange] {
81        &self.changes
82    }
83
84    /// Whether anything is reported for this endpoint at all.
85    ///
86    /// False only for an endpoint both scans hold identically, which the
87    /// comparison does not emit.
88    pub fn is_empty(&self) -> bool {
89        self.presence.is_in_both() && self.changes.is_empty()
90    }
91
92    /// Whether this endpoint accepts connections now and did not before.
93    ///
94    /// Reads the records only. An endpoint the baseline has no record for counts,
95    /// as does one it recorded [`Unasked`](PortState::Unasked). Whether the
96    /// baseline looked at all is [`presence`](Self::presence)'s question:
97    /// [`Presence::is_confirmed`] separates a port that opened from one nobody had
98    /// checked.
99    pub fn is_opened(&self) -> bool {
100        self.state_of(self.current.as_ref()) == Some(PortState::Open)
101            && self.state_of(self.baseline.as_ref()) != Some(PortState::Open)
102    }
103
104    /// Whether this endpoint accepted connections before and does not now.
105    ///
106    /// The mirror of [`is_opened`](Self::is_opened), with the same reading.
107    pub fn is_closed(&self) -> bool {
108        self.state_of(self.baseline.as_ref()) == Some(PortState::Open)
109            && self.state_of(self.current.as_ref()) != Some(PortState::Open)
110    }
111
112    fn state_of(&self, port: Option<&Port>) -> Option<PortState> {
113        port.map(Port::state)
114    }
115}
116
117/// Something that moved about one endpoint.
118///
119/// `#[non_exhaustive]` because new protocols let a scan establish more about a
120/// port, and adding a variant should not need a major version.
121#[non_exhaustive]
122#[derive(Debug, Clone, PartialEq)]
123pub enum PortChange {
124    /// The verdict moved. States are not ordered by how alarming they are:
125    /// `NoReply` to `Closed` is a firewall that stopped dropping probes, not a
126    /// port that shut.
127    State(Change<PortState>),
128    /// What is listening changed or was first identified.
129    Service(ServiceChange),
130    /// What the endpoint presents at the TLS handshake changed.
131    Security(SecurityChange),
132    /// Findings that appeared on the port, findings the current scan stopped
133    /// claiming, and findings whose severity moved. Paired as
134    /// [`HostChange::Findings`](super::host::HostChange::Findings) pairs its own.
135    ///
136    /// A claim the current scan does not make is resolved only where that scan
137    /// settled what the claim rests on; otherwise it goes under `unsettled`, the
138    /// finding-level [`Coverage::Unreached`]. That covers:
139    ///
140    /// - a claim drawn from what the endpoint accepts, where the current scan cut
141    ///   a version walk it rests on short, or made none;
142    /// - a claim drawn from the certificate's posture, where the current scan
143    ///   recorded no certificate (reported beside the
144    ///   [`Withdrawn`](CertificateChange::Withdrawn) for the absence);
145    /// - a vulnerability correlation, where the current scan identified nothing
146    ///   there or named the software without a version.
147    Findings {
148        /// Findings the current scan claims and the baseline did not.
149        appeared: Vec<Finding>,
150        /// Findings the baseline claimed and the current scan does not, other
151        /// than those under `unsettled`.
152        resolved: Vec<Finding>,
153        /// Findings the baseline claimed that the current scan neither claims
154        /// nor settled.
155        unsettled: Vec<Finding>,
156        /// Findings both scans claim, where the severity moved.
157        reassessed: Vec<Reassessment>,
158    },
159}
160
161/// Something that moved about what is listening on an endpoint.
162///
163/// [`Version`](Self::Version) is the one most monitoring looks for: 1.18.0 to
164/// 1.24.0 is a patch that landed, and the other way is a rollback.
165#[non_exhaustive]
166#[derive(Debug, Clone, PartialEq)]
167pub enum ServiceChange {
168    /// Nothing was identified here before, and something is now.
169    Identified(Service),
170    /// Something was identified here before and nothing is now. The service is
171    /// not necessarily gone: the endpoint may not have been asked, which the
172    /// phase's [`service_detection`](crate::report::ScanSettings::service_detection)
173    /// setting records.
174    Unidentified(Service),
175    /// The service is called something else.
176    Name(Change<String>),
177    /// The product behind it changed.
178    Product(Change<Option<String>>),
179    /// The vendor changed.
180    Vendor(Change<Option<String>>),
181    /// The version changed.
182    Version(Change<Option<String>>),
183    /// The trailing detail the fingerprint carried changed.
184    ExtraInfo(Change<Option<String>>),
185    /// Whose build it is, or which build, changed. A new package revision of the
186    /// same upstream version is how a distribution's security update looks from
187    /// outside.
188    Build(Change<Option<Build>>),
189    /// The platform identifiers changed, each list ascending.
190    Cpes {
191        /// Identifiers the current scan has and the baseline did not.
192        gained: Vec<String>,
193        /// Identifiers the baseline had and the current scan does not.
194        lost: Vec<String>,
195    },
196}
197
198/// Something that moved about an endpoint's transport security.
199#[non_exhaustive]
200#[derive(Debug, Clone, PartialEq)]
201pub enum SecurityChange {
202    /// The negotiated protocol version changed.
203    TlsVersion(Change<Option<String>>),
204    /// The negotiated cipher suite changed.
205    CipherSuite(Change<Option<String>>),
206    /// The application protocols offered changed, each list ascending.
207    Alpn {
208        /// Protocols the current scan saw offered and the baseline did not.
209        gained: Vec<String>,
210        /// Protocols the baseline saw offered and the current scan does not.
211        lost: Vec<String>,
212    },
213    /// The certificate changed, or its standing did.
214    Certificate(CertificateChange),
215}
216
217/// Something that moved about the certificate an endpoint presents.
218///
219/// Identity is the SHA-256 fingerprint, so there are no field-level variants: a
220/// certificate whose issuer or validity differs is a different certificate, and
221/// [`Rotated`](Self::Rotated).
222///
223/// [`Expiring`](Self::Expiring) and [`Expired`](Self::Expired) can happen to an
224/// unchanged certificate: the clock crossed a threshold between the two scans.
225/// See [`diff`](crate::diff) for which clock is used.
226#[non_exhaustive]
227#[derive(Debug, Clone, PartialEq)]
228pub enum CertificateChange {
229    /// A certificate is presented where none was before.
230    Presented(CertificateInfo),
231    /// No certificate is presented where one was before.
232    Withdrawn(CertificateInfo),
233    /// A different certificate is presented.
234    Rotated {
235        /// What the baseline scan was shown.
236        before: Box<CertificateInfo>,
237        /// What the current scan was shown.
238        after: Box<CertificateInfo>,
239    },
240    /// The certificate is still valid and inside the expiry threshold at the
241    /// current clock, and was outside it at the baseline's.
242    Expiring {
243        /// The certificate now inside the threshold.
244        certificate: Box<CertificateInfo>,
245        /// How long it has left, at the current scan's clock.
246        remaining: Duration,
247    },
248    /// The certificate is past its validity end at the current clock, and was
249    /// not at the baseline's.
250    Expired {
251        /// The certificate that lapsed.
252        certificate: Box<CertificateInfo>,
253        /// How long ago it lapsed, at the current scan's clock.
254        since: Duration,
255    },
256}
257
258/// Where a certificate stands at one moment.
259///
260/// Unordered. A comparison reports transitions into [`Expiring`](Self::Expiring)
261/// or [`Expired`](Self::Expired), the two a person has to act on.
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263enum Validity {
264    /// Nothing was presented, or the baseline was shown a different certificate,
265    /// so there is no earlier standing to move from.
266    Absent,
267    NotYetValid,
268    Valid,
269    Expiring,
270    Expired,
271}
272
273/// When the two clocks are used and what they are is documented on
274/// [`DiffOptions`](crate::diff::DiffOptions).
275pub(crate) struct Clocks {
276    pub(crate) baseline: SystemTime,
277    pub(crate) current: SystemTime,
278    pub(crate) expiry_threshold: Duration,
279}
280
281/// Compares the endpoints of two hosts, ascending by number and then transport.
282///
283/// Endpoints identical in both scans are left out.
284///
285/// ## An unasked port is not a record
286///
287/// A port a scan named and never probed is on its host at [`PortState::Unasked`],
288/// and is indexed here as that side holding no record for the endpoint, with
289/// coverage [`Coverage::Unreached`]. See [`diff`](crate::diff).
290pub(crate) fn compare<'a>(
291    baseline: &[&'a Port],
292    current: &[&'a Port],
293    presence: PresenceFor<'_>,
294    clocks: &Clocks,
295) -> Vec<PortDelta> {
296    // Indexed: a host from a full-port scan carries tens of thousands of ports,
297    // and a linear find per endpoint would be quadratic. The maps also give the
298    // ascending order the result promises.
299    let index = |ports: &[&'a Port]| -> BTreeMap<(u16, Protocol), &'a Port> {
300        ports
301            .iter()
302            .filter(|port| port.state() != PortState::Unasked)
303            .map(|port| ((port.number(), port.protocol()), *port))
304            .collect()
305    };
306    let unreached = |ports: &[&'a Port]| -> BTreeSet<(u16, Protocol)> {
307        ports
308            .iter()
309            .filter(|port| port.state() == PortState::Unasked)
310            .map(|port| (port.number(), port.protocol()))
311            .collect()
312    };
313
314    let baseline_unreached = unreached(baseline);
315    let current_unreached = unreached(current);
316    let baseline = index(baseline);
317    let current = index(current);
318
319    let keys: BTreeSet<(u16, Protocol)> = baseline.keys().chain(current.keys()).copied().collect();
320
321    let mut deltas = Vec::new();
322    for (number, protocol) in keys {
323        let before = baseline.get(&(number, protocol)).copied();
324        let after = current.get(&(number, protocol)).copied();
325
326        let (presence, changes) = match (before, after) {
327            (Some(_), Some(_)) => (Presence::Both, changes_between(before, after, clocks)),
328            (Some(_), None) => (
329                presence.removed(number, protocol, &current_unreached),
330                Vec::new(),
331            ),
332            (None, Some(_)) => (
333                presence.added(number, protocol, &baseline_unreached),
334                Vec::new(),
335            ),
336            (None, None) => unreachable!("a key comes from one side or the other"),
337        };
338
339        if presence.is_in_both() && changes.is_empty() {
340            continue;
341        }
342
343        deltas.push(PortDelta {
344            number,
345            protocol,
346            presence,
347            baseline: before.cloned(),
348            current: after.cloned(),
349            changes,
350        });
351    }
352
353    deltas
354}
355
356/// What each report says about having probed a given endpoint.
357///
358/// Asked per endpoint, since a scope names the ports it walked and the answer can
359/// differ between 443 and 8080 on the same address.
360pub(crate) struct PresenceFor<'a> {
361    pub(crate) baseline: &'a dyn Fn(u16, Protocol) -> Coverage,
362    pub(crate) current: &'a dyn Fn(u16, Protocol) -> Coverage,
363}
364
365impl PresenceFor<'_> {
366    fn added(
367        &self,
368        number: u16,
369        protocol: Protocol,
370        unreached: &BTreeSet<(u16, Protocol)>,
371    ) -> Presence {
372        Presence::Added {
373            before: Self::coverage(self.baseline, number, protocol, unreached),
374        }
375    }
376
377    fn removed(
378        &self,
379        number: u16,
380        protocol: Protocol,
381        unreached: &BTreeSet<(u16, Protocol)>,
382    ) -> Presence {
383        Presence::Removed {
384            after: Self::coverage(self.current, number, protocol, unreached),
385        }
386    }
387
388    /// What one side says about having probed an endpoint it holds no record
389    /// for.
390    ///
391    /// The side's own record answers first: a port it wrote down as
392    /// [`PortState::Unasked`] is unreached however wide its declared scope.
393    fn coverage(
394        scope: &dyn Fn(u16, Protocol) -> Coverage,
395        number: u16,
396        protocol: Protocol,
397        unreached: &BTreeSet<(u16, Protocol)>,
398    ) -> Coverage {
399        if unreached.contains(&(number, protocol)) {
400            Coverage::Unreached
401        } else {
402            scope(number, protocol)
403        }
404    }
405}
406
407/// Everything that moved between two records of the same endpoint.
408fn changes_between(
409    before: Option<&Port>,
410    after: Option<&Port>,
411    clocks: &Clocks,
412) -> Vec<PortChange> {
413    let (Some(before), Some(after)) = (before, after) else {
414        return Vec::new();
415    };
416
417    let mut changes = Vec::new();
418
419    if let Some(state) = Change::between(before.state(), after.state()) {
420        changes.push(PortChange::State(state));
421    }
422
423    changes.extend(
424        service_changes(before.service(), after.service())
425            .into_iter()
426            .map(PortChange::Service),
427    );
428
429    changes.extend(
430        security_changes(before.security(), after.security(), clocks)
431            .into_iter()
432            .map(PortChange::Security),
433    );
434
435    let (appeared, gone, reassessed) =
436        super::host::findings_between(before.findings(), after.findings());
437
438    // The claim's evidence is in the baseline's record; whether the current scan
439    // settled it is in the current one's.
440    let (unsettled, resolved): (Vec<Finding>, Vec<Finding>) = gone
441        .into_iter()
442        .partition(|finding| standing(finding, before, after) == Some(Standing::Unsettled));
443
444    if !appeared.is_empty()
445        || !resolved.is_empty()
446        || !unsettled.is_empty()
447        || !reassessed.is_empty()
448    {
449        changes.push(PortChange::Findings {
450            appeared,
451            resolved,
452            unsettled,
453            reassessed,
454        });
455    }
456
457    changes
458}
459
460/// Where the current account of an endpoint, `after`, leaves a claim the
461/// baseline's account, `before`, carried, or `None` where the claim is not
462/// one drawn from evidence either record holds.
463///
464/// A claim drawn from the TLS handshake asks the current record's security; a
465/// scan that made no enumeration is treated as an empty one. See
466/// [`Security::standing`].
467///
468/// A vulnerability correlation asks [`correlation_standing`].
469fn standing(finding: &Finding, before: &Port, after: &Port) -> Option<Standing> {
470    if finding.is_correlation() {
471        return correlation_standing(finding, before.service()?, after.service());
472    }
473    let silent = Security::new();
474    let now = after.security().unwrap_or(&silent);
475    now.standing(finding, before.security()?)
476}
477
478/// Where the service `now` identified leaves a correlation `basis`'s
479/// identification drew, or `None` where `basis` carries none of the
480/// identifiers the claim names and so is not what the claim rests on.
481///
482/// Upheld where `now` carries one of them, and overturned where it says something
483/// else runs there: another service, product, or version. That is the upgrade or
484/// replacement the comparison exists to see.
485///
486/// Unsettled where `now` says nothing that tells: no service, a label read off the
487/// port number, or the same software named without a version. A scan without
488/// service detection, or one that matched a product but not its release, did not
489/// say what runs there now. A merge reads it the same way, keeping an older
490/// identification's identifiers beside a newer one that states no version.
491fn correlation_standing(
492    finding: &Finding,
493    basis: &Service,
494    now: Option<&Service>,
495) -> Option<Standing> {
496    let backs = |service: &Service| finding.cpes().any(|cpe| service.cpes().contains(cpe));
497    if !backs(basis) {
498        return None;
499    }
500    let Some(now) = now.filter(|service| !service.is_inferred()) else {
501        return Some(Standing::Unsettled);
502    };
503    if backs(now) {
504        return Some(Standing::Upheld);
505    }
506
507    let differs = |stated: Option<&str>, then: Option<&str>| {
508        stated.is_some_and(|stated| then.is_none_or(|then| stated != then))
509    };
510    let contradicts = now.name() != basis.name()
511        || differs(now.product(), basis.product())
512        || differs(now.version(), basis.version());
513    Some(if contradicts {
514        Standing::Overturned
515    } else {
516        Standing::Unsettled
517    })
518}
519
520/// What moved about the service on an endpoint.
521///
522/// A service *inferred* from the port number is read as no service. Scanners seed
523/// one on every classified port from their own catalogue, so comparing them would
524/// report every catalogue difference between tools or releases.
525fn service_changes(before: Option<&Service>, after: Option<&Service>) -> Vec<ServiceChange> {
526    let before = before.filter(|service| !service.is_inferred());
527    let after = after.filter(|service| !service.is_inferred());
528
529    match (before, after) {
530        (None, None) => Vec::new(),
531        (None, Some(after)) => vec![ServiceChange::Identified(after.clone())],
532        (Some(before), None) => vec![ServiceChange::Unidentified(before.clone())],
533        (Some(before), Some(after)) => {
534            let mut changes = Vec::new();
535
536            if let Some(name) = Change::between(before.name().to_owned(), after.name().to_owned()) {
537                changes.push(ServiceChange::Name(name));
538            }
539            if let Some(product) = optional(before.product(), after.product()) {
540                changes.push(ServiceChange::Product(product));
541            }
542            if let Some(vendor) = optional(before.vendor(), after.vendor()) {
543                changes.push(ServiceChange::Vendor(vendor));
544            }
545            if let Some(version) = optional(before.version(), after.version()) {
546                changes.push(ServiceChange::Version(version));
547            }
548            if let Some(extra) = optional(before.extrainfo(), after.extrainfo()) {
549                changes.push(ServiceChange::ExtraInfo(extra));
550            }
551            if let Some(build) = Change::between(before.build().cloned(), after.build().cloned()) {
552                changes.push(ServiceChange::Build(build));
553            }
554
555            let (gained, lost) = set_change(
556                before.cpes().iter().map(|cpe| cpe.to_string()),
557                after.cpes().iter().map(|cpe| cpe.to_string()),
558            );
559            if !gained.is_empty() || !lost.is_empty() {
560                changes.push(ServiceChange::Cpes { gained, lost });
561            }
562
563            changes
564        }
565    }
566}
567
568/// What moved about the transport security on an endpoint.
569fn security_changes(
570    before: Option<&Security>,
571    after: Option<&Security>,
572    clocks: &Clocks,
573) -> Vec<SecurityChange> {
574    let mut changes = Vec::new();
575
576    let before_version = before.and_then(Security::tls_version);
577    let after_version = after.and_then(Security::tls_version);
578    if let Some(version) = optional(before_version, after_version) {
579        changes.push(SecurityChange::TlsVersion(version));
580    }
581
582    let before_cipher = before.and_then(Security::cipher_suite);
583    let after_cipher = after.and_then(Security::cipher_suite);
584    if let Some(cipher) = optional(before_cipher, after_cipher) {
585        changes.push(SecurityChange::CipherSuite(cipher));
586    }
587
588    let (gained, lost) = set_change(
589        before
590            .map(Security::alpn)
591            .unwrap_or_default()
592            .iter()
593            .map(|p| p.to_string()),
594        after
595            .map(Security::alpn)
596            .unwrap_or_default()
597            .iter()
598            .map(|p| p.to_string()),
599    );
600    if !gained.is_empty() || !lost.is_empty() {
601        changes.push(SecurityChange::Alpn { gained, lost });
602    }
603
604    changes.extend(
605        certificate_changes(before, after, clocks)
606            .into_iter()
607            .map(SecurityChange::Certificate),
608    );
609
610    changes
611}
612
613/// What moved about the certificate, including the expiry crossings that happen to
614/// a certificate nobody touched.
615fn certificate_changes(
616    before: Option<&Security>,
617    after: Option<&Security>,
618    clocks: &Clocks,
619) -> Vec<CertificateChange> {
620    let before_cert = before.and_then(Security::certificate);
621    let after_cert = after.and_then(Security::certificate);
622
623    let mut changes = Vec::new();
624
625    match (before_cert, after_cert) {
626        (None, None) => return changes,
627        (None, Some(after)) => changes.push(CertificateChange::Presented(after.clone())),
628        (Some(before), None) => {
629            changes.push(CertificateChange::Withdrawn(before.clone()));
630            return changes;
631        }
632        (Some(before), Some(after)) => {
633            if before.fingerprint_sha256() != after.fingerprint_sha256() {
634                changes.push(CertificateChange::Rotated {
635                    before: Box::new(before.clone()),
636                    after: Box::new(after.clone()),
637                });
638            }
639        }
640    }
641
642    // The standing of one certificate at two moments: where the certificate
643    // presented now stood when the baseline ran. A certificate the baseline was
644    // not shown stood nowhere, so a rotation onto one that is itself expiring
645    // still reports the expiry.
646    let same_certificate = matches!(
647        (before_cert, after_cert),
648        (Some(before), Some(after))
649            if before.fingerprint_sha256() == after.fingerprint_sha256()
650    );
651    let was = if same_certificate {
652        validity(after, clocks.expiry_threshold, clocks.baseline)
653    } else {
654        Validity::Absent
655    };
656    let is = validity(after, clocks.expiry_threshold, clocks.current);
657
658    if let Some(certificate) = after_cert {
659        match is {
660            Validity::Expiring if was != Validity::Expiring => {
661                let remaining = certificate
662                    .validity_end()
663                    .duration_since(clocks.current)
664                    .unwrap_or_default();
665                changes.push(CertificateChange::Expiring {
666                    certificate: Box::new(certificate.clone()),
667                    remaining,
668                });
669            }
670            Validity::Expired if was != Validity::Expired => {
671                let since = clocks
672                    .current
673                    .duration_since(certificate.validity_end())
674                    .unwrap_or_default();
675                changes.push(CertificateChange::Expired {
676                    certificate: Box::new(certificate.clone()),
677                    since,
678                });
679            }
680            _ => {}
681        }
682    }
683
684    changes
685}
686
687/// Where a certificate stands at `at`.
688fn validity(security: Option<&Security>, threshold: Duration, at: SystemTime) -> Validity {
689    let Some(security) = security else {
690        return Validity::Absent;
691    };
692    let Some(certificate) = security.certificate() else {
693        return Validity::Absent;
694    };
695
696    // `is_cert_expiring_at` checks the bounds again; they are read here only to
697    // tell `NotYetValid` and `Expired` apart.
698    if at < certificate.validity_start() {
699        Validity::NotYetValid
700    } else if at > certificate.validity_end() {
701        Validity::Expired
702    } else if security.is_cert_expiring_at(threshold, at) {
703        Validity::Expiring
704    } else {
705        Validity::Valid
706    }
707}
708
709/// A change between two optional strings, owned so the diff outlives the reports
710/// it was taken from.
711fn optional(before: Option<&str>, after: Option<&str>) -> Option<Change<Option<String>>> {
712    Change::between(before.map(str::to_owned), after.map(str::to_owned))
713}
714
715/// What one set gained and lost against another, both ascending.
716fn set_change(
717    before: impl Iterator<Item = String>,
718    after: impl Iterator<Item = String>,
719) -> (Vec<String>, Vec<String>) {
720    let before: std::collections::BTreeSet<String> = before.collect();
721    let after: std::collections::BTreeSet<String> = after.collect();
722
723    let gained = after.difference(&before).cloned().collect();
724    let lost = before.difference(&after).cloned().collect();
725    (gained, lost)
726}
727
728// ╔════════════════════════════════════════════╗
729// ║ ████████╗███████╗███████╗████████╗███████╗ ║
730// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
731// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
732// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
733// ║    ██║   ███████╗███████║   ██║   ███████║ ║
734// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
735// ╚════════════════════════════════════════════╝
736
737#[cfg(test)]
738mod tests {
739    use super::*;
740    use crate::model::confidence::Confidence;
741    use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
742    use crate::model::tls::{
743        CipherSuite, Interruption, TlsSupport, TlsVersion, UnfinishedVersion, VersionSupport,
744    };
745
746    fn clocks() -> Clocks {
747        Clocks {
748            baseline: SystemTime::UNIX_EPOCH,
749            current: SystemTime::UNIX_EPOCH,
750            expiry_threshold: Duration::from_secs(30 * 24 * 60 * 60),
751        }
752    }
753
754    fn port(state: PortState) -> Port {
755        Port::new(443, Protocol::Tcp, state)
756    }
757
758    fn finding(title: &str) -> Finding {
759        Finding::new(
760            DetectionId::new("audit", Version::new(1, 0, 0), "hash").expect("a detection id"),
761            title,
762            Severity::High,
763            Confidence::Certain,
764            DetectionClass::Passive,
765        )
766        .expect("a titled finding")
767    }
768
769    /// A findings change's four lists: appeared, resolved, unsettled and
770    /// reassessed.
771    type Moved<'a> = (
772        &'a [Finding],
773        &'a [Finding],
774        &'a [Finding],
775        &'a [Reassessment],
776    );
777
778    fn findings_change(changes: &[PortChange]) -> Option<Moved<'_>> {
779        changes.iter().find_map(|change| match change {
780            PortChange::Findings {
781                appeared,
782                resolved,
783                unsettled,
784                reassessed,
785            } => Some((
786                appeared.as_slice(),
787                resolved.as_slice(),
788                unsettled.as_slice(),
789                reassessed.as_slice(),
790            )),
791            _ => None,
792        })
793    }
794
795    #[test]
796    fn an_endpoint_that_did_not_move_reports_nothing() {
797        let before = port(PortState::Open);
798        let after = port(PortState::Open);
799        assert!(changes_between(Some(&before), Some(&after), &clocks()).is_empty());
800    }
801
802    #[test]
803    fn a_state_change_is_reported() {
804        let before = port(PortState::Open);
805        let after = port(PortState::Closed);
806
807        let changes = changes_between(Some(&before), Some(&after), &clocks());
808        assert!(changes.iter().any(|change| matches!(
809            change,
810            PortChange::State(state)
811                if state.before == PortState::Open && state.after == PortState::Closed
812        )));
813    }
814
815    /// A finding arriving on an endpoint is a change, as on a host.
816    #[test]
817    fn a_finding_that_appeared_on_the_endpoint_is_reported() {
818        let before = port(PortState::Open);
819        let mut after = port(PortState::Open);
820        after.add_finding(finding("Weak cipher"));
821
822        let changes = changes_between(Some(&before), Some(&after), &clocks());
823        let (appeared, resolved, _, _) = findings_change(&changes).expect("a findings change");
824        assert_eq!(appeared.len(), 1);
825        assert_eq!(appeared[0].title(), "Weak cipher");
826        assert!(resolved.is_empty());
827    }
828
829    #[test]
830    fn a_finding_that_went_away_from_the_endpoint_is_reported_as_resolved() {
831        let mut before = port(PortState::Open);
832        before.add_finding(finding("Weak cipher"));
833        let after = port(PortState::Open);
834
835        let changes = changes_between(Some(&before), Some(&after), &clocks());
836        let (appeared, resolved, _, _) = findings_change(&changes).expect("a findings change");
837        assert!(appeared.is_empty());
838        assert_eq!(resolved.len(), 1);
839    }
840
841    /// An endpoint enumerated as `support` says, carrying the findings drawn
842    /// from it, as a scan records one.
843    fn enumerated(support: TlsSupport) -> Port {
844        let findings = support.findings();
845        let mut port = port(PortState::Open).with_security(Security::new().with_support(support));
846        for finding in findings {
847            port.add_finding(finding);
848        }
849        port
850    }
851
852    /// TLS 1.0 accepted under AES-128-CBC with RSA key exchange, walked to the
853    /// end.
854    fn ten_accepted() -> TlsSupport {
855        TlsSupport::new().accepting(VersionSupport::new(
856            TlsVersion::Tls10,
857            vec![CipherSuite::from_code(0x002F).expect("a registered suite")],
858            vec![],
859        ))
860    }
861
862    fn titles(findings: &[Finding]) -> Vec<&str> {
863        findings.iter().map(Finding::title).collect()
864    }
865
866    /// A walk the current scan did not finish settled nothing the baseline's
867    /// claim rests on, so the claim's absence is not a fix. A scan whose budget
868    /// ran out during the TLS 1.0 walk must not report TLS 1.0 switched off.
869    #[test]
870    fn a_finding_a_cut_short_walk_did_not_get_back_to_is_not_resolved() {
871        let before = enumerated(ten_accepted());
872        let after = enumerated(TlsSupport::new().leaving_unfinished(UnfinishedVersion::new(
873            TlsVersion::Tls10,
874            Interruption::Stopped,
875        )));
876        assert!(
877            titles(&before.findings().cloned().collect::<Vec<_>>())
878                .contains(&"TLSv1.0 is still accepted"),
879            "the baseline's walk draws the claim this is about"
880        );
881
882        let changes = changes_between(Some(&before), Some(&after), &clocks());
883        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
884        assert!(
885            resolved.is_empty(),
886            "a walk that never finished reported {:?} resolved",
887            titles(resolved)
888        );
889        assert_eq!(
890            titles(unsettled),
891            titles(&before.findings().cloned().collect::<Vec<_>>()),
892            "every claim the baseline drew from TLS 1.0 is said to be unsettled"
893        );
894    }
895
896    /// The counterpart: a walk that finished and found TLS 1.0 refused is the
897    /// fix.
898    #[test]
899    fn a_finding_a_finished_walk_refuted_is_resolved() {
900        let before = enumerated(ten_accepted());
901        let after = enumerated(TlsSupport::new().accepting(VersionSupport::new(
902            TlsVersion::Tls13,
903            vec![CipherSuite::from_code(0x1301).expect("a registered suite")],
904            vec![],
905        )));
906
907        let changes = changes_between(Some(&before), Some(&after), &clocks());
908        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
909        assert!(unsettled.is_empty(), "{:?}", titles(unsettled));
910        assert!(titles(resolved).contains(&"TLSv1.0 is still accepted"));
911    }
912
913    /// An endpoint that completed a handshake and was shown a self-signed
914    /// certificate with `fingerprint`, carrying the posture findings the scan
915    /// draws from it.
916    fn presenting(fingerprint: &str) -> Port {
917        let certificate = CertificateInfo::new(
918            "www.example.test",
919            "www.example.test",
920            SystemTime::UNIX_EPOCH,
921            SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 24 * 60 * 60),
922            fingerprint,
923        )
924        .with_public_key("RSA", 2048);
925        let findings = certificate.findings(SystemTime::UNIX_EPOCH);
926        let mut port = port(PortState::Open).with_security(
927            Security::new()
928                .with_tls_version("TLSv1.3")
929                .with_certificate(certificate),
930        );
931        for finding in findings {
932            port.add_finding(finding);
933        }
934        port
935    }
936
937    /// A handshake the current scan did not complete settled nothing about the
938    /// certificate a posture claim rests on, so the claim's absence is not a
939    /// fix. The service pass records no security for an endpoint whose handshake
940    /// failed, and no certificate for one whose leaf would not parse.
941    #[test]
942    fn a_posture_finding_the_current_scan_saw_no_certificate_for_is_not_resolved() {
943        let before = presenting("aaaa");
944        let unparsed =
945            port(PortState::Open).with_security(Security::new().with_tls_version("TLSv1.3"));
946        assert_eq!(
947            titles(&before.findings().cloned().collect::<Vec<_>>()),
948            ["TLS certificate is self-signed"],
949            "the baseline's certificate draws the claim this is about"
950        );
951
952        for after in [port(PortState::Open), unparsed] {
953            let changes = changes_between(Some(&before), Some(&after), &clocks());
954            assert!(
955                changes.iter().any(|change| matches!(
956                    change,
957                    PortChange::Security(SecurityChange::Certificate(
958                        CertificateChange::Withdrawn(_)
959                    ))
960                )),
961                "the certificate's absence is still reported as such"
962            );
963            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
964            assert!(
965                resolved.is_empty(),
966                "a scan shown no certificate reported {:?} resolved",
967                titles(resolved)
968            );
969            assert_eq!(titles(unsettled), ["TLS certificate is self-signed"]);
970        }
971    }
972
973    /// The counterpart: a scan shown a different certificate settled the claim,
974    /// since the posture belonged to a certificate the endpoint stopped
975    /// presenting.
976    #[test]
977    fn a_posture_finding_the_current_scan_was_shown_another_certificate_for_is_resolved() {
978        let before = presenting("aaaa");
979        let after = port(PortState::Open).with_security(
980            Security::new()
981                .with_tls_version("TLSv1.3")
982                .with_certificate(
983                    CertificateInfo::new(
984                        "www.example.test",
985                        "Example CA",
986                        SystemTime::UNIX_EPOCH,
987                        SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 24 * 60 * 60),
988                        "bbbb",
989                    )
990                    .with_public_key("RSA", 2048),
991                ),
992        );
993
994        let changes = changes_between(Some(&before), Some(&after), &clocks());
995        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
996        assert!(unsettled.is_empty(), "{:?}", titles(unsettled));
997        assert_eq!(titles(resolved), ["TLS certificate is self-signed"]);
998    }
999
1000    /// An endpoint identified as Apache httpd 2.4.49, carrying the CVE
1001    /// correlation drawn from its CPE.
1002    fn correlated() -> Port {
1003        const CPE: &str = "cpe:/a:apache:http_server:2.4.49";
1004        let mut port = port(PortState::Open);
1005        port.set_service(
1006            Service::new("http", 90)
1007                .with_product("Apache httpd")
1008                .with_version("2.4.49")
1009                .with_cpe(CPE),
1010        );
1011        port.add_finding(
1012            finding("Apache httpd 2.4.49: path traversal")
1013                .with_reference(crate::model::finding::Reference::Cve(
1014                    "CVE-2021-41773".into(),
1015                ))
1016                .with_cpe(CPE),
1017        );
1018        port
1019    }
1020
1021    /// A correlation is not resolved by a scan that ran without service
1022    /// detection, labelled the port by its number alone, or named the software
1023    /// without a version: none of them said what runs there now.
1024    #[test]
1025    fn a_correlation_the_current_scan_identified_nothing_to_test_is_not_resolved() {
1026        let before = correlated();
1027
1028        let mut labelled = port(PortState::Open);
1029        labelled.set_service(Service::new("http", 0));
1030        let mut unversioned = port(PortState::Open);
1031        unversioned.set_service(Service::new("http", 90).with_product("Apache httpd"));
1032
1033        for (case, after) in [
1034            ("no service at all", port(PortState::Open)),
1035            ("a port-number label", labelled),
1036            ("the same software without a version", unversioned),
1037        ] {
1038            let changes = changes_between(Some(&before), Some(&after), &clocks());
1039            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
1040            assert!(
1041                resolved.is_empty(),
1042                "{case}: reported {:?} resolved",
1043                titles(resolved)
1044            );
1045            assert_eq!(
1046                titles(unsettled),
1047                ["Apache httpd 2.4.49: path traversal"],
1048                "{case}"
1049            );
1050        }
1051    }
1052
1053    /// The counterpart: a newer identification without the identifier the claim
1054    /// was drawn from settles it, as an upgrade.
1055    #[test]
1056    fn a_correlation_a_newer_identification_no_longer_backs_is_resolved() {
1057        let before = correlated();
1058        let mut upgraded = port(PortState::Open);
1059        upgraded.set_service(
1060            Service::new("http", 90)
1061                .with_product("Apache httpd")
1062                .with_version("2.4.58")
1063                .with_cpe("cpe:/a:apache:http_server:2.4.58"),
1064        );
1065        let mut replaced = port(PortState::Open);
1066        replaced.set_service(Service::new("http", 90).with_product("nginx"));
1067
1068        for (case, after) in [("upgraded", upgraded), ("replaced", replaced)] {
1069            let changes = changes_between(Some(&before), Some(&after), &clocks());
1070            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
1071            assert!(unsettled.is_empty(), "{case}: {:?}", titles(unsettled));
1072            assert_eq!(
1073                titles(resolved),
1074                ["Apache httpd 2.4.49: path traversal"],
1075                "{case}"
1076            );
1077        }
1078    }
1079
1080    /// One side missing is an endpoint that appeared or went away, which the
1081    /// delta's presence already says, so no field changes are listed.
1082    #[test]
1083    fn an_endpoint_present_on_one_side_only_reports_no_field_changes() {
1084        let only = port(PortState::Open);
1085        assert!(changes_between(Some(&only), None, &clocks()).is_empty());
1086        assert!(changes_between(None, Some(&only), &clocks()).is_empty());
1087    }
1088}