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
// 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 the model's enums are called in a file
//!
//! One name and one parser for each, defined together so that they cannot drift
//! apart. [`export::schema`](crate::export::schema) writes through the names
//! here and [`journal`](crate::journal) reads through the parsers, which is why
//! neither of them defines its own.
//!
//! A name is a promise. It appears in exported reports and in journals on disk,
//! so changing one is a breaking change to both. A new variant needs its name and
//! its parse case here, and `every_name_parses_back` fails until it has both.
//!
//! ## An unknown name is never guessed at here
//!
//! Every parser returns [`None`] for a name this build does not know. What that
//! becomes is the caller's, and the callers do not all answer alike.
//! [`record`](crate::record) reads downward, to the value that claims least of
//! the ones its type has, and says so at each field. [`reference()`] drops a
//! malformed reference and keeps the finding it belonged to.
//!
//! What none of them do is substitute a neighbour. A port state read as `Open`
//! because the file said something newer would be a scan reporting a listener
//! that is not there, so the reading is chosen in the one direction where a
//! stale build's mistake is always to claim too little.
//!
//! ## Strategy-supplied names are prefixed
//!
//! [`StatusProtocol::Custom`] and [`ScanResponse::Custom`] carry a name their
//! author chose, rendered with a `custom:` prefix so it cannot be mistaken for
//! one this engine defines. Without it, something calling itself `arp` would be
//! indistinguishable from a real ARP finding.

use std::borrow::Cow;

use crate::model::confidence::Confidence;
use crate::model::finding::{DetectionClass, Reference, Severity};
use crate::model::host::OsSource;
use crate::model::host::{Filtering, HostStatus, IpProtocolState, NetworkRole, StatusProtocol};
use crate::model::port::discovery::ScanResponse;
use crate::model::port::{PortSet, PortState, Protocol};
use crate::protocols::tcp;
use crate::report::ScannerKind;
use crate::report::{AttachmentSource, LivenessSkip, PortScope, ScanKind, StopReason};

/// The prefix that marks a name a strategy supplied rather than one this engine
/// defines.
const CUSTOM: &str = "custom:";

/// A host's reachability.
pub fn host_status_name(status: HostStatus) -> &'static str {
    match status {
        HostStatus::Unknown => "unknown",
        HostStatus::Down => "down",
        HostStatus::Filtered => "filtered",
        HostStatus::Up => "up",
    }
}

/// [`host_status_name`] read back.
pub fn host_status(name: &str) -> Option<HostStatus> {
    Some(match name {
        "unknown" => HostStatus::Unknown,
        "down" => HostStatus::Down,
        "filtered" => HostStatus::Filtered,
        "up" => HostStatus::Up,
        _ => return None,
    })
}

/// What a scan established about a port.
pub fn port_state_name(state: PortState) -> &'static str {
    match state {
        PortState::Unasked => "unasked",
        PortState::ClosedFiltered => "closed_filtered",
        PortState::Filtered => "filtered",
        PortState::Unfiltered => "unfiltered",
        PortState::Closed => "closed",
        PortState::OpenFiltered => "open_filtered",
        PortState::Open => "open",
    }
}

/// [`port_state_name`] read back.
pub fn port_state(name: &str) -> Option<PortState> {
    Some(match name {
        "unasked" => PortState::Unasked,
        "closed_filtered" => PortState::ClosedFiltered,
        "filtered" => PortState::Filtered,
        "unfiltered" => PortState::Unfiltered,
        "closed" => PortState::Closed,
        "open_filtered" => PortState::OpenFiltered,
        "open" => PortState::Open,
        _ => return None,
    })
}

/// What a scan established about a host accepting one IP protocol.
pub fn ip_protocol_state_name(state: IpProtocolState) -> &'static str {
    match state {
        IpProtocolState::Unasked => "unasked",
        IpProtocolState::OpenFiltered => "open_filtered",
        IpProtocolState::Filtered => "filtered",
        IpProtocolState::Closed => "closed",
        IpProtocolState::Open => "open",
    }
}

/// [`ip_protocol_state_name`] read back.
pub fn ip_protocol_state(name: &str) -> Option<IpProtocolState> {
    Some(match name {
        "unasked" => IpProtocolState::Unasked,
        "open_filtered" => IpProtocolState::OpenFiltered,
        "filtered" => IpProtocolState::Filtered,
        "closed" => IpProtocolState::Closed,
        "open" => IpProtocolState::Open,
        _ => return None,
    })
}

/// A transport.
pub fn protocol_name(protocol: Protocol) -> &'static str {
    match protocol {
        Protocol::Tcp => "tcp",
        Protocol::Udp => "udp",
        Protocol::Sctp => "sctp",
    }
}

/// [`protocol_name`] read back.
pub fn protocol(name: &str) -> Option<Protocol> {
    Some(match name {
        "tcp" => Protocol::Tcp,
        "udp" => Protocol::Udp,
        "sctp" => Protocol::Sctp,
        _ => return None,
    })
}

/// A role the scan concluded about a host.
pub fn network_role_name(role: NetworkRole) -> &'static str {
    match role {
        NetworkRole::Router => "router",
        NetworkRole::DnsServer => "dns",
        NetworkRole::DhcpServer => "dhcp",
        NetworkRole::NtpServer => "ntp",
        NetworkRole::SnmpAgent => "snmp",
        NetworkRole::DomainController => "domain-controller",
        NetworkRole::Switch => "switch",
        NetworkRole::Origin => "origin",
        NetworkRole::Tarpit => "tarpit",
        NetworkRole::Truncated => "truncated",
    }
}

/// [`network_role_name`] read back.
pub fn network_role(name: &str) -> Option<NetworkRole> {
    Some(match name {
        "router" => NetworkRole::Router,
        "dns" => NetworkRole::DnsServer,
        "dhcp" => NetworkRole::DhcpServer,
        "ntp" => NetworkRole::NtpServer,
        "snmp" => NetworkRole::SnmpAgent,
        "domain-controller" => NetworkRole::DomainController,
        "switch" => NetworkRole::Switch,
        "origin" => NetworkRole::Origin,
        "tarpit" => NetworkRole::Tarpit,
        "truncated" => NetworkRole::Truncated,
        _ => return None,
    })
}

/// A filtering conclusion the scan drew about the path to a host.
pub fn filtering_name(filtering: Filtering) -> &'static str {
    match filtering {
        Filtering::InlineMiddlebox => "inline_middlebox",
        Filtering::StatefulFilter => "stateful_filter",
        Filtering::PortTrustingAcl => "port_trusting_acl",
        Filtering::StatelessFilter => "stateless_filter",
    }
}

/// [`filtering_name`] read back.
pub fn filtering(name: &str) -> Option<Filtering> {
    Some(match name {
        "inline_middlebox" => Filtering::InlineMiddlebox,
        "stateful_filter" => Filtering::StatefulFilter,
        "port_trusting_acl" => Filtering::PortTrustingAcl,
        "stateless_filter" => Filtering::StatelessFilter,
        _ => return None,
    })
}

/// How bad a finding is, on the wire.
pub fn severity_name(severity: Severity) -> &'static str {
    match severity {
        Severity::Info => "info",
        Severity::Low => "low",
        Severity::Medium => "medium",
        Severity::High => "high",
        Severity::Critical => "critical",
    }
}

/// [`severity_name`] read back.
pub fn severity(name: &str) -> Option<Severity> {
    Some(match name {
        "info" => Severity::Info,
        "low" => Severity::Low,
        "medium" => Severity::Medium,
        "high" => Severity::High,
        "critical" => Severity::Critical,
        _ => return None,
    })
}

/// The intrusiveness a detection ran under, on the wire.
pub fn detection_class_name(class: DetectionClass) -> &'static str {
    match class {
        DetectionClass::Passive => "passive",
        DetectionClass::ActiveBenign => "active_benign",
        DetectionClass::ActiveMutating => "active_mutating",
        DetectionClass::Exploit => "exploit",
        DetectionClass::Dos => "dos",
    }
}

/// The name a whole envelope's ceiling is written under, `off` where it grants
/// nothing.
///
/// Beside [`detection_class_name`] rather than folded into it: a finding always
/// carries the class it ran under, and only a scan's settings can say that no
/// class was permitted at all.
pub fn detection_ceiling_name(ceiling: Option<DetectionClass>) -> &'static str {
    match ceiling {
        Some(class) => detection_class_name(class),
        None => "off",
    }
}

/// [`detection_class_name`] read back.
pub fn detection_class(name: &str) -> Option<DetectionClass> {
    Some(match name {
        "passive" => DetectionClass::Passive,
        "active_benign" => DetectionClass::ActiveBenign,
        "active_mutating" => DetectionClass::ActiveMutating,
        "exploit" => DetectionClass::Exploit,
        "dos" => DetectionClass::Dos,
        _ => return None,
    })
}

/// How sure a finding, or a service identification, is on the wire.
///
/// The first wire form [`Confidence`] has. Nothing serialized it until a finding
/// did, so its names are defined here beside every other model enum's rather
/// than
/// in the fingerprinting module that owns the type.
pub fn confidence_name(confidence: Confidence) -> &'static str {
    match confidence {
        Confidence::Heuristic => "heuristic",
        Confidence::Weak => "weak",
        Confidence::Probable => "probable",
        Confidence::Strong => "strong",
        Confidence::Certain => "certain",
    }
}

/// [`confidence_name`] read back.
pub fn confidence(name: &str) -> Option<Confidence> {
    Some(match name {
        "heuristic" => Confidence::Heuristic,
        "weak" => Confidence::Weak,
        "probable" => Confidence::Probable,
        "strong" => Confidence::Strong,
        "certain" => Confidence::Certain,
        _ => return None,
    })
}

/// Which kind of [`Reference`] this is, on the wire.
///
/// The kind travels beside a value the record carries separately, so its read-back
/// is [`reference()`], which takes both halves. It is the one parser here needing
/// the value alongside the name, since a reference is an enum with a
/// payload rather than a bare one.
pub fn reference_kind_name(reference: &Reference) -> &'static str {
    match reference {
        Reference::Cve(_) => "cve",
        Reference::Cwe(_) => "cwe",
        Reference::Url(_) => "url",
    }
}

/// A [`Reference`] rebuilt from its wire `kind` and `value`.
///
/// Returns [`None`] for an unknown kind, a CWE number that is not a number, or a
/// CVE identifier of the wrong shape. A malformed reference is dropped rather
/// than guessed at, the same discipline every parser here follows.
pub fn reference(kind: &str, value: &str) -> Option<Reference> {
    Some(match kind {
        "cve" => Reference::cve(value)?,
        "cwe" => Reference::cwe(value.parse().ok()?),
        "url" => Reference::url(value),
        _ => return None,
    })
}

/// The TCP flags set in `byte`, named and joined with `|`, so an arbitrary
/// evasion flag combination reads back in a report as `fin|psh|urg` rather than a
/// bare number. Ordered from the high header bit down, with the empty combination
/// of a flagless probe rendering as the empty string.
pub fn tcp_flags_name(byte: u8) -> String {
    [
        (tcp::flags::URG, "urg"),
        (tcp::flags::ACK, "ack"),
        (tcp::flags::PSH, "psh"),
        (tcp::flags::RST, "rst"),
        (tcp::flags::SYN, "syn"),
        (tcp::flags::FIN, "fin"),
    ]
    .into_iter()
    .filter(|(bit, _)| byte & bit != 0)
    .map(|(_, name)| name)
    .collect::<Vec<_>>()
    .join("|")
}

/// [`tcp_flags_name`] read back. A name this version does not know contributes
/// nothing, so a record written by a newer engine reads back as the flags this
/// one understands rather than failing.
///
/// That leniency is right for a journal, which this process wrote, and wrong for
/// a document somebody else did. A reader that wants the unknown name reported
/// rather than dropped uses [`tcp_flags_checked`].
pub fn tcp_flags(name: &str) -> u8 {
    tcp_flags_fold(name).0
}

/// [`tcp_flags`], refusing a name it does not know instead of skipping it.
///
/// The evasion settings in an exported report reach the record layer as strings,
/// and `tcp_flags` reading `"nonsense"` as no flags at all made a document
/// claiming something this build cannot express read back as a document claiming
/// nothing. `"syn|nonsense"` was worse: it read back as `syn`, which is a claim
/// the document did not make.
///
/// [`import::report::json`](crate::import::report::json) checks with this so an
/// unrecognised flag name is refused by name, the way every other named value in
/// that document already is.
pub fn tcp_flags_checked(name: &str) -> Option<u8> {
    match tcp_flags_fold(name) {
        (mask, true) => Some(mask),
        (_, false) => None,
    }
}

/// The mask, and whether every name in `name` was one this build knows.
fn tcp_flags_fold(name: &str) -> (u8, bool) {
    name.split('|')
        .fold((0, true), |(mask, known), part| match part.trim() {
            "fin" => (mask | tcp::flags::FIN, known),
            "syn" => (mask | tcp::flags::SYN, known),
            "rst" => (mask | tcp::flags::RST, known),
            "psh" => (mask | tcp::flags::PSH, known),
            "ack" => (mask | tcp::flags::ACK, known),
            "urg" => (mask | tcp::flags::URG, known),
            _ => (mask, false),
        })
}

/// The protocol behind a host's status.
pub fn status_protocol_name(protocol: &StatusProtocol) -> Cow<'_, str> {
    match protocol {
        StatusProtocol::Arp => Cow::Borrowed("arp"),
        StatusProtocol::Ndp => Cow::Borrowed("ndp"),
        StatusProtocol::IcmpEcho => Cow::Borrowed("icmp_echo"),
        StatusProtocol::IcmpTimestamp => Cow::Borrowed("icmp_timestamp"),
        StatusProtocol::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
        StatusProtocol::TcpSyn => Cow::Borrowed("tcp_syn"),
        StatusProtocol::Tcp => Cow::Borrowed("tcp"),
        StatusProtocol::Dhcp => Cow::Borrowed("dhcp"),
        StatusProtocol::Udp => Cow::Borrowed("udp"),
        StatusProtocol::Sctp => Cow::Borrowed("sctp"),
        StatusProtocol::Custom(name) => Cow::Owned(format!("{CUSTOM}{name}")),
    }
}

/// [`status_protocol_name`] read back.
///
/// An empty custom name is refused: it renders as the bare prefix and would read
/// back as a finding attributed to nothing.
pub fn status_protocol(name: &str) -> Option<StatusProtocol> {
    if let Some(custom) = name.strip_prefix(CUSTOM) {
        return (!custom.is_empty()).then(|| StatusProtocol::Custom(custom.into()));
    }

    Some(match name {
        "icmp_timestamp" => StatusProtocol::IcmpTimestamp,
        "arp" => StatusProtocol::Arp,
        "ndp" => StatusProtocol::Ndp,
        "icmp_echo" => StatusProtocol::IcmpEcho,
        "icmp_unreachable" => StatusProtocol::IcmpUnreachable,
        "tcp_syn" => StatusProtocol::TcpSyn,
        "tcp" => StatusProtocol::Tcp,
        "dhcp" => StatusProtocol::Dhcp,
        "udp" => StatusProtocol::Udp,
        "sctp" => StatusProtocol::Sctp,
        _ => return None,
    })
}

/// The packet that settled a port's state.
pub fn scan_response_name(response: &ScanResponse) -> Cow<'_, str> {
    match response {
        ScanResponse::TcpSynAck => Cow::Borrowed("tcp_syn_ack"),
        ScanResponse::OverheardSynAck => Cow::Borrowed("overheard_syn_ack"),
        ScanResponse::TcpRst => Cow::Borrowed("tcp_rst"),
        ScanResponse::ConnectionRefused => Cow::Borrowed("connection_refused"),
        ScanResponse::UdpResponse => Cow::Borrowed("udp_response"),
        ScanResponse::SctpInitAck => Cow::Borrowed("sctp_init_ack"),
        ScanResponse::SctpAbort => Cow::Borrowed("sctp_abort"),
        ScanResponse::NoResponse => Cow::Borrowed("no_response"),
        ScanResponse::IcmpUnreachable => Cow::Borrowed("icmp_unreachable"),
        ScanResponse::IcmpProhibited => Cow::Borrowed("icmp_prohibited"),
        ScanResponse::Custom(name) => Cow::Owned(format!("{CUSTOM}{name}")),
    }
}

/// [`scan_response_name`] read back. Empty custom names are refused, as in
/// [`status_protocol`].
pub fn scan_response(name: &str) -> Option<ScanResponse> {
    if let Some(custom) = name.strip_prefix(CUSTOM) {
        return (!custom.is_empty()).then(|| ScanResponse::Custom(custom.to_string()));
    }

    Some(match name {
        "tcp_syn_ack" => ScanResponse::TcpSynAck,
        "overheard_syn_ack" => ScanResponse::OverheardSynAck,
        "tcp_rst" => ScanResponse::TcpRst,
        "connection_refused" => ScanResponse::ConnectionRefused,
        "udp_response" => ScanResponse::UdpResponse,
        "sctp_init_ack" => ScanResponse::SctpInitAck,
        "sctp_abort" => ScanResponse::SctpAbort,
        "no_response" => ScanResponse::NoResponse,
        "icmp_unreachable" => ScanResponse::IcmpUnreachable,
        "icmp_prohibited" => ScanResponse::IcmpProhibited,
        _ => return None,
    })
}

/// Where a conclusion about an operating system came from.
pub fn os_source_name(source: OsSource) -> &'static str {
    match source {
        OsSource::TcpStack => "tcp_stack",
        OsSource::HardwareVendor => "hardware_vendor",
        OsSource::ServiceBanner => "service_banner",
        OsSource::SnmpAgent => "snmp_agent",
        OsSource::MdnsResponder => "mdns_responder",
        OsSource::Hostname => "hostname",
    }
}

/// [`os_source_name`] read back.
pub fn os_source(name: &str) -> Option<OsSource> {
    Some(match name {
        "tcp_stack" => OsSource::TcpStack,
        "hardware_vendor" => OsSource::HardwareVendor,
        "service_banner" => OsSource::ServiceBanner,
        "snmp_agent" => OsSource::SnmpAgent,
        "mdns_responder" => OsSource::MdnsResponder,
        "hostname" => OsSource::Hostname,
        _ => return None,
    })
}

/// Which protocol an attachment was read from.
pub fn attachment_source_name(source: AttachmentSource) -> &'static str {
    match source {
        AttachmentSource::Lldp => "lldp",
        AttachmentSource::Cdp => "cdp",
    }
}

/// The [`AttachmentSource`] a wire name spells, or `None` for one this build
/// does not know.
pub fn attachment_source(name: &str) -> Option<AttachmentSource> {
    Some(match name {
        "lldp" => AttachmentSource::Lldp,
        "cdp" => AttachmentSource::Cdp,
        _ => return None,
    })
}

/// The wire name for a scan kind.
pub fn scan_kind_name(kind: ScanKind) -> &'static str {
    match kind {
        ScanKind::Discovery => "discovery",
        ScanKind::PortScan => "port_scan",
        ScanKind::Listen => "listen",
    }
}

/// [`scan_kind_name`] read back.
pub fn scan_kind(name: &str) -> Option<ScanKind> {
    Some(match name {
        "discovery" => ScanKind::Discovery,
        "port_scan" => ScanKind::PortScan,
        "listen" => ScanKind::Listen,
        _ => return None,
    })
}

/// The wire name for why a port phase ran with no liveness pass.
pub fn liveness_skip_name(skip: LivenessSkip) -> &'static str {
    match skip {
        LivenessSkip::AssumeUp => "assume_up",
        LivenessSkip::IdleScan => "idle_scan",
        LivenessSkip::PortsNoDearer => "ports_no_dearer",
    }
}

/// [`liveness_skip_name`] read back.
pub fn liveness_skip(name: &str) -> Option<LivenessSkip> {
    Some(match name {
        "assume_up" => LivenessSkip::AssumeUp,
        "idle_scan" => LivenessSkip::IdleScan,
        "ports_no_dearer" => LivenessSkip::PortsNoDearer,
        _ => return None,
    })
}

/// Which strategy something is attributed to.
pub fn scanner_kind_name(kind: ScannerKind) -> &'static str {
    match kind {
        ScannerKind::Local => "local",
        ScannerKind::Passive => "passive",
        ScannerKind::Routed => "routed",
        ScannerKind::RoutedSctp => "routed_sctp",
        ScannerKind::SynPort => "syn_port",
        ScannerKind::TcpPort => "tcp_port",
        ScannerKind::Connect => "connect",
        ScannerKind::ConnectUdp => "connect_udp",
        ScannerKind::UdpPort => "udp_port",
        ScannerKind::SctpPort => "sctp_port",
        ScannerKind::OsEcho => "os_echo",
        ScannerKind::OsSeries => "os_series",
        ScannerKind::OsSnmp => "os_snmp",
        ScannerKind::Idle => "idle",
        ScannerKind::Composite => "composite",
        ScannerKind::Service => "service",
        ScannerKind::Detection => "detection",
        ScannerKind::Journal => "journal",
    }
}

/// [`scanner_kind_name`] read back.
pub fn scanner_kind(name: &str) -> Option<ScannerKind> {
    Some(match name {
        "local" => ScannerKind::Local,
        "passive" => ScannerKind::Passive,
        "routed" => ScannerKind::Routed,
        "routed_sctp" => ScannerKind::RoutedSctp,
        "syn_port" => ScannerKind::SynPort,
        "tcp_port" => ScannerKind::TcpPort,
        "connect" => ScannerKind::Connect,
        "connect_udp" => ScannerKind::ConnectUdp,
        "udp_port" => ScannerKind::UdpPort,
        "sctp_port" => ScannerKind::SctpPort,
        "os_echo" => ScannerKind::OsEcho,
        "os_series" => ScannerKind::OsSeries,
        "os_snmp" => ScannerKind::OsSnmp,
        "idle" => ScannerKind::Idle,
        "composite" => ScannerKind::Composite,
        "service" => ScannerKind::Service,
        "detection" => ScannerKind::Detection,
        "journal" => ScannerKind::Journal,
        _ => return None,
    })
}

/// Why a receive loop stopped.
pub fn stop_reason_name(reason: StopReason) -> &'static str {
    match reason {
        StopReason::Aborted => "aborted",
        StopReason::AllResponded => "all_responded",
        StopReason::AttemptsSpent => "attempts_spent",
        StopReason::DeadlineExpired => "deadline_expired",
        StopReason::TimedOut => "timed_out",
        StopReason::StreamClosed => "stream_closed",
    }
}

/// [`stop_reason_name`] read back.
pub fn stop_reason(name: &str) -> Option<StopReason> {
    Some(match name {
        "aborted" => StopReason::Aborted,
        "all_responded" => StopReason::AllResponded,
        "attempts_spent" => StopReason::AttemptsSpent,
        "deadline_expired" => StopReason::DeadlineExpired,
        "timed_out" => StopReason::TimedOut,
        "stream_closed" => StopReason::StreamClosed,
        _ => return None,
    })
}

/// The wire name of a phase's port scope.
///
/// The set itself travels separately, as a port specification; this names which
/// of the four things that set *is*. A scope with no set has a name here all the
/// same, because "the phase walked no ports" and "the record does not say" are
/// the two that must never be read as each other.
pub fn port_scope_name(scope: &PortScope) -> &'static str {
    match scope {
        PortScope::Unstated => "unstated",
        PortScope::NoPorts => "none",
        PortScope::Every(_) => "every",
        PortScope::Mixed(_) => "mixed",
    }
}

/// [`port_scope_name`] read back, given the set that travelled with it.
///
/// A name this build does not know reads as `None`, which a caller turns into
/// [`PortScope::Unstated`], the reading that claims nothing.
pub fn port_scope(name: &str, ports: Option<PortSet>) -> Option<PortScope> {
    Some(match (name, ports) {
        ("unstated", _) => PortScope::Unstated,
        ("none", _) => PortScope::NoPorts,
        ("every", Some(ports)) => PortScope::Every(ports),
        ("mixed", Some(ports)) => PortScope::Mixed(ports),
        // A set is what makes those two mean anything, so a name that needs one
        // and did not travel with one says nothing.
        ("every" | "mixed", None) => PortScope::Unstated,
        _ => return None,
    })
}

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

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

    /// One value of every variant of `$enum`, as the arms of one exhaustive
    /// match.
    ///
    /// The list and the match are built from the same rows, so a variant added
    /// to the enum without a row stops the build, and a row written twice is an
    /// unreachable arm, which the lints refuse. A list kept beside a match holds
    /// neither: the match forces an arm for a new variant, nothing forces the
    /// list to name it, and the variant is written to files and never read back.
    /// A variant carrying a value is given one, and matched whatever it carries.
    macro_rules! every {
        ($enum:ident { $($variant:ident $(($($carried:expr),+))?),+ $(,)? }) => {{
            let rows = vec![$($enum::$variant $(($($carried),+))?),+];
            for row in &rows {
                match row {
                    $($enum::$variant { .. } => {})+
                }
            }
            rows
        }};
    }

    /// Every variant survives being written down and read back.
    ///
    /// What it catches is a name and a parser that disagree. What it does not
    /// catch is a variant with no name at all: the match arms above are
    /// exhaustive, so the compiler refuses that before this runs.
    ///
    /// Driven from each vocabulary's `ALL` rather than from lists written out
    /// here, where there is one. A list written here is a second hand-maintained
    /// list with one reader, where `ALL` is the same list with five: the
    /// exported schema's enums, a report's ordering, a `FromStr`'s error
    /// message, and this. A vocabulary missing from `ALL` goes untested here
    /// either way, and being missing from `ALL` is the more visible mistake of
    /// the two. A vocabulary with no `ALL`, or with variants an `ALL` cannot
    /// hold because they carry a value, is listed by `every!`, which the
    /// compiler holds to the enum.
    #[test]
    fn every_name_parses_back() {
        for value in HostStatus::ALL {
            assert_eq!(host_status(host_status_name(value)), Some(value));
        }

        for value in PortState::ALL {
            assert_eq!(port_state(port_state_name(value)), Some(value));
        }

        for value in ScanKind::ALL {
            assert_eq!(scan_kind(scan_kind_name(value)), Some(value));
        }

        for value in LivenessSkip::ALL {
            assert_eq!(liveness_skip(liveness_skip_name(value)), Some(value));
        }

        for value in IpProtocolState::ALL {
            assert_eq!(
                ip_protocol_state(ip_protocol_state_name(value)),
                Some(value)
            );
        }

        for value in Filtering::ALL {
            assert_eq!(filtering(filtering_name(value)), Some(value));
        }

        for value in AttachmentSource::ALL {
            assert_eq!(
                attachment_source(attachment_source_name(value)),
                Some(value)
            );
        }

        for value in ScannerKind::ALL {
            assert_eq!(scanner_kind(scanner_kind_name(value)), Some(value));
        }

        for value in StopReason::ALL {
            assert_eq!(stop_reason(stop_reason_name(value)), Some(value));
        }

        for value in Protocol::ALL {
            assert_eq!(protocol(protocol_name(value)), Some(value));
        }

        for value in NetworkRole::ALL {
            assert_eq!(network_role(network_role_name(value)), Some(value));
        }

        for value in Severity::ALL {
            assert_eq!(severity(severity_name(value)), Some(value));
        }

        for value in DetectionClass::ALL {
            assert_eq!(detection_class(detection_class_name(value)), Some(value));
        }

        for value in Confidence::ALL {
            assert_eq!(confidence(confidence_name(value)), Some(value));
        }

        // A reference carries a value beside its kind, so its round trip is over
        // both halves rather than a bare name.
        for value in every!(Reference {
            Cve("CVE-2021-44228".to_string()),
            Cwe(79),
            Url("https://example.test/advisory".to_string()),
        }) {
            let kind = reference_kind_name(&value);
            let carried = match &value {
                Reference::Cve(s) | Reference::Url(s) => s.clone(),
                Reference::Cwe(n) => n.to_string(),
            };
            assert_eq!(reference(kind, &carried), Some(value));
        }

        for value in every!(OsSource {
            TcpStack,
            HardwareVendor,
            ServiceBanner,
            SnmpAgent,
            MdnsResponder,
            Hostname,
        }) {
            assert_eq!(os_source(os_source_name(value)), Some(value));
        }

        // `ALL` and then the variant it cannot hold, which carries a name a
        // strategy chose rather than one this enum knows.
        for value in StatusProtocol::ALL
            .iter()
            .cloned()
            .chain([StatusProtocol::Custom("a-strategy".into())])
        {
            let name = status_protocol_name(&value);
            assert_eq!(status_protocol(&name), Some(value.clone()), "{name}");
        }

        for value in every!(ScanResponse {
            TcpSynAck,
            OverheardSynAck,
            TcpRst,
            ConnectionRefused,
            UdpResponse,
            SctpInitAck,
            SctpAbort,
            NoResponse,
            IcmpUnreachable,
            IcmpProhibited,
            Custom("a-strategy".to_string()),
        }) {
            let name = scan_response_name(&value);
            assert_eq!(scan_response(&name), Some(value.clone()), "{name}");
        }
    }

    /// Every built-in protocol is spelled in all three places at once: the
    /// writer, the reader, and the report schema.
    ///
    /// The first two are exhaustive matches, so the compiler already refuses a
    /// variant that has no name. The schema is a JSON file the compiler cannot
    /// see, which is the gap that lets a finding survive a scan and disappear on
    /// the way to the report.
    ///
    /// The protocols are listed by `every!` for that reason: a variant added to
    /// [`StatusProtocol`] stops this test compiling until somebody has decided
    /// what the document calls it, and then it is checked against the schema
    /// and held to be in `ALL`.
    #[test]
    fn every_built_in_protocol_is_named_everywhere() {
        const SCHEMA: &str = include_str!("../../assets/schema/zond-report-v1.schema.json");

        // Scoped to the one `enum` block that holds these names, because the
        // document spells some of them twice: `dhcp` is a protocol here and a
        // network role four hundred lines up, and a search of the whole file
        // finds the wrong one and passes. Anchored on the description, which
        // occurs exactly once, and running to the first `]`, which closes the
        // enum.
        let described = SCHEMA
            .find("The protocol event that produced the evidence")
            .expect("the schema describes the evidence protocol");
        let names = &SCHEMA[described..];
        let names = &names[..names.find(']').expect("the enum closes")];

        // The scoping is the part that can silently stop working, so it is
        // asserted rather than assumed: a role name has no business in here.
        assert!(
            !names.contains("\"router\""),
            "the search caught the network-role enum instead"
        );

        let built_in: Vec<StatusProtocol> = every!(StatusProtocol {
            Arp,
            Ndp,
            IcmpEcho,
            IcmpTimestamp,
            IcmpUnreachable,
            TcpSyn,
            Tcp,
            Dhcp,
            Udp,
            Sctp,
            Custom("a-strategy".into()),
        })
        .into_iter()
        .filter(|protocol| !matches!(protocol, StatusProtocol::Custom(_)))
        .collect();

        // `ALL` is held to the same rows, since the schema's enum and every other
        // reader of `ALL` count on it naming each built-in protocol.
        assert_eq!(built_in.len(), StatusProtocol::ALL.len());

        for protocol in &built_in {
            assert!(
                StatusProtocol::ALL.contains(protocol),
                "`ALL` leaves out {protocol:?}"
            );

            let name = status_protocol_name(protocol);
            assert_eq!(status_protocol(&name), Some(protocol.clone()));
            assert!(
                names.contains(&format!("\"{name}\"")),
                "the report schema does not name '{name}'"
            );
        }
    }

    /// A port scope travels as a name and a set, and reading one back has a rule
    /// of its own, so it has a test of its own.
    ///
    /// [`PortScope`] has no `ALL`, because two of its four carry a set. The
    /// writer is an exhaustive match and breaks when a variant is added; the
    /// reader is a string match with a fallback and does not, so the rows are
    /// listed by `every!`, and a variant added without one stops the build here.
    #[test]
    fn every_port_scope_parses_back() {
        let ports = || PortSet::try_from("80,443").expect("a port set");

        for scope in every!(PortScope {
            Unstated,
            NoPorts,
            Every(ports()),
            Mixed(ports()),
        }) {
            let name = port_scope_name(&scope);
            assert_eq!(
                port_scope(name, scope.ports().cloned()),
                Some(scope.clone()),
                "{name}"
            );
        }

        // A kind that needs a set and did not travel with one says nothing,
        // rather than claiming the phase walked no ports.
        assert_eq!(port_scope("every", None), Some(PortScope::Unstated));
        assert_eq!(port_scope("mixed", None), Some(PortScope::Unstated));
        assert_eq!(port_scope("thorough", Some(ports())), None);
    }

    /// A name this build does not know is refused rather than falling into a
    /// neighbouring variant.
    #[test]
    fn an_unknown_name_is_refused() {
        assert_eq!(host_status("perhaps"), None);
        assert_eq!(port_state("ajar"), None);
        assert_eq!(protocol("dccp"), None);
        assert_eq!(network_role("gateway"), None);
        assert_eq!(os_source("astrology"), None);
        assert_eq!(status_protocol("igmp"), None);
        assert_eq!(scan_response("tcp_fin_ack"), None);
        assert_eq!(scan_kind("enrichment"), None);
        assert_eq!(scanner_kind("telepathy"), None);
        assert_eq!(stop_reason("bored"), None);
        assert_eq!(severity("catastrophic"), None);
        assert_eq!(detection_class("nosy"), None);
        assert_eq!(confidence("absolute"), None);
        assert_eq!(reference("mystery", "x"), None);
    }

    /// A custom name that is empty renders as the bare prefix and names nothing.
    #[test]
    fn an_empty_custom_name_is_refused() {
        assert_eq!(status_protocol(CUSTOM), None);
        assert_eq!(scan_response(CUSTOM), None);
    }
}