zond-engine 0.17.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # What changed about one endpoint
//!
//! A port pairs with a port by number and transport, which needs no policy: 443
//! over TCP is 443 over TCP in both scans. What is left is reporting what moved,
//! and this module holds the vocabulary for it: the state, what is listening, and
//! what it presents at the TLS handshake.
//!
//! ## Only the verdicts
//!
//! A port carries its verdict and the evidence behind it, and only the verdict
//! is compared. [`Discovery`](crate::model::port::Discovery) says which packet
//! settled the state, when it arrived, how long it took and who sent it; none
//! of that is the verdict, and a diff carrying it would report a change every
//! time a reply took a millisecond longer or a different router on the path
//! answered for a filtered port. The same
//! reasoning excludes a service's confidence score, which measures how sure the
//! fingerprinter is rather than what is running.

use std::collections::{BTreeMap, BTreeSet};
use std::time::Duration;
use std::time::SystemTime;

use crate::diff::change::{Change, Coverage, Presence};
use crate::diff::host::Reassessment;
use crate::model::finding::{Finding, Standing};
use crate::model::port::security::CertificateInfo;
use crate::model::port::{Port, PortState, Protocol, Security, Service};

/// One endpoint, as the two scans hold it.
///
/// The number and transport identify it in both. Everything else is what moved,
/// in [`changes`](Self::changes), with the whole record from each side kept
/// alongside so a consumer rendering the change has the context around it
/// without going back to the reports.
#[derive(Debug, Clone, PartialEq)]
pub struct PortDelta {
    number: u16,
    protocol: Protocol,
    presence: Presence,
    baseline: Option<Port>,
    current: Option<Port>,
    changes: Vec<PortChange>,
}

impl PortDelta {
    /// The port number, which is the same in both scans.
    pub fn number(&self) -> u16 {
        self.number
    }

    /// The transport, which is the same in both scans.
    pub fn protocol(&self) -> Protocol {
        self.protocol
    }

    /// Which scans hold a record for this endpoint, and what the other one says
    /// about having looked.
    pub fn presence(&self) -> Presence {
        self.presence
    }

    /// The baseline scan's record, if it has one.
    ///
    /// [`None`] where the baseline's own record is [`PortState::Unasked`], since
    /// a port nobody probed is a scan holding no finding for that endpoint. The
    /// module documentation of [`diff`](crate::diff) is the argument for that
    /// reading.
    pub fn baseline(&self) -> Option<&Port> {
        self.baseline.as_ref()
    }

    /// The current scan's record, if it has one, read the same way.
    pub fn current(&self) -> Option<&Port> {
        self.current.as_ref()
    }

    /// Everything that moved, in a fixed order: state, then service, then
    /// transport security.
    pub fn changes(&self) -> &[PortChange] {
        &self.changes
    }

    /// Whether anything is reported for this endpoint at all.
    ///
    /// False only for an endpoint both scans hold identically, which the
    /// comparison does not emit.
    pub fn is_empty(&self) -> bool {
        self.presence.is_in_both() && self.changes.is_empty()
    }

    /// Whether this endpoint accepts connections now and did not before.
    ///
    /// Reads the records. An endpoint the baseline has no record for counts,
    /// since a report is the whole of what a scan wrote down, and so does one the
    /// baseline recorded [`Unasked`](PortState::Unasked), which is a scan saying
    /// outright that it holds none. Whether the baseline looked at all is
    /// [`presence`](Self::presence)'s question, and [`Presence::is_confirmed`] is
    /// the test that separates a port that opened from one nobody had checked.
    pub fn is_opened(&self) -> bool {
        self.state_of(self.current.as_ref()) == Some(PortState::Open)
            && self.state_of(self.baseline.as_ref()) != Some(PortState::Open)
    }

    /// Whether this endpoint accepted connections before and does not now.
    ///
    /// The mirror of [`is_opened`](Self::is_opened), with the same reading.
    pub fn is_closed(&self) -> bool {
        self.state_of(self.baseline.as_ref()) == Some(PortState::Open)
            && self.state_of(self.current.as_ref()) != Some(PortState::Open)
    }

    fn state_of(&self, port: Option<&Port>) -> Option<PortState> {
        port.map(Port::state)
    }
}

/// Something that moved about one endpoint.
///
/// `#[non_exhaustive]`, since a scan learns to establish more about a port as it
/// learns to speak more protocols, and a consumer matching on this should pay
/// for that with a recompile rather than with a major version.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum PortChange {
    /// The verdict moved. What each state means is
    /// [`PortState`]'s own documentation, and the two are not ordered by how
    /// alarming they are: `Filtered` to `Closed` is a firewall that stopped
    /// dropping probes, not a port that shut.
    State(Change<PortState>),
    /// What is listening changed, or was identified where it was not.
    Service(ServiceChange),
    /// What the endpoint presents at the TLS handshake changed.
    Security(SecurityChange),
    /// Findings that appeared on the port, and findings no longer claimed about
    /// it. Paired the way [`HostChange::Findings`](super::host::HostChange::Findings)
    /// pairs its own.
    ///
    /// A claim the current scan does not make is resolved only where that
    /// scan settled what the claim rests on. One drawn from what the endpoint
    /// accepts rests on the versions whose walk drew it, and where the current
    /// scan cut one of those walks short, or made none, its silence is the
    /// finding's [`Coverage::Unreached`]: the claim goes under `unsettled`
    /// rather than `resolved`, for the reason an endpoint the scan never
    /// reached is not a port that closed. One drawn from the certificate's
    /// posture rests on that certificate, and a current scan that recorded
    /// none was not shown whether it is still presented, so the claim goes
    /// under `unsettled` beside the
    /// [`Withdrawn`](CertificateChange::Withdrawn) that reports the absence.
    /// A vulnerability correlation rests on the identification it was drawn
    /// from, and a current scan that identified nothing there, or named the
    /// software without a version, did not say what runs there now, so that
    /// claim goes under `unsettled` too.
    Findings {
        /// Findings the current scan claims and the baseline did not.
        appeared: Vec<Finding>,
        /// Findings the baseline claimed and the current scan does not, other
        /// than those under `unsettled`.
        resolved: Vec<Finding>,
        /// Findings the baseline claimed that the current scan neither claims
        /// nor settled: part of the evidence each rests on is a walk the
        /// current scan left unfinished or never made, a certificate it
        /// recorded none of, or an identification it did not make.
        unsettled: Vec<Finding>,
        /// Findings both scans claim, where the severity moved.
        reassessed: Vec<Reassessment>,
    },
}

/// Something that moved about what is listening on an endpoint.
///
/// [`Version`](Self::Version) is the one most monitoring is looking for: a
/// service that moved from 1.18.0 to 1.24.0 is a patch that landed, and one that
/// moved the other way is a rollback worth asking about.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum ServiceChange {
    /// Nothing was identified here before, and something is now.
    Identified(Service),
    /// Something was identified here before and nothing is now. Not the same as
    /// the service being gone: the endpoint may not have been asked, which
    /// the phase's
    /// [`service_detection`](crate::report::ScanSettings::service_detection)
    /// setting records.
    Unidentified(Service),
    /// The service is called something else.
    Name(Change<String>),
    /// The product behind it changed.
    Product(Change<Option<String>>),
    /// The vendor changed.
    Vendor(Change<Option<String>>),
    /// The version changed.
    Version(Change<Option<String>>),
    /// The trailing detail the fingerprint carried changed.
    ExtraInfo(Change<Option<String>>),
    /// The platform identifiers changed, each list ascending.
    Cpes {
        /// Identifiers the current scan has and the baseline did not.
        gained: Vec<String>,
        /// Identifiers the baseline had and the current scan does not.
        lost: Vec<String>,
    },
}

/// Something that moved about an endpoint's transport security.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum SecurityChange {
    /// The negotiated protocol version changed.
    TlsVersion(Change<Option<String>>),
    /// The negotiated cipher suite changed.
    CipherSuite(Change<Option<String>>),
    /// The application protocols offered changed, each list ascending.
    Alpn {
        /// Protocols the current scan saw offered and the baseline did not.
        gained: Vec<String>,
        /// Protocols the baseline saw offered and the current scan does not.
        lost: Vec<String>,
    },
    /// The certificate changed, or its standing did.
    Certificate(CertificateChange),
}

/// Something that moved about the certificate an endpoint presents.
///
/// Identity is the SHA-256 fingerprint, so two certificates are the same one when
/// they are byte for byte the same. That is why there are no field-level variants
/// here: a certificate whose issuer or validity differs is a different
/// certificate, and [`Rotated`](Self::Rotated) is what that is.
///
/// [`Expiring`](Self::Expiring) and [`Expired`](Self::Expired) are the two
/// changes an unchanged certificate can undergo. Nothing about it moved; the
/// clock did, and a threshold was crossed between the two scans. See the module
/// documentation of [`diff`](crate::diff) for which clock is used.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq)]
pub enum CertificateChange {
    /// A certificate is presented where none was before.
    Presented(CertificateInfo),
    /// No certificate is presented where one was before.
    Withdrawn(CertificateInfo),
    /// A different certificate is presented.
    Rotated {
        /// What the baseline scan was shown.
        before: Box<CertificateInfo>,
        /// What the current scan was shown.
        after: Box<CertificateInfo>,
    },
    /// The certificate is still valid and now falls inside the expiry threshold,
    /// where at the baseline's clock it did not.
    Expiring {
        /// The certificate now inside the threshold.
        certificate: Box<CertificateInfo>,
        /// How long it has left, at the current scan's clock.
        remaining: Duration,
    },
    /// The certificate is past its validity end, where at the baseline's clock
    /// it was not.
    Expired {
        /// The certificate that lapsed.
        certificate: Box<CertificateInfo>,
        /// How long ago it lapsed, at the current scan's clock.
        since: Duration,
    },
}

/// Where a certificate stands at one moment.
///
/// The five states are exhaustive and unordered. A comparison reads them as
/// labels and reports a transition into [`Expiring`](Self::Expiring) or
/// [`Expired`](Self::Expired) because those are the two a person has to act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Validity {
    /// Nothing was presented, or what is presented now was not what the
    /// baseline was shown, so there is no earlier standing for this certificate
    /// to have moved from.
    Absent,
    NotYetValid,
    Valid,
    Expiring,
    Expired,
}

/// When the two clocks are used and what they are is documented on
/// [`DiffOptions`](crate::diff::DiffOptions).
pub(crate) struct Clocks {
    pub(crate) baseline: SystemTime,
    pub(crate) current: SystemTime,
    pub(crate) expiry_threshold: Duration,
}

/// Compares the endpoints of two hosts, ascending by number and then transport.
///
/// Endpoints that are identical in both scans are left out entirely, so the
/// result is what moved and nothing else.
///
/// ## An unasked port is not a record
///
/// A port a scan named and never probed is on its host at
/// [`PortState::Unasked`], and it is indexed here as a side holding no record at
/// all for that endpoint rather than as one whose state happens to be that.
/// It answers [`Coverage::Unreached`] instead, which is the same machinery that
/// already keeps a narrowed scope from reading as a network that emptied. The
/// module documentation of [`diff`](crate::diff) is the whole argument.
pub(crate) fn compare<'a>(
    baseline: &[&'a Port],
    current: &[&'a Port],
    presence: PresenceFor<'_>,
    clocks: &Clocks,
) -> Vec<PortDelta> {
    // Indexed rather than searched. Every settled port is on the record, so a
    // host from a full-port scan carries tens of thousands of them, and a linear
    // find per endpoint made a comparison quadratic in the one number that grows
    // fastest. The maps also give the ascending order the result promises.
    let index = |ports: &[&'a Port]| -> BTreeMap<(u16, Protocol), &'a Port> {
        ports
            .iter()
            .filter(|port| port.state() != PortState::Unasked)
            .map(|port| ((port.number(), port.protocol()), *port))
            .collect()
    };
    let unreached = |ports: &[&'a Port]| -> BTreeSet<(u16, Protocol)> {
        ports
            .iter()
            .filter(|port| port.state() == PortState::Unasked)
            .map(|port| (port.number(), port.protocol()))
            .collect()
    };

    let baseline_unreached = unreached(baseline);
    let current_unreached = unreached(current);
    let baseline = index(baseline);
    let current = index(current);

    let keys: BTreeSet<(u16, Protocol)> = baseline.keys().chain(current.keys()).copied().collect();

    let mut deltas = Vec::new();
    for (number, protocol) in keys {
        let before = baseline.get(&(number, protocol)).copied();
        let after = current.get(&(number, protocol)).copied();

        let (presence, changes) = match (before, after) {
            (Some(_), Some(_)) => (Presence::Both, changes_between(before, after, clocks)),
            (Some(_), None) => (
                presence.removed(number, protocol, &current_unreached),
                Vec::new(),
            ),
            (None, Some(_)) => (
                presence.added(number, protocol, &baseline_unreached),
                Vec::new(),
            ),
            (None, None) => unreachable!("a key comes from one side or the other"),
        };

        if presence.is_in_both() && changes.is_empty() {
            continue;
        }

        deltas.push(PortDelta {
            number,
            protocol,
            presence,
            baseline: before.cloned(),
            current: after.cloned(),
            changes,
        });
    }

    deltas
}

/// What each report says about having probed a given endpoint.
///
/// Asked per endpoint rather than once per host, because a scope names the ports
/// it walked and the answer differs between 443 and 8080 on the same address.
pub(crate) struct PresenceFor<'a> {
    pub(crate) baseline: &'a dyn Fn(u16, Protocol) -> Coverage,
    pub(crate) current: &'a dyn Fn(u16, Protocol) -> Coverage,
}

impl PresenceFor<'_> {
    fn added(
        &self,
        number: u16,
        protocol: Protocol,
        unreached: &BTreeSet<(u16, Protocol)>,
    ) -> Presence {
        Presence::Added {
            before: Self::coverage(self.baseline, number, protocol, unreached),
        }
    }

    fn removed(
        &self,
        number: u16,
        protocol: Protocol,
        unreached: &BTreeSet<(u16, Protocol)>,
    ) -> Presence {
        Presence::Removed {
            after: Self::coverage(self.current, number, protocol, unreached),
        }
    }

    /// What one side says about having probed an endpoint it holds no record
    /// for.
    ///
    /// Its own record answers first where it has one. A scope is what a scan set
    /// out to walk and [`PortState::Unasked`] is how far it got, so a port the
    /// scan wrote down as never probed is not covered however wide the scope it
    /// declared was.
    fn coverage(
        scope: &dyn Fn(u16, Protocol) -> Coverage,
        number: u16,
        protocol: Protocol,
        unreached: &BTreeSet<(u16, Protocol)>,
    ) -> Coverage {
        if unreached.contains(&(number, protocol)) {
            Coverage::Unreached
        } else {
            scope(number, protocol)
        }
    }
}

/// Everything that moved between two records of the same endpoint.
fn changes_between(
    before: Option<&Port>,
    after: Option<&Port>,
    clocks: &Clocks,
) -> Vec<PortChange> {
    let (Some(before), Some(after)) = (before, after) else {
        return Vec::new();
    };

    let mut changes = Vec::new();

    if let Some(state) = Change::between(before.state(), after.state()) {
        changes.push(PortChange::State(state));
    }

    changes.extend(
        service_changes(before.service(), after.service())
            .into_iter()
            .map(PortChange::Service),
    );

    changes.extend(
        security_changes(before.security(), after.security(), clocks)
            .into_iter()
            .map(PortChange::Security),
    );

    let (appeared, gone, reassessed) =
        super::host::findings_between(before.findings(), after.findings());

    // What the baseline's claim rests on is in the baseline's own record, and
    // whether the current scan settled it is in the current one's.
    let (unsettled, resolved): (Vec<Finding>, Vec<Finding>) = gone
        .into_iter()
        .partition(|finding| standing(finding, before, after) == Some(Standing::Unsettled));

    if !appeared.is_empty()
        || !resolved.is_empty()
        || !unsettled.is_empty()
        || !reassessed.is_empty()
    {
        changes.push(PortChange::Findings {
            appeared,
            resolved,
            unsettled,
            reassessed,
        });
    }

    changes
}

/// Where the current account of an endpoint, `after`, leaves a claim the
/// baseline's account, `before`, carried, or `None` where the claim is not
/// one drawn from evidence either record holds.
///
/// A claim drawn from the TLS handshake asks the current record's security,
/// and a scan that made no enumeration at all holds no record to ask, which is
/// the same answer as one holding an empty one; see [`Security::standing`].
///
/// A vulnerability correlation rests on the identification it was drawn from,
/// and asks [`correlation_standing`].
fn standing(finding: &Finding, before: &Port, after: &Port) -> Option<Standing> {
    if finding.is_correlation() {
        return correlation_standing(finding, before.service()?, after.service());
    }
    let silent = Security::new();
    let now = after.security().unwrap_or(&silent);
    now.standing(finding, before.security()?)
}

/// Where the service `now` identified leaves a correlation `basis`'s
/// identification drew, or `None` where `basis` carries none of the
/// identifiers the claim names and so is not what the claim rests on.
///
/// Upheld where `now` carries one of them, and overturned where it says
/// something else runs there: another service, another product, or another
/// version of the same one. That is a newer identification that no longer
/// backs the claim, and its absence is the upgrade or the replacement the
/// comparison was run to see.
///
/// Unsettled where `now` said nothing that tells: no service, a label read off
/// the port number, or the same software named without a version. A scan run
/// without service detection, or one whose probe matched a product and not
/// its release, did not say what runs there now, and reporting the claim
/// resolved on its word would announce a vulnerability fixed by a scan that
/// never looked. The same reading a merge makes, which keeps an older
/// identification's identifiers beside a newer one that states no version.
fn correlation_standing(
    finding: &Finding,
    basis: &Service,
    now: Option<&Service>,
) -> Option<Standing> {
    let backs = |service: &Service| finding.cpes().any(|cpe| service.cpes().contains(cpe));
    if !backs(basis) {
        return None;
    }
    let Some(now) = now.filter(|service| !service.is_inferred()) else {
        return Some(Standing::Unsettled);
    };
    if backs(now) {
        return Some(Standing::Upheld);
    }

    let differs = |stated: Option<&str>, then: Option<&str>| {
        stated.is_some_and(|stated| then.is_none_or(|then| stated != then))
    };
    let contradicts = now.name() != basis.name()
        || differs(now.product(), basis.product())
        || differs(now.version(), basis.version());
    Some(if contradicts {
        Standing::Overturned
    } else {
        Standing::Unsettled
    })
}

/// What moved about the service on an endpoint.
///
/// A service the scan *inferred* from the port number is not one it found, and
/// is read here as no service at all. Every scan path seeds one on every
/// classified port, and so does nmap; comparing them would have two tools with
/// different port catalogues disagree about every port on the network, and two
/// releases of one tool disagree whenever the catalogue grew.
fn service_changes(before: Option<&Service>, after: Option<&Service>) -> Vec<ServiceChange> {
    let before = before.filter(|service| !service.is_inferred());
    let after = after.filter(|service| !service.is_inferred());

    match (before, after) {
        (None, None) => Vec::new(),
        (None, Some(after)) => vec![ServiceChange::Identified(after.clone())],
        (Some(before), None) => vec![ServiceChange::Unidentified(before.clone())],
        (Some(before), Some(after)) => {
            let mut changes = Vec::new();

            if let Some(name) = Change::between(before.name().to_owned(), after.name().to_owned()) {
                changes.push(ServiceChange::Name(name));
            }
            if let Some(product) = optional(before.product(), after.product()) {
                changes.push(ServiceChange::Product(product));
            }
            if let Some(vendor) = optional(before.vendor(), after.vendor()) {
                changes.push(ServiceChange::Vendor(vendor));
            }
            if let Some(version) = optional(before.version(), after.version()) {
                changes.push(ServiceChange::Version(version));
            }
            if let Some(extra) = optional(before.extrainfo(), after.extrainfo()) {
                changes.push(ServiceChange::ExtraInfo(extra));
            }

            let (gained, lost) = set_change(
                before.cpes().iter().map(|cpe| cpe.to_string()),
                after.cpes().iter().map(|cpe| cpe.to_string()),
            );
            if !gained.is_empty() || !lost.is_empty() {
                changes.push(ServiceChange::Cpes { gained, lost });
            }

            changes
        }
    }
}

/// What moved about the transport security on an endpoint.
fn security_changes(
    before: Option<&Security>,
    after: Option<&Security>,
    clocks: &Clocks,
) -> Vec<SecurityChange> {
    let mut changes = Vec::new();

    let before_version = before.and_then(Security::tls_version);
    let after_version = after.and_then(Security::tls_version);
    if let Some(version) = optional(before_version, after_version) {
        changes.push(SecurityChange::TlsVersion(version));
    }

    let before_cipher = before.and_then(Security::cipher_suite);
    let after_cipher = after.and_then(Security::cipher_suite);
    if let Some(cipher) = optional(before_cipher, after_cipher) {
        changes.push(SecurityChange::CipherSuite(cipher));
    }

    let (gained, lost) = set_change(
        before
            .map(Security::alpn)
            .unwrap_or_default()
            .iter()
            .map(|p| p.to_string()),
        after
            .map(Security::alpn)
            .unwrap_or_default()
            .iter()
            .map(|p| p.to_string()),
    );
    if !gained.is_empty() || !lost.is_empty() {
        changes.push(SecurityChange::Alpn { gained, lost });
    }

    changes.extend(
        certificate_changes(before, after, clocks)
            .into_iter()
            .map(SecurityChange::Certificate),
    );

    changes
}

/// What moved about the certificate, including the two changes that happen to a
/// certificate nobody touched.
fn certificate_changes(
    before: Option<&Security>,
    after: Option<&Security>,
    clocks: &Clocks,
) -> Vec<CertificateChange> {
    let before_cert = before.and_then(Security::certificate);
    let after_cert = after.and_then(Security::certificate);

    let mut changes = Vec::new();

    match (before_cert, after_cert) {
        (None, None) => return changes,
        (None, Some(after)) => changes.push(CertificateChange::Presented(after.clone())),
        (Some(before), None) => {
            changes.push(CertificateChange::Withdrawn(before.clone()));
            return changes;
        }
        (Some(before), Some(after)) => {
            if before.fingerprint_sha256() != after.fingerprint_sha256() {
                changes.push(CertificateChange::Rotated {
                    before: Box::new(before.clone()),
                    after: Box::new(after.clone()),
                });
            }
        }
    }

    // **The standing of one certificate at two moments, not of two certificates.**
    //
    // A certificate nobody touched still crosses a threshold when enough time
    // passes between the two scans, and that is the change a renewal queue is
    // built from. Read as the standing of whatever each side happened to
    // present, a rotation onto a certificate that is *also* expiring cancelled
    // the alert: both sides answered `Expiring`, nothing had "changed", and an
    // endpoint that needs renewing today reported a rotation and nothing else.
    //
    // So the question is what the certificate presented *now* stood at when the
    // baseline ran, and a certificate the baseline was not shown stood at
    // nothing. Where both sides present the same one this is exactly the reading
    // above; where they do not, the standing has no incumbent to be measured
    // against and the current one is reported on its own terms.
    let same_certificate = matches!(
        (before_cert, after_cert),
        (Some(before), Some(after))
            if before.fingerprint_sha256() == after.fingerprint_sha256()
    );
    let was = if same_certificate {
        validity(after, clocks.expiry_threshold, clocks.baseline)
    } else {
        Validity::Absent
    };
    let is = validity(after, clocks.expiry_threshold, clocks.current);

    if let Some(certificate) = after_cert {
        match is {
            Validity::Expiring if was != Validity::Expiring => {
                let remaining = certificate
                    .validity_end()
                    .duration_since(clocks.current)
                    .unwrap_or_default();
                changes.push(CertificateChange::Expiring {
                    certificate: Box::new(certificate.clone()),
                    remaining,
                });
            }
            Validity::Expired if was != Validity::Expired => {
                let since = clocks
                    .current
                    .duration_since(certificate.validity_end())
                    .unwrap_or_default();
                changes.push(CertificateChange::Expired {
                    certificate: Box::new(certificate.clone()),
                    since,
                });
            }
            _ => {}
        }
    }

    changes
}

/// Where a certificate stands at `at`.
fn validity(security: Option<&Security>, threshold: Duration, at: SystemTime) -> Validity {
    let Some(security) = security else {
        return Validity::Absent;
    };
    let Some(certificate) = security.certificate() else {
        return Validity::Absent;
    };

    // The two bounds are asked here and again inside `is_cert_expiring_at`,
    // which is the one place they belong: this reads them to tell `NotYetValid`
    // and `Expired` apart, and that reads them because it is public and answers
    // for itself. Restating either here would be the bound written down twice.
    if at < certificate.validity_start() {
        Validity::NotYetValid
    } else if at > certificate.validity_end() {
        Validity::Expired
    } else if security.is_cert_expiring_at(threshold, at) {
        Validity::Expiring
    } else {
        Validity::Valid
    }
}

/// A change between two optional strings, owned so the diff outlives the reports
/// it was taken from.
fn optional(before: Option<&str>, after: Option<&str>) -> Option<Change<Option<String>>> {
    Change::between(before.map(str::to_owned), after.map(str::to_owned))
}

/// What one set gained and lost against another, both ascending.
fn set_change(
    before: impl Iterator<Item = String>,
    after: impl Iterator<Item = String>,
) -> (Vec<String>, Vec<String>) {
    let before: std::collections::BTreeSet<String> = before.collect();
    let after: std::collections::BTreeSet<String> = after.collect();

    let gained = after.difference(&before).cloned().collect();
    let lost = before.difference(&after).cloned().collect();
    (gained, lost)
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::confidence::Confidence;
    use crate::model::finding::{DetectionClass, DetectionId, Severity, Version};
    use crate::model::tls::{
        CipherSuite, Interruption, TlsSupport, TlsVersion, UnfinishedVersion, VersionSupport,
    };

    fn clocks() -> Clocks {
        Clocks {
            baseline: SystemTime::UNIX_EPOCH,
            current: SystemTime::UNIX_EPOCH,
            expiry_threshold: Duration::from_secs(30 * 24 * 60 * 60),
        }
    }

    fn port(state: PortState) -> Port {
        Port::new(443, Protocol::Tcp, state)
    }

    fn finding(title: &str) -> Finding {
        Finding::new(
            DetectionId::new("audit", Version::new(1, 0, 0), "hash").expect("a detection id"),
            title,
            Severity::High,
            Confidence::Certain,
            DetectionClass::Passive,
        )
        .expect("a titled finding")
    }

    /// A findings change's four lists: appeared, resolved, unsettled and
    /// reassessed.
    type Moved<'a> = (
        &'a [Finding],
        &'a [Finding],
        &'a [Finding],
        &'a [Reassessment],
    );

    fn findings_change(changes: &[PortChange]) -> Option<Moved<'_>> {
        changes.iter().find_map(|change| match change {
            PortChange::Findings {
                appeared,
                resolved,
                unsettled,
                reassessed,
            } => Some((
                appeared.as_slice(),
                resolved.as_slice(),
                unsettled.as_slice(),
                reassessed.as_slice(),
            )),
            _ => None,
        })
    }

    #[test]
    fn an_endpoint_that_did_not_move_reports_nothing() {
        let before = port(PortState::Open);
        let after = port(PortState::Open);
        assert!(changes_between(Some(&before), Some(&after), &clocks()).is_empty());
    }

    #[test]
    fn a_state_change_is_reported() {
        let before = port(PortState::Open);
        let after = port(PortState::Closed);

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        assert!(changes.iter().any(|change| matches!(
            change,
            PortChange::State(state)
                if state.before == PortState::Open && state.after == PortState::Closed
        )));
    }

    /// A finding arriving on an endpoint is a change, the port half of the
    /// property `diff::host` holds for a whole host.
    #[test]
    fn a_finding_that_appeared_on_the_endpoint_is_reported() {
        let before = port(PortState::Open);
        let mut after = port(PortState::Open);
        after.add_finding(finding("Weak cipher"));

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        let (appeared, resolved, _, _) = findings_change(&changes).expect("a findings change");
        assert_eq!(appeared.len(), 1);
        assert_eq!(appeared[0].title(), "Weak cipher");
        assert!(resolved.is_empty());
    }

    #[test]
    fn a_finding_that_went_away_from_the_endpoint_is_reported_as_resolved() {
        let mut before = port(PortState::Open);
        before.add_finding(finding("Weak cipher"));
        let after = port(PortState::Open);

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        let (appeared, resolved, _, _) = findings_change(&changes).expect("a findings change");
        assert!(appeared.is_empty());
        assert_eq!(resolved.len(), 1);
    }

    /// An endpoint enumerated as `support` says, carrying the findings drawn
    /// from it, which is how a scan records one.
    fn enumerated(support: TlsSupport) -> Port {
        let findings = support.findings();
        let mut port = port(PortState::Open).with_security(Security::new().with_support(support));
        for finding in findings {
            port.add_finding(finding);
        }
        port
    }

    /// TLS 1.0 accepted under AES-128-CBC with RSA key exchange, walked to the
    /// end.
    fn ten_accepted() -> TlsSupport {
        TlsSupport::new().accepting(VersionSupport::new(
            TlsVersion::Tls10,
            vec![CipherSuite::from_code(0x002F).expect("a registered suite")],
            vec![],
        ))
    }

    fn titles(findings: &[Finding]) -> Vec<&str> {
        findings.iter().map(Finding::title).collect()
    }

    /// A walk the current scan did not finish settled nothing the baseline's
    /// claim rests on, so the claim's absence is not a fix.
    ///
    /// The false fix a comparison already refuses for a port the scan never
    /// reached: a scheduled scan whose budget ran out during the TLS 1.0 walk
    /// would otherwise tell whoever reads the comparison that the withdrawn
    /// version had been switched off.
    #[test]
    fn a_finding_a_cut_short_walk_did_not_get_back_to_is_not_resolved() {
        let before = enumerated(ten_accepted());
        let after = enumerated(TlsSupport::new().leaving_unfinished(UnfinishedVersion::new(
            TlsVersion::Tls10,
            Interruption::Stopped,
        )));
        assert!(
            titles(&before.findings().cloned().collect::<Vec<_>>())
                .contains(&"TLSv1.0 is still accepted"),
            "the baseline's walk draws the claim this is about"
        );

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
        assert!(
            resolved.is_empty(),
            "a walk that never finished reported {:?} resolved",
            titles(resolved)
        );
        assert_eq!(
            titles(unsettled),
            titles(&before.findings().cloned().collect::<Vec<_>>()),
            "every claim the baseline drew from TLS 1.0 is said to be unsettled"
        );
    }

    /// The counterpart: a walk that finished and found TLS 1.0 refused is the
    /// fix, and holding it back would hide the one change the comparison was
    /// run to see.
    #[test]
    fn a_finding_a_finished_walk_refuted_is_resolved() {
        let before = enumerated(ten_accepted());
        let after = enumerated(TlsSupport::new().accepting(VersionSupport::new(
            TlsVersion::Tls13,
            vec![CipherSuite::from_code(0x1301).expect("a registered suite")],
            vec![],
        )));

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
        assert!(unsettled.is_empty(), "{:?}", titles(unsettled));
        assert!(titles(resolved).contains(&"TLSv1.0 is still accepted"));
    }

    /// An endpoint that completed a handshake and was shown a self-signed
    /// certificate with `fingerprint`, carrying the posture findings the scan
    /// draws from it, which is how a scan records one.
    fn presenting(fingerprint: &str) -> Port {
        let certificate = CertificateInfo::new(
            "www.example.test",
            "www.example.test",
            SystemTime::UNIX_EPOCH,
            SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 24 * 60 * 60),
            fingerprint,
        )
        .with_public_key("RSA", 2048);
        let findings = certificate.findings(SystemTime::UNIX_EPOCH);
        let mut port = port(PortState::Open).with_security(
            Security::new()
                .with_tls_version("TLSv1.3")
                .with_certificate(certificate),
        );
        for finding in findings {
            port.add_finding(finding);
        }
        port
    }

    /// A handshake the current scan did not complete settled nothing about the
    /// certificate a posture claim rests on, so the claim's absence is not a
    /// fix.
    ///
    /// The certificate side of the cut-short walk above. The service pass
    /// records no security at all for an endpoint whose handshake failed, and
    /// no certificate for one whose leaf would not parse, so an endpoint that
    /// timed out this once would otherwise report its self-signed certificate
    /// replaced by nothing and the problem fixed.
    #[test]
    fn a_posture_finding_the_current_scan_saw_no_certificate_for_is_not_resolved() {
        let before = presenting("aaaa");
        let unparsed =
            port(PortState::Open).with_security(Security::new().with_tls_version("TLSv1.3"));
        assert_eq!(
            titles(&before.findings().cloned().collect::<Vec<_>>()),
            ["TLS certificate is self-signed"],
            "the baseline's certificate draws the claim this is about"
        );

        for after in [port(PortState::Open), unparsed] {
            let changes = changes_between(Some(&before), Some(&after), &clocks());
            assert!(
                changes.iter().any(|change| matches!(
                    change,
                    PortChange::Security(SecurityChange::Certificate(
                        CertificateChange::Withdrawn(_)
                    ))
                )),
                "the certificate's absence is still reported as such"
            );
            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
            assert!(
                resolved.is_empty(),
                "a scan shown no certificate reported {:?} resolved",
                titles(resolved)
            );
            assert_eq!(titles(unsettled), ["TLS certificate is self-signed"]);
        }
    }

    /// The counterpart: a scan shown a different certificate settled the
    /// claim, since the posture belonged to bytes the endpoint no longer
    /// presents.
    #[test]
    fn a_posture_finding_the_current_scan_was_shown_another_certificate_for_is_resolved() {
        let before = presenting("aaaa");
        let after = port(PortState::Open).with_security(
            Security::new()
                .with_tls_version("TLSv1.3")
                .with_certificate(
                    CertificateInfo::new(
                        "www.example.test",
                        "Example CA",
                        SystemTime::UNIX_EPOCH,
                        SystemTime::UNIX_EPOCH + Duration::from_secs(365 * 24 * 60 * 60),
                        "bbbb",
                    )
                    .with_public_key("RSA", 2048),
                ),
        );

        let changes = changes_between(Some(&before), Some(&after), &clocks());
        let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
        assert!(unsettled.is_empty(), "{:?}", titles(unsettled));
        assert_eq!(titles(resolved), ["TLS certificate is self-signed"]);
    }

    /// An endpoint identified as Apache httpd 2.4.49, carrying the CVE
    /// correlation drawn from its CPE, which is how a scan records one.
    fn correlated() -> Port {
        const CPE: &str = "cpe:/a:apache:http_server:2.4.49";
        let mut port = port(PortState::Open);
        port.set_service(
            Service::new("http", 90)
                .with_product("Apache httpd")
                .with_version("2.4.49")
                .with_cpe(CPE),
        );
        port.add_finding(
            finding("Apache httpd 2.4.49: path traversal")
                .with_reference(crate::model::finding::Reference::Cve(
                    "CVE-2021-41773".into(),
                ))
                .with_cpe(CPE),
        );
        port
    }

    /// **A correlation the current scan identified nothing to test is not
    /// resolved.** It rests on the identification it was drawn from, and a
    /// scan run without service detection, one that labelled the port by its
    /// number alone, or one that named the software without reading a version
    /// did not say what runs there now. Reported resolved, a quick port scan
    /// compared against last month's thorough one would announce every
    /// vulnerability on the network fixed.
    #[test]
    fn a_correlation_the_current_scan_identified_nothing_to_test_is_not_resolved() {
        let before = correlated();

        let mut labelled = port(PortState::Open);
        labelled.set_service(Service::new("http", 0));
        let mut unversioned = port(PortState::Open);
        unversioned.set_service(Service::new("http", 90).with_product("Apache httpd"));

        for (case, after) in [
            ("no service at all", port(PortState::Open)),
            ("a port-number label", labelled),
            ("the same software without a version", unversioned),
        ] {
            let changes = changes_between(Some(&before), Some(&after), &clocks());
            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
            assert!(
                resolved.is_empty(),
                "{case}: reported {:?} resolved",
                titles(resolved)
            );
            assert_eq!(
                titles(unsettled),
                ["Apache httpd 2.4.49: path traversal"],
                "{case}"
            );
        }
    }

    /// The counterpart: a newer identification that no longer carries the
    /// identifier the claim was drawn from settled it, and that is the upgrade
    /// the comparison was run to see.
    #[test]
    fn a_correlation_a_newer_identification_no_longer_backs_is_resolved() {
        let before = correlated();
        let mut upgraded = port(PortState::Open);
        upgraded.set_service(
            Service::new("http", 90)
                .with_product("Apache httpd")
                .with_version("2.4.58")
                .with_cpe("cpe:/a:apache:http_server:2.4.58"),
        );
        let mut replaced = port(PortState::Open);
        replaced.set_service(Service::new("http", 90).with_product("nginx"));

        for (case, after) in [("upgraded", upgraded), ("replaced", replaced)] {
            let changes = changes_between(Some(&before), Some(&after), &clocks());
            let (_, resolved, unsettled, _) = findings_change(&changes).expect("a findings change");
            assert!(unsettled.is_empty(), "{case}: {:?}", titles(unsettled));
            assert_eq!(
                titles(resolved),
                ["Apache httpd 2.4.49: path traversal"],
                "{case}"
            );
        }
    }

    /// One side missing is an endpoint that appeared or went away, which the
    /// presence of the delta already says. Comparing fields would restate it.
    #[test]
    fn an_endpoint_present_on_one_side_only_reports_no_field_changes() {
        let only = port(PortState::Open);
        assert!(changes_between(Some(&only), None, &clocks()).is_empty());
        assert!(changes_between(None, Some(&only), &clocks()).is_empty());
    }
}