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
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
// 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 a service said about the machine underneath it
//!
//! A stack's shape says which family a host belongs to. A banner frequently says
//! which build: `SSH-2.0-OpenSSH_9.6p1 Debian` names a distribution outright, and
//! `Server: Microsoft-IIS/10.0` names a family with something close to certainty.
//! This is where that half is read.
//!
//! ## What a banner can and cannot say
//!
//! It names the host, modestly. What it actually describes is the *software*, and
//! the software is not always the machine: a container reports the base image it
//! was built from rather than the kernel it runs on, a reverse proxy reports
//! itself, and an appliance reports the vendor's firmware. That is why this
//! source sits below a stack reading, which is the machine answering for itself,
//! and why the two agreeing is worth more than either.
//!
//! ## Where it is joined up
//!
//! A rule matches the text it was written against, and that is not always the
//! whole banner. The imported SSH rules match a version string as it arrives, so
//! they work directly off what the transport read. The imported HTTP rules match
//! a `Server` header value, `^Microsoft-IIS/4.0$` anchored at both ends, so a
//! full response never matches one and reaching them means handing over the
//! extracted header rather than the banner.
//!
//! Extraction is [`HttpHeadersAnalyzer`](crate::fingerprint::HttpHeadersAnalyzer)'s
//! job, and it runs the extracted value back through the signature set for
//! *operating-system* metadata as well as for service identification. So SSH
//! and the other line-oriented protocols reach this source directly, and the
//! largest single family of OS-bearing rules in the corpus, the web servers,
//! reaches it through that analyzer.
//!
//! ## It costs nothing, which is the point
//!
//! Over half the shipped signature corpus, 2442 of 4732 rules, already carries
//! `os.*` metadata, matched against text the service pipeline already collects
//! from ports it has already opened. No probe here is new. The work is entirely
//! in *not throwing the metadata away*: a
//! [`Signature`](super::super::matcher::Signature) keeping only a rule's
//! service, product, vendor and version would drop everything else on the
//! floor.
//!
//! ## Templates
//!
//! The imported rules do not hold literal values so much as instructions for
//! building them from what the pattern captured:
//!
//! ```text
//! os.product = "{capture:1}"
//! os.cpe23   = "cpe:/o:microsoft:windows_2000:{os.version}"
//! ```
//!
//! Two forms, and they resolve in order. `{capture:N}` takes the Nth capture
//! group, and is why a match has to keep its groups at all. `{os.field}` takes a
//! sibling field of the same rule, so the capture form has to be resolved first.
//! 205 rules in the corpus build a platform identifier out of a version that was
//! itself captured.
//!
//! A template naming something absent resolves to **nothing at all**, and the
//! field is dropped rather than emitted half-built. A platform identifier reading
//! `cpe:/o:microsoft:windows_2000:` is worse than no identifier: it is a string a
//! consumer will try to match on.

use std::collections::HashMap;

use crate::model::host::OsEvidence;
use crate::model::host::OsSource;

/// What a matched service rule said about the operating system underneath it.
///
/// A struct of the fields worth keeping rather than the rule's whole metadata
/// map. The corpus carries a dozen `os.*` keys and this holds the ones that name
/// the machine or qualify that naming. What is left out is the packaging: an
/// edition and a build number, which distinguish two ways of selling one system
/// rather than two systems.
///
/// Stored behind a pointer on the signatures that have one, because 2290 of the
/// 4732 rules have none and a scan holds all of them at once.
/// Comparable but not [`Eq`]: [`certainty`](Self::certainty) is a float, and a
/// value nobody can write down exactly is not one two rules should be claimed to
/// share.
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq)]
pub struct OsMetadata {
    /// The vendor, such as `"Microsoft"`.
    pub vendor: Option<String>,
    /// The family, such as `"Windows"`.
    pub family: Option<String>,
    /// The product, such as `"Windows Server 2003"`.
    pub product: Option<String>,
    /// The version or service pack.
    pub version: Option<String>,
    /// The kernel release, where a rule reads one.
    ///
    /// Not a finer [`version`](Self::version), and not a competitor to it. A
    /// distribution release and the kernel it ships are two facts about one
    /// machine: Debian 12 runs kernel 6.1, and neither number is a better answer
    /// than the other. Filing the kernel as a version would make an SSH banner
    /// naming `12` and an SNMP agent naming `6.1.0` look like a contradiction,
    /// and a host that told this engine both would be reported as neither.
    ///
    /// Read from the `os.kernel` key, which is this engine's own: the imported
    /// corpus has no notion of it and puts a kernel in `os.version` where it
    /// finds one.
    pub kernel: Option<String>,
    /// A Common Platform Enumeration identifier.
    pub cpe23: Option<String>,
    /// The instruction set the system runs on: `x86_64`, `mips`, `armv7l`.
    ///
    /// A fact about the machine rather than a finer
    /// [`version`](Self::version), and one an SNMP agent hands over for nothing:
    /// `sysDescr` on a Unix host is `uname -a`, which ends with the machine
    /// type. A hundred and seventy shipped rules that fire carry one, and
    /// without this field nothing reads it.
    pub arch: Option<String>,
    /// What kind of box the rule says this is: `Printer`, `Switch`, `Router`.
    ///
    /// Read from `os.device`, falling back to `hw.device`, which is the same
    /// class written under the hardware namespace by rules that describe a
    /// device rather than the software on it.
    ///
    /// Its presence changes how the rest of the rule reads. A rule stating a
    /// class is describing hardware, so its `product` is a model number and its
    /// `vendor` is a manufacturer; see [`evidence_from`].
    pub device: Option<String>,
    /// How sure the corpus itself says this rule is, `0.0..=1.0`.
    ///
    /// The imported rules carry their own hedging on 353 entries, and honouring
    /// it is free: a corpus that marks a rule uncertain has told us something we
    /// would otherwise have to guess.
    pub certainty: Option<f32>,
}

impl OsMetadata {
    /// Reads the `os.*` keys out of a rule's metadata map, or `None` if it names
    /// no operating system at all.
    ///
    /// Called once per rule when the database is built, never per match.
    pub fn from_map(metadata: &HashMap<String, String>) -> Option<Self> {
        let get = |key: &str| metadata.get(key).filter(|v| !v.is_empty()).cloned();

        let found = Self {
            vendor: get("os.vendor"),
            family: get("os.family"),
            product: get("os.product"),
            version: get("os.version"),
            kernel: get("os.kernel"),
            cpe23: get("os.cpe23"),
            arch: get("os.arch"),
            device: get("os.device").or_else(|| get("hw.device")),
            certainty: get("os.certainty").and_then(|v| v.parse().ok()),
        };

        // A rule naming neither a family nor a product cannot become an
        // operating-system *reading*, and `evidence_from` is what declines it.
        // It is kept here where it names an instruction set, because that is a
        // fact about the host collected rather than voted on: seven rules state
        // one and nothing else, and dropping them at this layer put their answer
        // out of reach of every layer above.
        (found.family.is_some() || found.product.is_some() || found.arch.is_some()).then_some(found)
    }

    /// Resolves this rule's templates against what its pattern captured.
    ///
    /// `captures` is indexed as the pattern numbers its groups, index 0 being the
    /// whole match. A field whose template names a group that did not participate
    /// resolves to `None` and is dropped rather than emitted half-built. A
    /// platform identifier reading `cpe:/o:microsoft:windows_2000:` is worse than
    /// no identifier at all, because a consumer will try to match on it.
    pub fn resolve(&self, captures: &[String]) -> Self {
        // Capture templates first: the sibling form below reads the results.
        let vendor = fill(self.vendor.as_deref(), captures);
        let family = fill(self.family.as_deref(), captures);
        let product = fill(self.product.as_deref(), captures);
        let version = fill(self.version.as_deref(), captures);
        let kernel = fill(self.kernel.as_deref(), captures);
        let device = fill(self.device.as_deref(), captures);
        let arch = fill(self.arch.as_deref(), captures);

        let siblings = [
            ("os.vendor", vendor.as_deref()),
            ("os.family", family.as_deref()),
            ("os.product", product.as_deref()),
            ("os.version", version.as_deref()),
            ("os.kernel", kernel.as_deref()),
        ];
        let cpe23 = fill(self.cpe23.as_deref(), captures)
            .and_then(|template| fill_siblings(&template, &siblings));

        Self {
            vendor,
            family,
            product,
            version,
            kernel,
            cpe23,
            arch,
            device,
            certainty: self.certainty,
        }
    }
}

/// Substitutes `{capture:N}` for the Nth capture group.
///
/// `None` when the template names a group that did not participate, or resolves
/// to nothing at all, since an empty value is not a value.
pub(crate) fn fill(template: Option<&str>, captures: &[String]) -> Option<String> {
    let template = template?;
    if !template.contains("{capture:") {
        return Some(template.to_string());
    }

    let mut out = String::with_capacity(template.len());
    let mut rest = template;
    while let Some(start) = rest.find("{capture:") {
        out.push_str(&rest[..start]);
        let after = &rest[start + "{capture:".len()..];
        let end = after.find('}')?;
        let index: usize = after[..end].parse().ok()?;
        let value = captures.get(index).filter(|value| !value.is_empty())?;
        out.push_str(value);
        rest = &after[end + 1..];
    }
    out.push_str(rest);

    let out = out.trim().to_string();
    (!out.is_empty()).then_some(out)
}

/// Substitutes `{os.field}` for a sibling field already resolved.
fn fill_siblings(template: &str, siblings: &[(&str, Option<&str>)]) -> Option<String> {
    let mut out = template.to_string();
    for (name, value) in siblings {
        let token = format!("{{{name}}}");
        if out.contains(&token) {
            out = out.replace(&token, value.filter(|v| !v.is_empty())?);
        }
    }
    (!out.trim().is_empty()).then(|| out.trim().to_string())
}

/// The hardware a rule describes, where it describes any.
///
/// Read from the same metadata map [`OsMetadata::from_map`] reads, and kept
/// apart from it because the two answer different questions about one machine: a
/// NETGEAR ReadyNAS runs Linux, and neither half is the other. Five hundred and
/// thirty-six shipped rules that match name hardware and no operating system,
/// and without this every one of them produces nothing at all, because a
/// metadata map naming neither an OS family nor an OS product is dropped whole.
///
/// Templates resolve against what the pattern captured, exactly as the operating
/// system's do, so a rule reading a model out of its own match works here too.
pub fn hardware_from(
    metadata: &HashMap<String, String>,
    captures: &[String],
) -> Option<crate::model::host::HardwareInfo> {
    // The corpus hedging its own claim, honoured the way the operating system's
    // is. Forty-six rules state zero, which is the corpus saying in as many
    // words that this attribution is worth nothing, and emitting one anyway
    // would put a vendor on a host on the strength of a rule that disclaimed it.
    let certainty: f32 = metadata
        .get("hw.certainty")
        .and_then(|value| value.parse().ok())
        .unwrap_or(1.0);
    if certainty <= 0.0 {
        return None;
    }

    let get = |key: &str| {
        metadata
            .get(key)
            .filter(|value| !value.is_empty())
            .and_then(|value| fill(Some(value.as_str()), captures))
    };

    // Captures first, because the sibling form below reads their results:
    // `hw.product` is written `Thermal Label Printer {hw.model}` on the label
    // printers, and resolving it before the model would leave the brace in a
    // value a report prints.
    let vendor = get("hw.vendor");
    let model = get("hw.model");
    let family = get("hw.family");
    let version = get("hw.version");
    let serial = get("hw.serial_number");

    let siblings = [
        ("hw.vendor", vendor.as_deref()),
        ("hw.model", model.as_deref()),
        ("hw.family", family.as_deref()),
        ("hw.version", version.as_deref()),
    ];
    let resolve = |value: Option<String>| {
        value.and_then(|template| match template.contains('{') {
            true => fill_siblings(&template, &siblings),
            false => Some(template),
        })
    };

    let product = resolve(get("hw.product"));
    let cpe23 = resolve(get("hw.cpe23"));

    crate::model::host::HardwareInfo::described(crate::model::host::HardwareDescription {
        vendor: vendor.as_deref(),
        product: product.as_deref(),
        family: family.as_deref(),
        cpe23: cpe23.as_deref(),
        model: model.as_deref(),
        version: version.as_deref(),
        serial_number: serial.as_deref(),
    })
}

/// What a matched service rule contributes to identifying the host, read as
/// `source` attests it.
///
/// `None` when the rule resolved to nothing usable.
///
/// # The family, and when a product may stand in for one
///
/// Most imported rules name no `os.family`, and for the ones describing an
/// operating system the `os.product` is the family in all but name, as `Linux`
/// and `AIX` and `Windows Server 2008 R2` are, so it is read as one. 362 rules
/// depend on that.
///
/// A rule that names a [device class](OsMetadata::device) is the exception, and
/// it is not a small one. There the product is a model number and reading
/// it as a family puts `NC-8700w` on the ballot [`resolve`](super::resolve)
/// settles by vote, where it can only run against real families. Measured, on a
/// Brother print server: `NC-8700w` at 0.385 against `Network device` at 0.4
/// leaves 25%, under the floor, and a host that answered three separate probes
/// would be reported as unidentified. Those 389 rules state no family, keep
/// their model in `product` and their class in `device`, and abstain.
pub fn evidence_from(
    metadata: &OsMetadata,
    captures: &[String],
    source: OsSource,
) -> Option<OsEvidence> {
    let resolved = metadata.resolve(captures);
    let family = match (&resolved.family, &resolved.device) {
        (Some(family), _) => Some(family.clone()),
        (None, Some(_)) => None,
        (None, None) => Some(resolved.product.clone()?),
    };

    // The corpus's own hedging where it gave any. Absent means the rule
    // asserted its attribution without qualification, which is the ordinary
    // case, only 353 of the shipped rules carry the field at all, so the
    // default is full strength and a stated certainty is a *downgrade*, never
    // an upgrade.
    let certainty = resolved.certainty.unwrap_or(1.0).clamp(0.0, 1.0);

    // Forty-six rules state 0.0, which is the corpus saying in as many words that
    // this attribution is worth nothing. Emitting it at zero confidence would put
    // a family name into the resolver where it can only ever drag a real answer
    // down through the disagreement penalty. Declining is what the corpus asked
    // for.
    if certainty <= f32::EPSILON {
        return None;
    }

    let confidence = certainty * ceiling(source);

    let described = resolved
        .product
        .clone()
        .or_else(|| resolved.family.clone())
        .or_else(|| family.clone())
        .or_else(|| resolved.vendor.clone())
        .or_else(|| resolved.device.clone())?;

    let read = match source {
        OsSource::SnmpAgent => "snmp agent names",
        OsSource::MdnsResponder => "mdns responder names",
        _ => "service banner names",
    };

    Some(OsEvidence {
        source,
        family,
        device: resolved.device,
        vendor: resolved.vendor,
        product: resolved.product,
        version: resolved.version,
        kernel: resolved.kernel,
        arch: resolved.arch,
        cpe: resolved.cpe23,
        confidence,
        evidence: format!("{read} {described}"),
    })
}

/// Fills in what the corpus canonically knows about the operating system this
/// evidence names, where it names one that is recognised.
///
/// A rule that identified a service reports the operating system as the string
/// the service handed over. An SMB session setup says `Windows Server 2008 R2
/// Standard`, and the rule reading it states a vendor, a product and a CPE and
/// no *family*, because the string it matched had no family in it to state.
/// [`evidence_from`] then falls back to reading the product as the family, so
/// the host votes as its own edition, and two Windows machines running
/// different editions disagree about what they are.
///
/// The corpus already holds the answer: 59 rules that take an operating
/// system's name and say what it canonically is. This is the stage that
/// consults them, through
/// [`canonical_os_name`](crate::fingerprint::SignatureDb).
///
/// # It may only add
///
/// Every field the first match stated is kept. The canonical reading is
/// generally coarser about the product, naming a family where the service named
/// a release, so letting it overwrite would turn `Windows Server 2008 R2` into
/// `Windows`. The product stands, and so does everything else already present;
/// only the empty fields are filled.
///
/// The family is the one field that is replaced, and only where it is the
/// product repeated, which is what [`evidence_from`]'s own fallback leaves
/// behind. That is the point of the stage: a host whose family is its release
/// votes as its edition, and two Windows machines running different ones
/// disagree about what they are.
///
/// The confidence is the first match's own. A canonical name is a naming rather
/// than a second observation of the host, so it adds no weight and takes none
/// away.
pub fn canonicalise(evidence: OsEvidence, canonical: &OsEvidence) -> OsEvidence {
    /// Keeps what the first match said, and takes the canonical reading only
    /// where it said nothing.
    fn or(mine: Option<String>, theirs: &Option<String>) -> Option<String> {
        mine.or_else(|| theirs.clone())
    }

    // The family is the exception, because there is rarely an empty one to
    // fill: `evidence_from` reads the product as the family where a rule
    // states none, so by the time this runs the field usually holds the
    // release. A family equal to the product is that fallback showing, and the
    // canonical reading is the answer it was standing in for.
    //
    // A rule that genuinely states both as the same word, which the Linux and
    // AIX rules do, is unaffected: the canonical reading agrees with it.
    let family = match (&evidence.family, &evidence.product, &canonical.family) {
        (Some(family), Some(product), Some(canonical)) if family == product => {
            Some(canonical.clone())
        }
        _ => or(evidence.family, &canonical.family),
    };

    OsEvidence {
        family,
        vendor: or(evidence.vendor, &canonical.vendor),
        version: or(evidence.version, &canonical.version),
        kernel: or(evidence.kernel, &canonical.kernel),
        arch: or(evidence.arch, &canonical.arch),
        cpe: or(evidence.cpe, &canonical.cpe),
        device: evidence.device.or_else(|| canonical.device.clone()),
        ..evidence
    }
}

/// The most a rule matched against `source`'s text may be worth, before the
/// corpus's own certainty scales it.
///
/// One number per kind of text, because the kinds are not equally close to the
/// machine. See [`BANNER_CEILING`] and [`AGENT_CEILING`].
pub fn ceiling(source: OsSource) -> f32 {
    match source {
        // The machine answering for itself, as SNMP is, and worth the same.
        OsSource::SnmpAgent | OsSource::MdnsResponder => AGENT_CEILING,
        _ => BANNER_CEILING,
    }
}

/// The most a banner is worth, before the corpus's own certainty scales it.
///
/// Enough to name a host on its own, and not by much. `OpenSSH_9.6p1 Debian`
/// really does say Debian, a distribution's build of a daemon running on that
/// distribution, and pretending otherwise would discard the most direct statement
/// a machine ever makes about itself.
///
/// Held below what a stack reading is worth for a reason that is not hedging.
/// A banner describes the software, and the software is not always the host.
/// A container reports the base image it was built from rather than the kernel it
/// runs on; a reverse proxy reports the proxy and not what is behind it; an
/// appliance reports the vendor's firmware while the box underneath runs
/// something else. The stack, by contrast, is the machine answering for itself.
///
/// So one banner names a host at around 55, which reports but does not reach the
/// threshold that stops further probing; a banner agreeing with a stack reading
/// reaches the low eighties, which is the point of having both.
pub const BANNER_CEILING: f32 = 0.55;

/// The most a management agent's own description of its machine is worth.
///
/// Above [`BANNER_CEILING`] for the reason that ceiling exists: a banner is a
/// string a daemon carries from its build, and the gap between the build and the
/// running machine is what holds the number down. `sysDescr` has no such gap. On
/// a Unix host net-snmp renders it from `uname -a` when the question is asked, so
/// it is the kernel executing at the moment of asking, and on an appliance it is
/// the firmware build reporting itself. The agent is part of the machine, not
/// software running on it.
///
/// Below the 85 that
/// [`OsFingerprint::is_highly_confident`](crate::model::host::OsFingerprint::is_highly_confident)
/// reads, so one agent still does not settle a host on its own. Reaching that
/// takes a second independent source, which is the rule everywhere else here and
/// there is no case for exempting this one.
pub const AGENT_CEILING: f32 = 0.8;

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

#[cfg(test)]
mod tests {
    use super::*;

    fn metadata(pairs: &[(&str, &str)]) -> OsMetadata {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        OsMetadata::from_map(&map).expect("names an operating system")
    }

    fn hardware(
        pairs: &[(&str, &str)],
        captures: &[String],
    ) -> Option<crate::model::host::HardwareInfo> {
        let map: HashMap<String, String> = pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect();
        hardware_from(&map, captures)
    }

    /// A product written as a phrase around a sibling field, which is how the
    /// label printers and half the Cisco access points state theirs. Resolving
    /// the captures without then resolving the siblings put a literal brace in a
    /// value a report prints.
    #[test]
    fn a_product_written_around_a_sibling_field_is_completed_from_it() {
        let found = hardware(
            &[
                ("hw.vendor", "Cisco"),
                ("hw.model", "{capture:1}"),
                ("hw.product", "Aironet {hw.model}"),
            ],
            &["Aironet 1140".to_string(), "1140".to_string()],
        )
        .expect("it names something");

        assert_eq!(found.product(), Some("Aironet 1140"));
        assert_eq!(found.model(), Some("1140"));
    }

    /// Forty-six rules state `hw.certainty = 0.0`, which is the corpus saying in
    /// as many words that its own attribution is worth nothing. Emitting one
    /// anyway would put a vendor on a host on the strength of a rule that
    /// disclaimed it.
    #[test]
    fn a_rule_that_disclaims_its_own_attribution_produces_no_hardware() {
        assert!(hardware(&[("hw.certainty", "0.0"), ("hw.vendor", "Generic")], &[],).is_none());
    }

    /// The three fields a service states and an address block cannot reach.
    #[test]
    fn a_rule_that_names_a_unit_keeps_the_model_revision_and_serial() {
        let found = hardware(
            &[
                ("hw.vendor", "Xerox"),
                ("hw.product", "WorkCentre 4200"),
                ("hw.model", "4200"),
                ("hw.version", "2"),
                ("hw.serial_number", "{capture:1}"),
            ],
            &[
                "WorkCentre 4200 XRX9000123".to_string(),
                "XRX9000123".to_string(),
            ],
        )
        .expect("it names something");

        assert_eq!(found.model(), Some("4200"));
        assert_eq!(found.hardware_version(), Some("2"));
        assert_eq!(found.serial_number(), Some("XRX9000123"));
    }

    /// A rule taken verbatim from the imported corpus, with the capture groups
    /// its pattern would have produced. Templates in three fields at once, which
    /// is the ordinary shape rather than a corner case.
    #[test]
    fn a_real_rule_builds_its_values_from_what_the_pattern_captured() {
        let rule = metadata(&[
            ("os.vendor", "Microsoft"),
            ("os.family", "Windows"),
            ("os.product", "{capture:1}"),
            ("os.edition", "{capture:2}"),
            ("os.version", "{capture:3}"),
        ]);

        let resolved = rule.resolve(&[
            "Windows Server 2003 Standard SP2".to_string(),
            "Windows Server 2003".to_string(),
            "Standard".to_string(),
            "SP2".to_string(),
        ]);

        assert_eq!(resolved.vendor.as_deref(), Some("Microsoft"));
        assert_eq!(resolved.family.as_deref(), Some("Windows"));
        assert_eq!(resolved.product.as_deref(), Some("Windows Server 2003"));
        assert_eq!(resolved.version.as_deref(), Some("SP2"));
    }

    /// The second template form, and the reason resolution is ordered: 205 rules
    /// in the corpus build a platform identifier out of a version that was itself
    /// captured, so the capture form has to be filled before the sibling form
    /// reads it.
    #[test]
    fn a_platform_identifier_is_built_from_a_field_that_was_itself_captured() {
        let rule = metadata(&[
            ("os.family", "Windows"),
            ("os.product", "Windows 2000"),
            ("os.version", "{capture:2}"),
            ("os.cpe23", "cpe:/o:microsoft:windows_2000:{os.version}"),
        ]);

        let resolved = rule.resolve(&[
            "Windows 2000 Professional SP4".to_string(),
            "Professional".to_string(),
            "SP4".to_string(),
        ]);

        assert_eq!(
            resolved.cpe23.as_deref(),
            Some("cpe:/o:microsoft:windows_2000:SP4"),
            "the sibling template must see the resolved capture, not the template"
        );
    }

    /// A template naming a group that did not participate resolves to nothing and
    /// the field is dropped. Emitting the half-built value would put
    /// `cpe:/o:microsoft:windows_2000:` into a report, which is worse than an
    /// absent identifier because a consumer will try to match on it.
    #[test]
    fn a_template_over_an_absent_capture_drops_the_field_rather_than_half_building_it() {
        let rule = metadata(&[
            ("os.family", "Windows"),
            ("os.product", "Windows 2000"),
            ("os.version", "{capture:2}"),
            ("os.cpe23", "cpe:/o:microsoft:windows_2000:{os.version}"),
        ]);

        // An optional group that did not participate arrives as an empty string.
        let resolved = rule.resolve(&["Windows 2000".to_string(), String::new(), String::new()]);

        assert_eq!(resolved.version, None);
        assert_eq!(resolved.cpe23, None, "no dangling identifier");
        assert_eq!(
            resolved.product.as_deref(),
            Some("Windows 2000"),
            "and the fields that did resolve survive"
        );
    }

    /// A rule naming neither a family nor a product describes no operating
    /// system, and does not become one however it is carried.
    #[test]
    fn metadata_that_names_no_system_is_not_a_reading() {
        let map: HashMap<String, String> = [("os.certainty".to_string(), "1.0".to_string())]
            .into_iter()
            .collect();
        assert!(OsMetadata::from_map(&map).is_none());
    }

    /// An architecture alone is kept, and is still not a reading.
    ///
    /// The two halves are the whole arrangement. Seven rules state an
    /// instruction set and nothing else, and dropping them at `from_map` put
    /// their answer out of reach of every layer above, so the metadata survives.
    /// It cannot stand as an operating-system reading, though: evidence naming
    /// nothing describable would enter a resolver that settles by vote as a
    /// nameless candidate, so `evidence_from` declines it and the architecture is
    /// collected instead.
    #[test]
    fn an_architecture_alone_is_kept_but_is_not_a_reading() {
        let map: HashMap<String, String> = [("os.arch".to_string(), "mips".to_string())]
            .into_iter()
            .collect();

        let metadata = OsMetadata::from_map(&map).expect("the architecture survives");
        assert_eq!(metadata.arch.as_deref(), Some("mips"));

        assert!(
            evidence_from(&metadata, &[], OsSource::ServiceBanner).is_none(),
            "an architecture is a fact about the host, not a reading of its system"
        );
    }

    /// 362 rules name an operating system in `os.product` and no family at all,
    /// `Linux`, `AIX`, `FreeBSD`, and reading the product as the family is what
    /// makes them work.
    #[test]
    fn a_product_stands_in_for_a_family_nobody_stated() {
        let rule = metadata(&[("os.vendor", "Ubuntu"), ("os.product", "Linux")]);
        let found = evidence_from(&rule, &[], OsSource::ServiceBanner).expect("names a system");

        assert_eq!(found.family.as_deref(), Some("Linux"));
    }

    /// Except where a device class says the product is a model number. 389 rules
    /// are written that way, and reading `NC-8700w` as a family would set a
    /// printer's model against the class of box a hop counter had established.
    #[test]
    fn a_model_number_never_stands_in_for_a_family() {
        let rule = metadata(&[
            ("os.vendor", "Brother"),
            ("os.product", "NC-8700w"),
            ("os.device", "Printer"),
        ]);
        let found = evidence_from(&rule, &[], OsSource::SnmpAgent).expect("names a system");

        assert_eq!(found.family, None);
        assert_eq!(found.product.as_deref(), Some("NC-8700w"));
        assert_eq!(found.device.as_deref(), Some("Printer"));
    }

    /// The corpus writes the same class under two namespaces. Both are the same
    /// fact about the same box.
    #[test]
    fn a_class_written_under_the_hardware_namespace_is_the_same_class() {
        let rule = metadata(&[("os.product", "Linux"), ("hw.device", "IP Camera")]);
        assert_eq!(rule.device.as_deref(), Some("IP Camera"));
    }

    /// A class can be captured out of the text like anything else, and a
    /// template that resolves to nothing is dropped rather than emitted raw.
    #[test]
    fn a_captured_device_class_resolves_against_the_match() {
        let rule = metadata(&[("os.product", "VRP"), ("os.device", "{capture:2}")]);

        let captures = ["".to_string(), "".to_string(), "Switch".to_string()];
        assert_eq!(rule.resolve(&captures).device.as_deref(), Some("Switch"));
        assert_eq!(rule.resolve(&[]).device, None);
    }

    /// What an agent says is worth more than what a daemon was compiled with,
    /// and the gap is the whole reason the two are separate sources.
    #[test]
    fn an_agent_outweighs_a_banner_saying_the_same_thing() {
        let rule = metadata(&[("os.family", "Linux"), ("os.kernel", "6.1.0")]);

        let by_agent = evidence_from(&rule, &[], OsSource::SnmpAgent).expect("names a system");
        let by_banner = evidence_from(&rule, &[], OsSource::ServiceBanner).expect("names a system");

        assert!(
            by_agent.confidence > by_banner.confidence,
            "an agent rendering `uname -a` on demand is closer to the machine \
             than a string a daemon carried from its build"
        );
        assert!(
            by_agent.confidence < 0.85,
            "and still not enough to settle a host on its own"
        );
    }

    /// The corpus hedges on 353 of its own rules and honouring that is free.
    /// A rule marked uncertain must not be worth what a confident one is.
    #[test]
    fn the_corpus_own_hedging_lowers_what_a_rule_is_worth() {
        let confident = metadata(&[("os.family", "Linux"), ("os.product", "Ubuntu")]);
        let hedged = metadata(&[
            ("os.family", "Linux"),
            ("os.product", "Ubuntu"),
            ("os.certainty", "0.5"),
        ]);

        let confident =
            evidence_from(&confident, &[], OsSource::ServiceBanner).expect("names a system");
        let hedged = evidence_from(&hedged, &[], OsSource::ServiceBanner).expect("names a system");

        assert!(
            hedged.confidence < confident.confidence,
            "an unqualified rule is the ordinary case and must outrank a hedged one"
        );
    }

    /// Forty-six rules in the corpus state a certainty of zero, which is it
    /// saying the attribution is worth nothing. Emitting that as evidence would
    /// put a family name in front of the resolver where it can only drag a real
    /// answer down through the disagreement penalty.
    #[test]
    fn a_rule_the_corpus_calls_worthless_produces_no_evidence() {
        let worthless = metadata(&[
            ("os.family", "Linux"),
            ("os.product", "Ubuntu"),
            ("os.certainty", "0.0"),
        ]);
        assert!(evidence_from(&worthless, &[], OsSource::ServiceBanner).is_none());
    }

    /// A banner names a host on its own, `OpenSSH_9.6p1 Debian` really does say
    /// Debian, but modestly, and below the threshold that would stop a caller
    /// probing further. The software is not always the host: a container
    /// reports its base image rather than the kernel underneath it.
    #[test]
    fn a_banner_alone_names_a_host_but_does_not_settle_it() {
        let rule = metadata(&[("os.family", "Linux"), ("os.product", "Ubuntu")]);
        let evidence = evidence_from(&rule, &[], OsSource::ServiceBanner).expect("names a system");
        assert!(evidence.confidence <= BANNER_CEILING);

        let alone = super::super::resolve(vec![evidence]).expect("a banner names a host");
        assert!(alone.accuracy >= 40, "reported rather than discarded");
        assert!(
            !alone.to_fingerprint().is_highly_confident(),
            "and not enough on its own to stop looking"
        );
    }

    /// The reason for having two sources rather than a better single one. A
    /// banner and a stack reading are read from different places and fail in
    /// different ways, so agreement between them is worth more than either, and
    /// this is where a verdict legitimately passes what one packet could
    /// support.
    #[test]
    fn a_banner_agreeing_with_the_wire_is_worth_more_than_either() {
        use super::super::OsVerdict;
        use crate::model::host::OsSource;

        let banner = evidence_from(
            &metadata(&[("os.family", "Linux"), ("os.product", "Ubuntu")]),
            &[],
            OsSource::ServiceBanner,
        )
        .expect("names a system");

        let stack = OsVerdict {
            family: Some("Linux".to_string()),
            device: None,
            vendor: None,
            product: None,
            version: None,
            kernel: None,
            arch: None,
            cpe: None,
            accuracy: 65,
            detail_accuracy: None,
            source: OsSource::TcpStack,
            evidence: "syn-ack opts=M,S,T,N,W".to_string(),
        }
        .as_evidence();

        let together = super::super::resolve(vec![stack, banner]).expect("named");
        assert!(
            together.accuracy > 65,
            "two independent sources agreeing must beat the better one alone"
        );
        assert_eq!(together.family.as_deref(), Some("Linux"));
    }

    /// A device-info record is the machine answering for itself, as `sysDescr`
    /// is, so it is worth the same and not what a daemon was compiled with.
    #[test]
    fn a_responder_answering_for_the_machine_is_worth_what_an_agent_is() {
        assert_eq!(ceiling(OsSource::MdnsResponder), AGENT_CEILING);
        assert!(ceiling(OsSource::MdnsResponder) > ceiling(OsSource::ServiceBanner));
    }
}

#[cfg(test)]
mod against_the_shipped_corpus {
    use crate::fingerprint::SignatureDb;
    use crate::model::port::Protocol;

    /// A banner naming a release must yield that release.
    ///
    /// Both of these are strings read off a real host on 2026-08-21, exactly as
    /// they arrive on the wire. The first is the case that depends on matching
    /// the right text: the corpus holds a rule mapping it to Debian 12 with a
    /// CPE, and anchors its patterns on the SSH software identifier, so matching
    /// the whole identification line instead lets only a loose family rule fire,
    /// and the engine would report `Linux`.
    ///
    /// The second names no release yet, and that is the corpus being short
    /// rather than the matcher being broken: it holds no OpenSSH 10 rule. It is
    /// here so that adding one is visible as this assertion getting stronger.
    #[test]
    fn a_banner_that_names_a_release_yields_the_release() {
        let db = SignatureDb::global();

        let debian_12 = db
            .identify(22, Protocol::Tcp, "SSH-2.0-OpenSSH_9.2p1 Debian-2+deb12u10")
            .and_then(|found| found.os)
            .expect("a Debian OpenSSH banner names an operating system");

        assert_eq!(debian_12.family.as_deref(), Some("Linux"));
        assert_eq!(
            debian_12.version.as_deref(),
            Some("12"),
            "the release is the whole reason to read a banner: {debian_12:?}"
        );
        assert_eq!(
            debian_12.cpe.as_deref(),
            Some("cpe:/o:debian:debian_linux:12.0"),
            "the CPE keeps its registered form, which is a name in somebody \
             else's namespace rather than this engine's claim"
        );
        assert_eq!(debian_12.vendor.as_deref(), Some("Debian"));

        let debian_13 = db
            .identify(22, Protocol::Tcp, "SSH-2.0-OpenSSH_10.0p2 Debian-7+deb13u4")
            .and_then(|found| found.os)
            .expect("a Debian OpenSSH banner names an operating system");
        assert_eq!(debian_13.family.as_deref(), Some("Linux"));
        assert_eq!(
            debian_13.version.as_deref(),
            Some("13"),
            "read from the release Debian stamps into its own package version, so a \
             release the corpus has never seen still names itself: {debian_13:?}"
        );

        // A backport says which release it was built *for*, in the same place.
        let backported = db
            .identify(22, Protocol::Tcp, "SSH-2.0-OpenSSH_9.7p1 Debian-1~bpo12+1")
            .and_then(|found| found.os)
            .expect("a backport names one too");
        assert_eq!(backported.version.as_deref(), Some("12"));

        // And a banner with the suffix stripped, `DebianBanner no`, names no
        // release, because there is none in it to name. Declining is right:
        // guessing a release from an OpenSSH version would attribute Debian's
        // packaging to every distribution that ships the same upstream.
        let stripped = db
            .identify(22, Protocol::Tcp, "SSH-2.0-OpenSSH_10.0p2")
            .and_then(|found| found.os);
        assert!(
            stripped.is_none_or(|os| os.version.is_none()),
            "a stripped banner carries no release and must not invent one"
        );
    }

    /// A distribution with nothing in its banners to match.
    ///
    /// Arch ships OpenSSH unpatched and unmarked, so no banner rule can reach
    /// it, and Recog carries none. Its kernel release is the one place its own
    /// packaging signs its work, and there is no version, since a rolling release
    /// has none to give.
    ///
    /// Authored from the naming convention rather than from a host this engine
    /// has read, which is safe here for one specific reason: the failure mode is
    /// silence. `arch1` in a kernel release is a string only Arch produces, so a
    /// wrong guess about the shape means the rule never fires, and it cannot name
    /// somebody else's machine Arch.
    #[test]
    fn arch_is_named_by_its_kernel_because_nothing_else_names_it() {
        let db = SignatureDb::global();

        let found = db.identify(161, Protocol::Udp, "Linux host 6.12.1-arch1-1 #1 SMP PREEMPT_DYNAMIC Fri, 22 Nov 2024 12:00:00 +0000 x86_64",
        )
        .and_then(|found| found.os)
        .expect("an Arch kernel names Arch");

        assert_eq!(found.vendor.as_deref(), Some("Arch Linux"));
        assert_eq!(found.kernel.as_deref(), Some("6.12.1"));
        assert_eq!(
            found.version, None,
            "a rolling release has no version, and inventing one would be worse \
             than the silence it replaced"
        );

        // And the banner it actually presents on port 22 names nothing, which is
        // the honest answer rather than a gap to be papered over: a bare
        // `OpenSSH_10.0p2` is Arch, Fedora, Gentoo or a source build alike.
        let by_ssh = db
            .identify(22, Protocol::Tcp, "SSH-2.0-OpenSSH_10.0p2")
            .and_then(|found| found.os);
        assert!(
            by_ssh.is_none_or(|os| os.vendor.is_none()),
            "an unmarked upstream banner must not be attributed to any distribution"
        );
    }

    /// The instruction set a `uname`-derived `sysDescr` ends with.
    ///
    /// 255 shipped rules carry `os.arch`, and without the field every one of
    /// them drops it. It is a third axis beside what a machine runs and what
    /// it is: a FreeBSD release and `amd64` are two facts, and an exploit that
    /// needs a payload built for the target cares about the second.
    #[test]
    fn an_agent_that_states_its_machine_type_keeps_it() {
        let db = SignatureDb::global();

        let found = db
            .identify(
                161,
                Protocol::Udp,
                "FreeBSD freebsd-10-x64-ports-p 10.0-RELEASE-p4 FreeBSD 10.0-RELEASE-p4 #0: \
                 Tue Jun 3 13:14:57 UTC 2014 \
                 root@amd64-builder.daemonology.net:/usr/obj/usr/src/sys/GENERIC amd64",
            )
            .and_then(|found| found.os)
            .expect("a FreeBSD agent names FreeBSD");

        assert_eq!(found.family.as_deref(), Some("FreeBSD"));
        assert_eq!(found.version.as_deref(), Some("10.0-RELEASE-p4"));
        assert_eq!(found.arch.as_deref(), Some("amd64"));
    }

    /// A `sysDescr` that names hardware and no operating system.
    ///
    /// Read off a Brother NC-8700w print server on 2026-08-26, exactly as its
    /// agent answered. The rule for it carries a vendor, a model, a firmware and
    /// a device class, and no family, since the box never said what it runs.
    ///
    /// Every field here is on the wire, and none of it would reach a report
    /// with the model read as the *family*: put on the ballot against the
    /// `Network device` a hop counter of 255 has already established, the two
    /// annihilate. What this asserts is that the reading survives to be
    /// reported, with the model under `product` where it belongs and the class
    /// on its own axis.
    #[test]
    fn an_agent_that_names_only_hardware_names_hardware() {
        let db = SignatureDb::global();

        let found = db
            .identify(
                161,
                Protocol::Udp,
                "Brother NC-8700w, Firmware Ver.ZL  ,MID 8CE-823,FID 2",
            )
            .and_then(|found| found.os)
            .expect("a shipped rule reads this exact string");

        assert_eq!(found.vendor.as_deref(), Some("Brother"));
        assert_eq!(found.product.as_deref(), Some("NC-8700w"));
        assert_eq!(found.version.as_deref(), Some("ZL"));
        assert_eq!(found.device.as_deref(), Some("Printer"));
        assert_eq!(
            found.family, None,
            "a model number is not a family, and reading it as one is what put \
             `NC-8700w` on a ballot against `Network device`"
        );
    }

    /// The kernel an agent reads out is the point of asking, and it survives the
    /// whole path from datagram to evidence.
    #[test]
    fn an_agent_that_names_a_kernel_names_a_kernel() {
        let db = SignatureDb::global();

        let found = db
            .identify(
                161,
                Protocol::Udp,
                "Linux zond 6.1.0-18-arm64 #1 SMP Debian 6.1.76-1 (2024-02-01) aarch64",
            )
            .and_then(|found| found.os)
            .expect("the kernel rule reads this");

        assert_eq!(found.family.as_deref(), Some("Linux"));
        assert_eq!(found.kernel.as_deref(), Some("6.1.0"));
        assert_eq!(found.source, crate::model::host::OsSource::SnmpAgent);
    }

    /// Releases nobody has a machine for.
    ///
    /// The generic Debian rule reads the release out of the stamp its packaging
    /// writes, so a release this engine has never been pointed at names itself
    /// from a string alone. That is what makes these testable without booting
    /// anything, which matters because the arm64 cloud images for Debian 9 and 11
    /// do not boot under Apple's hypervisor at all.
    #[test]
    fn a_release_names_itself_without_a_machine_to_read_it_from() {
        let db = SignatureDb::global();
        for (banner, release) in [
            ("SSH-2.0-OpenSSH_7.4p1 Debian-10+deb9u7", "9"),
            ("SSH-2.0-OpenSSH_7.9p1 Debian-10+deb10u2", "10"),
            ("SSH-2.0-OpenSSH_8.4p1 Debian-5+deb11u3", "11"),
        ] {
            let found = db
                .identify(22, Protocol::Tcp, banner)
                .and_then(|found| found.os)
                .unwrap_or_else(|| panic!("{banner} names nothing"));

            assert_eq!(found.family.as_deref(), Some("Linux"));
            assert_eq!(found.vendor.as_deref(), Some("Debian"));
            assert_eq!(
                found.version.as_deref(),
                Some(release),
                "read from the stamp rather than from a table of known releases: {banner}"
            );
        }
    }

    /// The channel that answers the question no packet can.
    ///
    /// A TCP stack's shape names a family and cannot separate two kernels eleven
    /// releases apart, measured on two labelled hosts. A service banner names
    /// a distribution release at best. An SNMP agent's `sysDescr` is the output
    /// of `uname -a`, so it states the kernel outright, and 27 shipped rules are
    /// written against it.
    ///
    /// Matched through the same entry point the analyzer uses, so this cannot
    /// pass while the engine feeds the matcher something else, which is how the
    /// SSH release rules stayed unreachable.
    #[test]
    fn an_snmp_agent_names_the_system_it_is_running() {
        let db = SignatureDb::global();
        let sys_descr = "Linux zond 6.1.0-18-arm64 #1 SMP Debian 6.1.76-1 (2024-02-01) aarch64";

        let found = db
            .identify(161, Protocol::Udp, sys_descr)
            .and_then(|found| found.os)
            .expect("a uname string names an operating system");

        assert_eq!(found.family.as_deref(), Some("Linux"));
        assert_eq!(
            found.kernel.as_deref(),
            Some("6.1.0"),
            "the kernel release is the whole reason to read this field: {found:?}"
        );
        assert_eq!(
            found.version, None,
            "a kernel is not a distribution release, and must not occupy its field \
             where it would contradict a banner that named one"
        );
        assert!(
            !found.evidence.to_ascii_lowercase().contains("zond"),
            "the nodename is somebody's hostname and must not travel with the finding"
        );
    }

    /// The claim this module makes, checked against what actually ships rather
    /// than against a fixture: real banners, matched by the real signature
    /// database, produce an operating system.
    ///
    /// Each of these is a string a host genuinely sends. If the imported
    /// metadata stopped reaching the matcher, which is the state this module
    /// exists to prevent, every one would come back naming nothing and no other
    /// test in the tree would notice.
    #[test]
    fn real_banners_name_an_operating_system_through_the_shipped_signatures() {
        let db = SignatureDb::global();
        // Each is the text the corpus's patterns are written against, which is
        // not always the whole banner: the imported HTTP rules match a `Server`
        // header *value* (`^Microsoft-IIS/...$`, anchored both ends), so feeding
        // them a full response can never match. Extracting that value is
        // `HttpHeadersAnalyzer`'s job and is where this evidence is joined up
        // for HTTP; see the note in the module docs.
        let cases = [
            (22u16, "SSH-2.0-OpenSSH_9.6p1 Debian-3"),
            (80, "Microsoft-IIS/4.0"),
        ];
        // Matched the way the analyzer matches them, which for a structured
        // banner is against the field the corpus anchors on as well as the whole
        // line. Feeding only the line would let this test pass while every
        // release-naming SSH rule is unreachable.

        let mut named = 0usize;
        for (port, banner) in cases {
            // The port-linked set first, then the global one, exactly as the
            // matcher does.
            let found = db
                .identify(port, Protocol::Tcp, banner)
                .and_then(|found| found.os);

            if let Some(os) = found {
                assert!(
                    os.family.as_deref().is_none_or(|family| !family.is_empty()),
                    "a named family is not an empty one"
                );
                assert!(os.confidence > 0.0);
                named += 1;
            }
        }

        assert_eq!(
            named,
            cases.len(),
            "a shipped signature failed to name an operating system for text it was \
             written against, which is what it looks like when the imported metadata \
             stops reaching the matcher"
        );
    }
}