zond-engine 0.18.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
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
// 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

//! # Fingerprinting corpus regression tests
//!
//! Locks matching behaviour against silent regression, in four layers:
//!
//! 1. **Self-consistency** ([`every_signature_matches_its_example`]): 95% of
//!    signature rules ship a recorded `example` banner they are meant to match.
//!    Every example is run through the real signature, and every one matches.
//! 2. **Prefilter soundness** ([`prefilter_never_drops_a_matching_signature`]):
//!    for every example that matches its pattern, the global-match prefilter
//!    must select that signature as a candidate. This is what makes it safe to
//!    narrow the global set instead of scanning all of it.
//! 3. **One reply, one witness** ([`one_reply_is_one_witness`]): whatever a
//!    rule's example leaves on a host's record, it leaves under the source it
//!    was read as, so the arithmetic that combines sources never counts one
//!    reading as two witnesses.
//! 4. **Golden end-to-end** ([`golden_cases_resolve_end_to_end`],
//!    [`non_standard_port_is_identified_via_global_fallback`]): real banners
//!    driven through the whole pipeline with the exact verdict pinned.
//!
//! ## Imported examples
//!
//! The rules imported from Recog hold their examples to the same standard,
//! which Recog's own suite holds them to upstream. Each is the text the engine
//! reads a reply as, so an example Recog stores in base64 is stored here
//! decoded, and each pattern carries the flags it was written under: Recog's
//! case-insensitive flag as `(?i)`, its dot-matches-newline as `(?s)`, and
//! Ruby's line anchors, which are the default there, as `(?m)` where a rule
//! relies on them.

use proptest::prelude::*;
use rayon::prelude::*;

use super::db::SignatureDb;
use super::matcher::Signature;
use super::prefilter::{LiteralPrefilter, Prefilter};
use super::response::{Collected, ResponseSet, TlsInfo};
use super::{Analyzer, BannerRegexAnalyzer, PortContext, ServiceVerdict, TlsCertAnalyzer, Tunnel};
use crate::model::confidence::Confidence;

/// The signature set flattened exactly as the runtime builds it, paired with
/// each signature's recorded example (if any).
fn signatures_with_examples() -> (Vec<Signature>, Vec<Option<String>>) {
    let defs = SignatureDb::embedded_definitions();
    let mut signatures = Vec::new();
    let mut examples = Vec::new();
    for def in &defs {
        for rule in &def.r#match {
            signatures.push(Signature::new(&def.service.name, rule));
            examples.push(rule.example.clone().filter(|e| !e.is_empty()));
        }
    }
    (signatures, examples)
}

#[test]
fn every_signature_matches_its_example() {
    let (signatures, examples) = signatures_with_examples();

    let mut mismatches: Vec<String> = signatures
        .par_iter()
        .zip(examples.par_iter())
        .filter_map(|(signature, example)| {
            let example = example.as_deref()?;
            signature
                .identify(example, crate::model::host::OsSource::ServiceBanner)
                .is_none()
                .then(|| format!("example={example:?} pattern={:?}", signature.pattern()))
        })
        .collect();
    mismatches.sort();

    assert!(
        mismatches.is_empty(),
        "{} examples do not match their own rule. A pattern that fails its own \
         example fails the banner it was written from too.\nFirst:\n{}",
        mismatches.len(),
        mismatches
            .iter()
            .take(20)
            .cloned()
            .collect::<Vec<_>>()
            .join("\n"),
    );
}

#[test]
fn prefilter_never_drops_a_matching_signature() {
    let (signatures, examples) = signatures_with_examples();
    let prefilter = LiteralPrefilter::build(&signatures);

    // For every example that genuinely matches its signature, the prefilter must
    // list that signature as a candidate, or global matching would miss it.
    let violations: usize = signatures
        .par_iter()
        .zip(examples.par_iter())
        .enumerate()
        .filter(|(idx, (signature, example))| {
            let Some(example) = example.as_deref() else {
                return false;
            };
            if signature
                .identify(example, crate::model::host::OsSource::ServiceBanner)
                .is_none()
            {
                return false; // example doesn't match anyway (known baseline)
            }
            !prefilter.candidates(example).contains(idx)
        })
        .count();

    assert_eq!(
        violations,
        0,
        "prefilter dropped {}",
        crate::logging::counted(
            violations as u128,
            "matching signature",
            "matching signatures"
        )
    );
}

/// Signatures the prefilter cannot narrow, and so matches against every
/// response on every port, are those with no literal worth indexing: a
/// structural pattern, one written with look-arounds, or one whose literals
/// are all shorter than the prefilter indexes.
///
/// Pinned so a rule the extractor could narrow does not slip into the bucket
/// unnoticed, where it costs a regex run per response for the life of the
/// corpus.
#[test]
fn only_a_pattern_with_no_literal_is_matched_against_every_response() {
    const KNOWN_ALWAYS_RUN: usize = 12;
    let (signatures, _) = signatures_with_examples();
    let prefilter = LiteralPrefilter::build(&signatures);
    let always: Vec<&str> = prefilter
        .always_run()
        .iter()
        .map(|&idx| signatures[idx].pattern())
        .collect();
    assert!(
        always.len() <= KNOWN_ALWAYS_RUN,
        "{} of {} signatures always run:\n{}",
        always.len(),
        signatures.len(),
        always.join("\n")
    );
}

/// One reply is one witness, whatever the rule that read it says about the
/// machine.
///
/// Every shipped rule's example, read as each kind of text a rule is matched
/// against, and filed with a host the way a reply's reading is: what it implies
/// about the system and the hardware it describes, together, on a host with no
/// address behind it and no name. Whatever that leaves on record has to be
/// filed under the source that was read. Filed under another, the reply stands
/// in for a witness that said nothing, and beside its own reading it is counted
/// twice, which the arithmetic that combines sources takes for two witnesses
/// agreeing: a vendor a service described, read back as its address's own,
/// carries a single SNMP description past the confidence at which the active
/// OS probe is skipped.
///
/// What it sees is what one reply produces. A scanner joining two exchanges,
/// such as a name one of them learned and a record the other fetched under
/// that name, is outside any sweep of single replies, and each such join is
/// pinned where it is made.
#[test]
fn one_reply_is_one_witness() {
    use crate::model::host::{Host, OsSource};
    use std::collections::BTreeSet;

    let (signatures, examples) = signatures_with_examples();
    let read_as = [
        OsSource::ServiceBanner,
        OsSource::SnmpAgent,
        OsSource::MdnsResponder,
    ];

    let mut misfiled: Vec<String> = signatures
        .par_iter()
        .zip(examples.par_iter())
        .filter_map(|(signature, example)| Some((signature, example.as_deref()?)))
        .flat_map_iter(|(signature, example)| {
            read_as.into_iter().filter_map(move |source| {
                let matched = signature.identify(example, source)?;
                let mut host = Host::new("192.0.2.1".parse().expect("a literal address"));
                super::AboutTheHost {
                    os: matched.os.into_iter().collect(),
                    hardware: matched.hardware,
                    names: Vec::new(),
                }
                .apply(&mut host);

                let filed: BTreeSet<OsSource> =
                    host.os_evidence().map(|evidence| evidence.source).collect();
                filed
                    .iter()
                    .any(|other| *other != source)
                    .then(|| format!("{example:?} read as {source:?} left {filed:?}"))
            })
        })
        .collect();
    misfiled.sort();

    assert!(
        misfiled.is_empty(),
        "{} left a reading under a source they were not read as:\n{}",
        crate::logging::counted(misfiled.len() as u128, "example", "examples"),
        misfiled
            .iter()
            .take(20)
            .cloned()
            .collect::<Vec<_>>()
            .join("\n"),
    );
}

#[test]
fn golden_cases_resolve_end_to_end() {
    struct Case {
        port: u16,
        response: &'static str,
        service: &'static str,
        product: Option<&'static str>,
        version: Option<&'static str>,
    }

    let cases = [
        Case {
            port: 22,
            response: "SSH-2.0-OpenSSH_9.6p1 Debian-3",
            service: "ssh",
            product: Some("OpenSSH"),
            version: Some("9.6p1"),
        },
        Case {
            port: 22,
            response: "SSH-2.0-dropbear_2022.83",
            service: "ssh",
            product: Some("dropbear"),
            version: Some("2022.83"),
        },
        // Best-match, not first-match: the generic `HTTP/1.1` signature is
        // listed before the `Server: nginx` one and matches this response too,
        // but the more specific match, naming product and version, has to win.
        Case {
            port: 80,
            response: "HTTP/1.1 200 OK\r\nServer: nginx/1.25.3\r\nContent-Type: text/html\r\n\r\n",
            service: "http",
            product: Some("nginx"),
            version: Some("1.25.3"),
        },
    ];

    for case in cases {
        let responses = ResponseSet::from_banners(vec![case.response.to_string()]);
        let evidence = BannerRegexAnalyzer.analyze(
            &PortContext {
                port: case.port,
                protocol: crate::model::port::Protocol::Tcp,
                addr: None,
                tunnel: None,
                speaks_http: false,
                detection: crate::config::ServiceDetection::default(),
                host_name: None,
            },
            &responses,
            &Collected::default(),
        );
        let verdict = ServiceVerdict::resolve(evidence);

        assert_eq!(
            verdict.service.as_deref(),
            Some(case.service),
            "service for {:?}",
            case.response
        );
        if let Some(product) = case.product {
            assert_eq!(
                verdict.product.as_deref(),
                Some(product),
                "product for {:?}",
                case.response
            );
        }
        if let Some(version) = case.version {
            assert_eq!(
                verdict.version.as_deref(),
                Some(version),
                "version for {:?}",
                case.response
            );
        }
    }
}

#[test]
fn non_standard_port_is_identified_via_global_fallback() {
    // SSH on an unclaimed high port: no linked signatures, so identification
    // must come from the prefilter-narrowed global fallback.
    let port = 51987;
    assert!(
        SignatureDb::global().signatures_for_port(port).is_empty(),
        "test assumes port {port} is unclaimed"
    );

    let responses = ResponseSet::from_banners(vec!["SSH-2.0-OpenSSH_9.6p1".to_string()]);
    let evidence = BannerRegexAnalyzer.analyze(
        &PortContext {
            protocol: crate::model::port::Protocol::Tcp,
            port,
            addr: None,
            tunnel: None,
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        },
        &responses,
        &Collected::default(),
    );
    // A global-fallback match is not corroborated by the port.
    assert!(
        evidence.iter().all(|e| !e.port_confirmed),
        "global-fallback evidence must not be port-confirmed"
    );
    let verdict = ServiceVerdict::resolve(evidence);

    assert_eq!(verdict.service.as_deref(), Some("ssh"));
    assert_eq!(verdict.product.as_deref(), Some("OpenSSH"));
    assert_eq!(verdict.version.as_deref(), Some("9.6p1"));
}

proptest! {
    /// The headline fuzz target: adversarial banners driven through the whole
    /// banner-matching pipeline against the real signature set, so prefilter,
    /// then regex, then best-match, then resolve. It never panics and always
    /// terminates, whatever bytes arrive on the wire. Port 80 exercises the
    /// port-linked tier; unmatched banners fall through to the global prefilter,
    /// so both matching paths are covered.
    #[test]
    fn banner_pipeline_never_panics_on_adversarial_input(banner in "(?s).*") {
        let responses = ResponseSet::from_banners(vec![banner]);
        let ctx = PortContext {
            port: 80,
            protocol: crate::model::port::Protocol::Tcp,
            addr: None,
            tunnel: None,
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        };
        let evidence = BannerRegexAnalyzer.analyze(&ctx, &responses, &Collected::default());
        let _ = ServiceVerdict::resolve(evidence);
    }
}

#[test]
fn port_linked_match_is_tagged_port_confirmed() {
    // The same SSH banner on port 22 matches a signature registered for the
    // port, so its evidence is port-confirmed, the flag the resolver ranks on.
    let responses = ResponseSet::from_banners(vec!["SSH-2.0-OpenSSH_9.6p1 Debian-3".to_string()]);
    let evidence = BannerRegexAnalyzer.analyze(
        &PortContext {
            port: 22,
            protocol: crate::model::port::Protocol::Tcp,
            addr: None,
            tunnel: None,
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        },
        &responses,
        &Collected::default(),
    );
    assert!(
        evidence.iter().any(|e| e.port_confirmed),
        "a port-linked match must be tagged port-confirmed"
    );
}

/// A recorded self-signed appliance certificate (DER). Subject == issuer,
/// `O=Zond Appliance`, `CN=zond-device.local`. Serves as the parse oracle for
/// the TLS analyzer, mirroring the recorded-banner corpus above.
const SELF_SIGNED_CERT: &[u8] = include_bytes!("testdata/selfsigned.der");

#[test]
fn tls_cert_identifies_self_signed_appliance() {
    let responses = ResponseSet::default().with_tls(TlsInfo {
        certificates: vec![SELF_SIGNED_CERT.to_vec()],
        ..TlsInfo::default()
    });

    let evidence = TlsCertAnalyzer.analyze(
        &PortContext {
            port: 8443,
            protocol: crate::model::port::Protocol::Tcp,
            addr: None,
            tunnel: Some(Tunnel::Tls),
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        },
        &responses,
        &Collected::default(),
    );
    let verdict = ServiceVerdict::resolve(evidence);

    // The port is identified as TLS, and the self-signed subject O= names the vendor.
    assert_eq!(verdict.service.as_deref(), Some("ssl"));
    assert_eq!(verdict.vendor.as_deref(), Some("Zond Appliance"));
    assert_eq!(verdict.confidence, Confidence::Probable);
    let service = verdict.to_service().unwrap();
    // The tunnel's own `ssl` verdict is not re-prefixed into `ssl/ssl`, even
    // under a TLS context.
    assert_eq!(service.name(), "ssl");
    // The vendor reaches the projected Service, rather than being extracted
    // here and dropped by `to_service`.
    assert_eq!(service.vendor(), Some("Zond Appliance"));
}

#[test]
fn tls_analyzer_is_silent_without_a_certificate() {
    // No TLS captured: the analyzer must produce nothing, not a bare "ssl".
    let responses = ResponseSet::from_banners(vec!["HTTP/1.1 200 OK".to_string()]);
    assert!(
        TlsCertAnalyzer
            .analyze(
                &PortContext {
                    port: 80,
                    protocol: crate::model::port::Protocol::Tcp,
                    addr: None,
                    tunnel: None,
                    speaks_http: false,
                    detection: crate::config::ServiceDetection::default(),
                    host_name: None,
                },
                &responses,
                &Collected::default(),
            )
            .is_empty()
    );
}

#[test]
fn banner_matched_in_a_tunnel_is_labelled_with_scheme() {
    // A protocol identified from data read inside TLS keeps its bare service on
    // the evidence but is labelled `ssl/<proto>` for the user.
    let responses = ResponseSet::from_banners(vec!["SSH-2.0-OpenSSH_9.6p1".to_string()]);
    let ctx = PortContext {
        port: 22,
        protocol: crate::model::port::Protocol::Tcp,
        addr: None,
        tunnel: Some(Tunnel::Tls),
        speaks_http: false,
        detection: crate::config::ServiceDetection::default(),
        host_name: None,
    };
    let evidence = BannerRegexAnalyzer.analyze(&ctx, &responses, &Collected::default());
    let verdict = ServiceVerdict::resolve(evidence);

    assert_eq!(verdict.service.as_deref(), Some("ssh")); // evidence stays bare
    assert_eq!(verdict.tunnel, Some(Tunnel::Tls));
    assert_eq!(verdict.to_service().unwrap().name(), "ssl/ssh"); // label composes both
}

/// What the banner analyzer names `banner` on `port`, as the service and
/// product of its resolved verdict.
fn named(port: u16, protocol: crate::model::port::Protocol, banner: &str) -> ServiceVerdict {
    let responses = ResponseSet::from_banners(vec![banner.to_string()]);
    let evidence = BannerRegexAnalyzer.analyze(
        &PortContext {
            port,
            protocol,
            addr: None,
            tunnel: None,
            speaks_http: false,
            detection: crate::config::ServiceDetection::default(),
            host_name: None,
        },
        &responses,
        &Collected::default(),
    );
    ServiceVerdict::resolve(evidence)
}

/// A Zabbix agent is named by the header its protocol frames every reply
/// in, and not by the digit an `agent.ping` answer carries.
///
/// A rule anchored on that digit alone is consulted across the whole corpus
/// for any port its own did not name, and reads every text that begins with
/// a `1` as an agent: a session cookie, a page titled with a count, the
/// object identifier every SNMP agent answers with. Each of those put a
/// monitoring agent's name on a web server or a printer.
#[test]
fn only_a_framed_zabbix_reply_is_named_zabbix() {
    use crate::model::port::Protocol::{Tcp, Udp};

    let not_zabbix = [
        (
            8080,
            Tcp,
            "HTTP/1.1 200 OK\r\nServer: farm\r\nSet-Cookie: 1f3a9c=0; Path=/\r\n\
             Content-Type: text/html\r\n\r\n<title>1 new message</title>",
        ),
        (51987, Tcp, "1\r\n"),
        (161, Udp, "1.3.6.1.4.1.11.2.3.9.1"),
    ];
    for (port, protocol, banner) in not_zabbix {
        // Every witness rather than the winner: a reading that loses the
        // ranking on one port is still a reading, and it wins on the next
        // port that has nothing better to say.
        let verdict = named(port, protocol, banner);
        assert!(
            verdict
                .evidence
                .iter()
                .all(|evidence| evidence.service.as_deref() != Some("zabbix")),
            "{banner:?} on {port} was read as zabbix: {verdict:?}"
        );
    }

    // `agent.ping` answered: the header, the protocol flag, an eight-byte
    // little-endian length of one, and the `1` itself.
    let pong = "ZBXD\u{1}\u{1}\0\0\0\0\0\0\0\u{31}";
    for port in [10050, 51987] {
        let verdict = named(port, Tcp, pong);
        assert_eq!(verdict.service.as_deref(), Some("zabbix"), "on {port}");
    }
}

/// A raw-print port is named by the PJL its printer answers in, and not by
/// the two letters of a vendor's name wherever they fall.
///
/// A rule reading `HP` anywhere is consulted across the whole corpus for any
/// port its own did not name, and reads every reply that mentions PHP, an
/// `X-Powered-By` header or a page about it, as a JetDirect printer. What a
/// printer on its raw port says of its own accord is a PJL reply, which opens
/// with the `@PJL` command it answers.
#[test]
fn only_a_pjl_reply_is_named_a_raw_print_port() {
    use crate::model::port::Protocol::Tcp;

    let not_a_printer = [
        (
            8080,
            "HTTP/1.1 200 OK\r\nServer: Apache\r\nX-Powered-By: PHP/8.1.2\r\n\
             Content-Type: text/html\r\n\r\n<title>Welcome</title>",
        ),
        (51987, "X-Powered-By: PHP/8.1.2"),
        (9100, "Powered by PHP"),
    ];
    for (port, banner) in not_a_printer {
        let verdict = named(port, Tcp, banner);
        assert!(
            verdict
                .evidence
                .iter()
                .all(|evidence| evidence.service.as_deref() != Some("jetdirect")),
            "{banner:?} on {port} was read as a raw-print port: {verdict:?}"
        );
    }

    // `@PJL INFO ID` answered: the command echoed, then the model in quotes
    // and the form feed that ends every PJL reply.
    let id = "@PJL INFO ID\r\n\"HP LaserJet 4250\"\r\n\u{c}";
    let verdict = named(9100, Tcp, id);
    assert_eq!(verdict.service.as_deref(), Some("jetdirect"));
}

/// Every rule that reads a byte from 0x80 up ships an example, so the tests
/// above run it.
///
/// Those are the rules a reading of the reply as text can lose: a decoder that
/// turned such a byte into anything but its own code point left thirteen of
/// them matching nothing, and none carried an example that would have said so.
/// A rule of that kind without one is a rule nothing checks.
#[test]
fn every_rule_reading_a_high_byte_ships_an_example() {
    /// Whether `pattern` names, by escape, a byte from 0x80 up.
    fn names_a_high_byte(pattern: &str) -> bool {
        pattern
            .match_indices("\\x")
            .filter_map(|(at, _)| pattern.get(at + 2..at + 4))
            .filter_map(|digits| u8::from_str_radix(digits, 16).ok())
            .any(|byte| byte >= 0x80)
    }

    let mut unexampled: Vec<String> = SignatureDb::embedded_definitions()
        .iter()
        .flat_map(|def| {
            def.r#match
                .iter()
                .filter(|rule| names_a_high_byte(&rule.pattern))
                .filter(|rule| rule.example.as_deref().is_none_or(str::is_empty))
                .map(|rule| {
                    format!(
                        "{}#{}",
                        def.service.name,
                        rule.name.as_deref().unwrap_or("?")
                    )
                })
        })
        .collect();
    unexampled.sort();

    assert!(
        unexampled.is_empty(),
        "rules reading a high byte with no example: {unexampled:?}"
    );
}

/// Binary replies reach the rules written for their bytes, read the way the
/// transport reads them.
///
/// Each reply is built from the specification of its protocol and handed over
/// as bytes, so the decoding between the socket and the matcher is under test
/// as well as the rule: every one of these was once matched against text in
/// which its high bytes had become the replacement character.
#[test]
fn binary_replies_reach_the_rules_written_for_their_bytes() {
    use crate::model::port::Protocol::Tcp;

    let replies: &[(u16, &[u8], &str)] = &[
        // RFC 1002 §4.3.3: a positive session response.
        (139, b"\x82\x00\x00\x00", "netbios-ssn"),
        // RFC 1002 §4.3.4: a negative one, called name not present.
        (139, b"\x83\x00\x00\x01\x82", "netbios-ssn"),
        // RFC 854: IAC DO TERMINAL-TYPE.
        (23, b"\xff\xfd\x18\xff\xfd\x20", "telnet"),
        // An Active Directory bind response, every length in four bytes.
        (
            389,
            b"\x30\x84\x00\x00\x00\x10\x02\x01\x01\x61\x84\x00\x00\x00\x07\x0a\x01\x00\x04\x00\x04\x00",
            "ldap",
        ),
        // RFC 1928 §3: no acceptable method.
        (1080, b"\x05\xff", "socks5"),
        // RFC 4271 §4.5: NOTIFICATION, Cease.
        (
            179,
            b"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00\x15\x03\x06\x05",
            "bgp",
        ),
        // RFC 2637 §2.2: Start-Control-Connection-Reply.
        (
            1723,
            b"\x00\x9c\x00\x01\x1a\x2b\x3c\x4d\x00\x02\x00\x00\x01\x00\x01\x00",
            "pptp",
        ),
        // ZMTP 3.0: the greeting's signature and version.
        (5556, b"\xff\x00\x00\x00\x00\x00\x00\x00\x01\x7f\x03\x00", "zeromq"),
        // A native protocol v4 ERROR frame.
        (9042, b"\x84\x00\x00\x01\x00\x00\x00\x00\x10", "cassandra"),
        // The legacy server list ping answered.
        (
            25565,
            b"\xff\x00\x16\x00\xa7\x00\x31\x00\x00\x00\x37\x00\x36",
            "minecraft",
        ),
        // A record-marked PMAPPROC_DUMP reply naming nothing.
        (
            111,
            b"\x80\x00\x00\x1czond\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
            "rpcbind",
        ),
        // RFC 1179: a daemon command acknowledged.
        (515, b"\x00", "lpd"),
        // The RMI transport protocol: ProtocolAck and the endpoint seen.
        (1099, b"N\x00\x0c198.51.100.7\x00\x00\x04\x4b", "java-rmi"),
        // AFP over TCP: a DSI GetStatus reply's header.
        (
            548,
            b"\x01\x03\x00\x01\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00",
            "afp",
        ),
        // NRPE: a version 2 response, OK, two of whose CRC bytes read as one
        // UTF-8 character.
        (5666, b"\x00\x02\x00\x02\x5a\xc3\x91\x07\x00\x00NRPE v4.1.0", "nrpe"),
        // MQTT 3.1.1 §3.2: CONNACK, connection accepted.
        (1883, b"\x20\x02\x00\x00", "mqtt"),
        // RFC 1928 §3: no authentication required.
        (1080, b"\x05\x00", "socks5"),
        // MS-TDS 2.2.6.5: a pre-login response naming SQL Server 15.0.2000.
        (1433, TDS_PRELOGIN_RESPONSE, "mssql"),
        // The SOCKS 4 protocol: request granted.
        (
            51987,
            b"\x00\x5a\x00\x50\x7f\x00\x00\x01",
            "socks4",
        ),
        // The memcached binary protocol: a version response naming 1.6.21.
        (
            11211,
            b"\x81\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x00\
              \x00\x00\x00\x00\x00\x00\x00\x001.6.21",
            "memcached_binary",
        ),
    ];

    for (port, reply, service) in replies {
        let text = super::extract::reply_text(reply);
        let verdict = named(*port, Tcp, &text);
        assert_eq!(
            verdict.service.as_deref(),
            Some(*service),
            "{reply:02x?} on {port}"
        );
    }
}

/// A pre-login response as MS-TDS lays it out: the packet header, the VERSION,
/// ENCRYPTION, INSTOPT, THREADID and MARS options and their terminator, then
/// their data.
const TDS_PRELOGIN_RESPONSE: &[u8] = b"\x04\x01\x00\x2b\x00\x00\x01\x00\
    \x00\x00\x1a\x00\x06\x01\x00\x20\x00\x01\x02\x00\x21\x00\x01\x03\x00\x22\x00\x00\
    \x04\x00\x22\x00\x01\xff\x0f\x00\x07\xd0\x00\x00\x02\x00\x00";

/// A binary rule claims its protocol's reply and not another's that opens the
/// same way.
///
/// Each of these rules once read one or two leading bytes, and they are
/// consulted on every port nothing else names, where a reply of any protocol
/// can arrive. Each is held here against a reply of a different protocol
/// sharing its first bytes, taken from that protocol's specification, and so
/// against the rule itself rather than whichever rule wins the ranking.
#[test]
fn a_binary_rule_does_not_claim_another_protocol_opening_the_same_way() {
    // A Modbus TCP reply to a register read: transaction ID, protocol zero,
    // a length, then unit, function and one register.
    fn modbus(transaction: [u8; 2]) -> Vec<u8> {
        let mut reply = transaction.to_vec();
        reply.extend_from_slice(b"\x00\x00\x00\x05\x01\x03\x02\x00\x2a");
        reply
    }
    let cases: &[(&str, &str, Vec<u8>)] = &[
        // Kerberos over TCP, RFC 4120 §7.2.2: a length, then a KRB-ERROR.
        (
            "lpd",
            "lpd_response",
            b"\x00\x00\x00\x0b\x7e\x09\x30\x07\xa6\x03\x02\x01\x06".to_vec(),
        ),
        // RFC 2637 §2.2: PPTP's Start-Control-Connection-Reply.
        (
            "lpd",
            "lpd_response",
            b"\x00\x9c\x00\x01\x1a\x2b\x3c\x4d\x00\x02\x00\x00".to_vec(),
        ),
        // RFC 2812 §3.3.2: an IRC server's first words.
        (
            "java-rmi",
            "jrmp_ack",
            b"NOTICE AUTH :*** Looking up your hostname\r\n".to_vec(),
        ),
        ("afp", "dsi_reply", modbus([0x01, 0x03])),
        ("nrpe", "nrpe_response", modbus([0x00, 0x02])),
        ("mqtt", "mqtt_connack", modbus([0x20, 0x02])),
        // DCE/RPC's bind_ack: version 5, minor version 0, packet type 12.
        (
            "socks5",
            "socks5_response",
            b"\x05\x00\x0c\x03\x10\x00\x00\x00\x44\x00\x00\x00".to_vec(),
        ),
        ("mssql", "mssql_prelogin_response", modbus([0x04, 0x01])),
        // RFC 9110 §15.6.2: any other server declining a method it lacks.
        (
            "tor",
            "tor_socks_match",
            b"HTTP/1.0 501 Not Implemented\r\n\r\n".to_vec(),
        ),
        // RFC 1035 §4.2.2: a DNS reply over TCP, ninety bytes long.
        (
            "socks4",
            "socks4_response",
            b"\x00\x5a\x12\x34\x81\x80\x00\x01\x00\x01\x00\x00\x00\x00".to_vec(),
        ),
        // RFC 6455 §5.2: a WebSocket text frame of ten bytes.
        (
            "memcached_binary",
            "version_response",
            b"\x81\x0aHello Zond".to_vec(),
        ),
    ];

    let defs = SignatureDb::embedded_definitions();
    let claimed: Vec<String> = cases
        .iter()
        .filter(|(service, rule, reply)| {
            let (def, matched) = defs
                .iter()
                .filter(|def| def.service.name == *service)
                .find_map(|def| {
                    def.r#match
                        .iter()
                        .find(|candidate| candidate.name.as_deref() == Some(*rule))
                        .map(|matched| (def, matched))
                })
                .unwrap_or_else(|| panic!("no rule {service}#{rule}"));
            Signature::new(&def.service.name, matched)
                .identify(
                    &super::extract::reply_text(reply),
                    crate::model::host::OsSource::ServiceBanner,
                )
                .is_some()
        })
        .map(|(service, rule, reply)| format!("{service}#{rule} claimed {reply:02x?}"))
        .collect();

    assert!(claimed.is_empty(), "{claimed:#?}");
}

/// A high first byte alone names nothing.
///
/// These rules are consulted on every port nothing else names, and a dozen
/// binary protocols open on 0xFF or on a byte just past 0x80. Each is written
/// against its protocol's header whole, so a reply that shares one byte with
/// it is not taken for it.
#[test]
fn a_high_first_byte_alone_names_no_binary_protocol() {
    use crate::model::port::Protocol::Tcp;

    let others: &[&[u8]] = &[
        b"\x82\x01\x02\x03 something else",
        b"\x80\x00\x01\x00 not a reply to this engine",
        b"\xff\x00\x10\x00\x41\x00\x42",
    ];
    for reply in others {
        let verdict = named(51987, Tcp, &super::extract::reply_text(reply));
        for claimed in ["netbios-ssn", "rpcbind", "minecraft", "zeromq"] {
            assert!(
                verdict
                    .evidence
                    .iter()
                    .all(|evidence| evidence.service.as_deref() != Some(claimed)),
                "{reply:02x?} was read as {claimed}: {verdict:?}"
            );
        }
    }
}

/// A NetBIOS session service is named from its answer end to end, over a
/// socket, the one path every other test here stands in for.
#[tokio::test]
async fn a_session_service_is_named_from_its_answer_over_a_socket() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    use crate::model::port::{PortState, Protocol};
    use crate::testing::loopback::accept_from_this_process;

    let listener = TcpListener::bind("127.0.0.1:0").await.expect("a socket");
    let addr = listener.local_addr().expect("its address");
    let server = tokio::spawn(async move {
        let Ok(mut sock) = accept_from_this_process(&listener).await else {
            return;
        };
        let mut request = [0u8; 128];
        if sock.read(&mut request).await.is_ok_and(|read| read > 0) {
            let _ = sock.write_all(b"\x82\x00\x00\x00").await;
        }
        let _ = sock.read(&mut request).await;
    });

    let stream = TcpStream::connect(addr).await.expect("connects");
    let port = super::baseline_port(139, Protocol::Tcp, PortState::Open);
    let identified =
        super::fingerprint_tcp(stream, port, crate::config::ServiceDetection::Probe).await;
    server.abort();

    // Named above the label the port's number alone earns, which is what it
    // carries before anything is asked.
    let labelled = super::baseline_port(139, Protocol::Tcp, PortState::Open);
    let label = labelled.service().map(|service| service.confidence());
    let identified = identified.service().expect("the port is named");
    assert_eq!(identified.name(), "netbios-ssn");
    assert!(
        Some(identified.confidence()) > label,
        "{identified:?} is no more than the port's label"
    );
}

/// A server that answers the RDP negotiation is named, with the security layer
/// it chose.
///
/// Every Windows release since Vista and xrdp answer a negotiation request
/// with a 19-byte Connection Confirm (MS-RDPBCGR 2.2.1.2), and which layer the
/// server selects is the question an assessor asks of it first: CredSSP
/// authenticates before any session exists, and TLS alone puts a logon screen
/// in front of whoever connects.
#[test]
fn an_rdp_negotiation_answer_names_the_security_layer() {
    use crate::model::port::Protocol::Tcp;

    let answers: &[(&[u8], Option<&str>)] = &[
        (
            b"\x03\x00\x00\x13\x0e\xd0\x00\x00\x12\x34\x00\x02\x1f\x08\x00\x02\x00\x00\x00",
            Some("security layer: CredSSP (NLA)"),
        ),
        (
            b"\x03\x00\x00\x13\x0e\xd0\x00\x00\x12\x34\x00\x02\x01\x08\x00\x01\x00\x00\x00",
            Some("security layer: TLS without NLA"),
        ),
        (
            b"\x03\x00\x00\x13\x0e\xd0\x00\x00\x12\x34\x00\x03\x00\x08\x00\x02\x00\x00\x00",
            Some("security layer: standard RDP security only"),
        ),
        // A source reference whose two bytes form a UTF-8 sequence.
        (
            b"\x03\x00\x00\x13\x0e\xd0\x00\x00\xc3\xa9\x00\x02\x1f\x08\x00\x02\x00\x00\x00",
            Some("security layer: CredSSP (NLA)"),
        ),
        // A server from before negotiation existed.
        (b"\x03\x00\x00\x0b\x06\xd0\x00\x00\x12\x34\x00", None),
    ];
    for (answer, layer) in answers {
        let verdict = named(3389, Tcp, &super::extract::reply_text(answer));
        assert_eq!(verdict.service.as_deref(), Some("rdp"), "{answer:02x?}");
        assert_eq!(verdict.extrainfo.as_deref(), *layer, "{answer:02x?}");
    }
}

/// The same, end to end over a socket: the probe goes out, the confirm comes
/// back, and the port is named from it.
#[tokio::test]
async fn an_rdp_server_is_named_from_its_negotiation_over_a_socket() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::{TcpListener, TcpStream};

    use crate::model::port::{PortState, Protocol};
    use crate::testing::loopback::accept_from_this_process;

    let listener = TcpListener::bind("127.0.0.1:0").await.expect("a socket");
    let addr = listener.local_addr().expect("its address");
    let server = tokio::spawn(async move {
        let Ok(mut sock) = accept_from_this_process(&listener).await else {
            return;
        };
        let mut request = [0u8; 64];
        // Answer only a negotiation request, as a real server does.
        if sock
            .read(&mut request)
            .await
            .is_ok_and(|read| read == 19 && request[5] == 0xe0)
        {
            let _ = sock
                .write_all(
                    b"\x03\x00\x00\x13\x0e\xd0\x00\x00\x12\x34\x00\x02\x1f\x08\x00\x02\x00\x00\x00",
                )
                .await;
        }
        let _ = sock.read(&mut request).await;
    });

    let stream = TcpStream::connect(addr).await.expect("connects");
    let port = super::baseline_port(3389, Protocol::Tcp, PortState::Open);
    let identified =
        super::fingerprint_tcp(stream, port, crate::config::ServiceDetection::Probe).await;
    server.abort();

    let service = identified.service().expect("the port is named");
    assert_eq!(service.name(), "rdp");
    assert_eq!(service.extrainfo(), Some("security layer: CredSSP (NLA)"));
}

/// A domain controller's root DSE as the matcher reads it: the attributes the
/// rules read, at the functional level `level`, in the four-byte lengths
/// Active Directory writes.
fn root_dse(level: &[u8]) -> String {
    let mut bytes = b"\x04\x15supportedCapabilities1\x84\x00\x00\x00\x18\x04\x16".to_vec();
    bytes.extend_from_slice(b"1.2.840.113556.1.4.8000\x84\x00\x00\x00\x28");
    bytes.extend_from_slice(b"\x04\x1ddomainControllerFunctionality1\x84\x00\x00\x00");
    bytes.push(2 + level.len() as u8);
    bytes.extend_from_slice(&[0x04, level.len() as u8]);
    bytes.extend_from_slice(level);
    super::extract::reply_text(&bytes)
}

/// A domain controller's functional level names its release only as far as
/// the level does.
///
/// Level 7 is the highest Server 2016, 2019 and 2022 support alike, so it
/// names Windows Server and no release. A 2016 reading there would stand on
/// every 2019 and 2022 controller with a CPE sending it to the wrong
/// vulnerability records, and nothing else a modern controller answers would
/// contradict it. Level 10 is Server 2025's alone, and level 6 still names
/// 2012 R2.
#[test]
fn a_functional_level_names_the_release_only_as_far_as_it_goes() {
    use crate::model::port::Protocol::Tcp;

    // The CPE a reading carries, release and all: `windows` is the family's
    // own, which is as far as level 7 goes.
    let cases: &[(&[u8], &str, &str)] = &[
        (b"7", "Windows Server", "cpe:/o:microsoft:windows:-"),
        (
            b"10",
            "Windows Server 2025",
            "cpe:/o:microsoft:windows_server_2025:-",
        ),
        (
            b"6",
            "Windows Server 2012 R2",
            "cpe:/o:microsoft:windows_server_2012:-",
        ),
    ];
    for (level, product, cpe) in cases {
        let found = SignatureDb::global()
            .identify(389, Tcp, &root_dse(level))
            .expect("a controller's root DSE is read");
        let os = found.os.expect("the level names an operating system");
        assert_eq!(os.product.as_deref(), Some(*product), "level {level:?}");
        assert_eq!(os.cpe.as_deref(), Some(*cpe), "level {level:?}");
        assert_eq!(
            found.product.as_deref(),
            Some("Active Directory Controller")
        );
    }
}

/// A domain controller read over SMB and LDAP together is reported with the
/// CPE of the release the two establish.
///
/// Its SMB service states build 20348, which is Windows Server 2022 and
/// carries that release's CPE; its functional level of 7 names Windows Server
/// and carries the family's. The first is the second carried further, so the
/// merged product is the 2022 release, and its CPE has to be the one naming
/// it: the family's is a true reading of something coarser than what was
/// concluded, and two CPEs that differ for that reason are no disagreement.
/// Dropping both left a controller with a named release and no identifier
/// to look its vulnerabilities up by, less than SMB said alone.
#[test]
fn smb_and_ldap_together_keep_the_cpe_of_the_release_they_establish() {
    use crate::model::port::Protocol::Tcp;

    let db = SignatureDb::global();
    let read = |port: u16, text: &str| {
        db.identify(port, Tcp, text)
            .and_then(|found| found.os)
            .expect("the reply names an operating system")
    };
    let smb = read(445, "Windows 10.0 Build 20348");
    let ldap = read(389, &root_dse(b"7"));

    for evidence in [vec![smb.clone(), ldap.clone()], vec![ldap, smb]] {
        let verdict = super::os::resolve(evidence).expect("the two agree");
        assert_eq!(verdict.product.as_deref(), Some("Windows Server 2022"));
        assert_eq!(
            verdict.cpe.as_deref(),
            Some("cpe:/o:microsoft:windows_server_2022:-")
        );
    }
}

/// What the transport hands the matcher for `bytes` read from `port`: the
/// fields a structured reply yields, then the reply whole, as the banner
/// collection does.
fn read_as_the_transport(port: u16, bytes: &[u8]) -> ServiceVerdict {
    let mut banners = super::extract::from_stream(port, bytes);
    banners.push(super::extract::reply_text(bytes));
    let evidence = BannerRegexAnalyzer.analyze(
        &PortContext::new(port, crate::model::port::Protocol::Tcp),
        &ResponseSet::from_banners(banners),
        &Collected::default(),
    );
    ServiceVerdict::resolve(evidence)
}

/// The services a domain, a file server or a database host answers on every
/// day are named past a label, over TCP, from what each says before any
/// login.
///
/// Each reply is built from its protocol's specification: a password-protected
/// Redis refusing INFO, a VNC server's greeting, a SQL Server pre-login answer,
/// and a KDC, an NFS server and a nameserver each answering over TCP the
/// question the corpus had asked them only over UDP.
#[test]
fn everyday_services_are_named_over_tcp_from_what_they_say_first() {
    struct Case {
        port: u16,
        reply: Vec<u8>,
        service: &'static str,
        product: Option<&'static str>,
        version: Option<&'static str>,
        extrainfo: Option<&'static str>,
    }

    // A KRB-ERROR, error 6, behind its four-byte length.
    let krb_error = {
        let fields = [0xA6, 0x03, 0x02, 0x01, 6];
        let mut sequence = vec![0x30, fields.len() as u8];
        sequence.extend_from_slice(&fields);
        let mut error = vec![0x7E, sequence.len() as u8];
        error.extend_from_slice(&sequence);
        let mut framed = (error.len() as u32).to_be_bytes().to_vec();
        framed.extend_from_slice(&error);
        framed
    };
    // A PROG_MISMATCH for versions 3 to 4, behind a last-fragment record mark.
    let nfs_mismatch = {
        let mut reply = b"zone".to_vec();
        for word in [1u32, 0, 0, 0, 2, 3, 4] {
            reply.extend_from_slice(&word.to_be_bytes());
        }
        let mut framed = (0x8000_0000 | reply.len() as u32).to_be_bytes().to_vec();
        framed.extend_from_slice(&reply);
        framed
    };
    // A version.bind answer from BIND, behind its two-byte length.
    let bind_version = {
        let mut message = b"\x00\x00\x84\x00\x00\x01\x00\x01\x00\x00\x00\x00".to_vec();
        message.extend_from_slice(b"\x07version\x04bind\x00\x00\x10\x00\x03");
        let text = b"9.18.28-0ubuntu0.22.04.1-Ubuntu";
        message.extend_from_slice(b"\xc0\x0c\x00\x10\x00\x03\x00\x00\x00\x00");
        message.extend_from_slice(&((text.len() + 1) as u16).to_be_bytes());
        message.push(text.len() as u8);
        message.extend_from_slice(text);
        let mut framed = (message.len() as u16).to_be_bytes().to_vec();
        framed.extend_from_slice(&message);
        framed
    };
    // A pre-login response: VERSION 15.0.2000, then ENCRYPTION, then the end.
    let prelogin = b"\x04\x01\x00\x1a\x00\x00\x01\x00\
        \x00\x00\x0b\x00\x06\x01\x00\x11\x00\x01\xff\x0f\x00\x07\xd0\x00\x00\x02"
        .to_vec();

    let cases = [
        Case {
            port: 6379,
            reply: b"-NOAUTH Authentication required.\r\n".to_vec(),
            service: "redis",
            product: None,
            version: None,
            extrainfo: Some("authentication required"),
        },
        Case {
            port: 5900,
            reply: b"RFB 003.008\n".to_vec(),
            service: "vnc",
            product: None,
            version: None,
            extrainfo: Some("protocol 3.8"),
        },
        Case {
            port: 1433,
            reply: prelogin,
            service: "mssql",
            product: Some("SQL Server"),
            version: Some("15.0.2000"),
            extrainfo: Some("SQL Server 2019"),
        },
        Case {
            port: 88,
            reply: krb_error,
            service: "kerberos",
            product: None,
            version: None,
            extrainfo: None,
        },
        Case {
            port: 2049,
            reply: nfs_mismatch,
            service: "nfs",
            product: Some("NFS"),
            version: Some("4"),
            extrainfo: Some("versions 3 to 4"),
        },
        Case {
            port: 53,
            reply: bind_version,
            service: "dns",
            product: Some("BIND"),
            version: Some("9.18.28"),
            extrainfo: None,
        },
    ];

    for case in cases {
        let verdict = read_as_the_transport(case.port, &case.reply);
        assert_eq!(
            verdict.service.as_deref(),
            Some(case.service),
            "on {}",
            case.port
        );
        assert_eq!(verdict.product.as_deref(), case.product, "on {}", case.port);
        assert_eq!(verdict.version.as_deref(), case.version, "on {}", case.port);
        assert_eq!(
            verdict.extrainfo.as_deref(),
            case.extrainfo,
            "on {}",
            case.port
        );
    }
}

/// A Kafka broker is named by its answer to the ApiVersions request, and a
/// reply that merely opens on two zero bytes is not taken for one.
///
/// Every protocol that frames its messages with a four-byte length opens that
/// way, and the rule is consulted on every port nothing else names. What only
/// a broker answering this engine's request sends is the correlation id the
/// request carried, and an error code behind it.
#[test]
fn only_a_reply_to_the_api_versions_request_is_named_kafka() {
    use crate::model::port::Protocol::Tcp;

    let broker = super::extract::reply_text(b"\x00\x00\x00\x06\x00\x00\x00\x03\x00\x00");
    assert_eq!(named(9092, Tcp, &broker).service.as_deref(), Some("kafka"));

    let others: &[&[u8]] = &[
        b"\x00\x00\x00\x0b\x7e\x09\x30\x07\xa6\x03\x02\x01\x06",
        b"\x00\x00\x01\x00 some other framed protocol",
    ];
    for reply in others {
        let verdict = named(51987, Tcp, &super::extract::reply_text(reply));
        assert!(
            verdict
                .evidence
                .iter()
                .all(|evidence| evidence.service.as_deref() != Some("kafka")),
            "{reply:02x?} was read as kafka: {verdict:?}"
        );
    }
}

/// The NRPE probe is a version 2 query the daemon answers: the whole 1036-byte
/// packet NRPE's common.h lays out, typed a query, with a CRC-32 that checks.
///
/// The daemon reads a full packet before it replies and drops one whose CRC
/// fails, so a probe short of either is a connection held open until the
/// daemon's own timeout and an NRPE port that answers nothing.
#[test]
fn the_nrpe_probe_is_a_query_the_daemon_answers() {
    // CRC-32 as NRPE computes it: reflected, polynomial 0xEDB88320, starting
    // from and finished with all ones.
    fn crc32(bytes: &[u8]) -> u32 {
        let mut crc = u32::MAX;
        for &byte in bytes {
            crc ^= u32::from(byte);
            for _ in 0..8 {
                crc = (crc >> 1) ^ (0xEDB8_8320 & 0u32.wrapping_sub(crc & 1));
            }
        }
        !crc
    }
    assert_eq!(
        crc32(b"123456789"),
        0xCBF4_3926,
        "the published check value"
    );

    let db = SignatureDb::global();
    let query = db
        .tcp_probe_payloads(5666)
        .iter()
        .find(|payload| payload.starts_with(b"\x00\x02"))
        .expect("port 5666 has an NRPE probe");

    assert_eq!(query.len(), 1036, "the whole packet");
    assert_eq!(&query[2..4], b"\x00\x01", "a query");
    assert!(
        query[10..].starts_with(b"_NRPE_CHECK\0"),
        "the version check"
    );

    let mut zeroed = query.clone();
    zeroed[4..8].fill(0);
    assert_eq!(
        u32::from_be_bytes(query[4..8].try_into().expect("four bytes")),
        crc32(&zeroed),
        "the CRC-32 over the packet with its own field zeroed"
    );
}

/// Tor is named by what only Tor says, and a SOCKS5 proxy on Tor's port by what
/// every SOCKS5 proxy says.
///
/// The greeting's answer, version 5 and no authentication, is RFC 1928's for
/// any proxy that asks for none, so a rule reading Tor into it named every
/// such proxy Tor. Tor's own mark is the 501 its SOCKS port sends a web
/// request.
#[test]
fn tor_is_named_by_its_own_answer_and_not_by_a_socks5_greeting() {
    use crate::model::port::Protocol::Tcp;

    let greeting = named(9050, Tcp, "\u{5}\u{0}");
    assert_eq!(greeting.service.as_deref(), Some("socks5"));

    let web = "HTTP/1.0 501 Tor is not an HTTP Proxy\r\nContent-Type: text/html\r\n\r\n";
    for port in [9050, 9150] {
        let verdict = named(port, Tcp, web);
        assert_eq!(verdict.service.as_deref(), Some("tor"), "on {port}");
        assert_eq!(verdict.product.as_deref(), Some("tor_socks"), "on {port}");
    }
}