zond-engine 0.16.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
// 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

//! # TCP Scan Techniques
//!
//! Which segment a TCP port probe carries, and what an answer to it proves.
//!
//! A port scan asks a target one question, and the flags on the probe decide
//! which question that is. A SYN asks "will you accept a connection here?" and
//! is answered positively; the five techniques that do not send one ask "is
//! there anyone behind this port at all?" and are answered *negatively*, by the
//! RST that only a closed port is obliged to send. That inversion is the point
//! of them: a filter that blocks connection attempts often passes a segment
//! that is not one, so the probe reaches a stack that a SYN never would. The
//! seventh, [`Window`](TcpScanTechnique::Window), reads that same refusal for
//! the one field in it that answers positively.
//!
//! The mapping from reply to verdict lives here rather than in the scanner
//! because it is the whole of what distinguishes the techniques. Everything
//! else - retransmission, pacing, source selection, the deadline - is identical
//! across all seven, and the scanner is written once against this table. The
//! flags themselves live in [`crate::protocols::tcp`], which is the layer that
//! knows what a TCP header is.
//!
//! ## What each technique rests on
//!
//! RFC 793 §3.4 requires a port with nothing behind it to answer any segment
//! that does not carry RST with a RST, and requires a port in LISTEN to ignore
//! a segment carrying neither SYN, ACK nor RST. Silence is therefore weak
//! evidence of a listener and a RST is strong evidence of none - which is why
//! [`PortState::OpenFiltered`] is the honest verdict for silence here, and
//! [`PortState::Filtered`] is not.
//!
//! Not every stack obeys. Windows, many Cisco devices, BSDI and IBM OS/400
//! answer every flag probe with a RST whatever the port state. Against those,
//! [`Fin`](TcpScanTechnique::Fin), [`Null`](TcpScanTechnique::Null),
//! [`Xmas`](TcpScanTechnique::Xmas) and [`Maimon`](TcpScanTechnique::Maimon)
//! report every port closed - not merely useless but confidently wrong. A run
//! that finds *no* open-filtered port at all has almost certainly met one, and
//! is worth repeating with [`Syn`](TcpScanTechnique::Syn).
//!
//! ## No technique here answers the whole question
//!
//! These are not seven ways of doing the same thing, and running one of them is
//! rarely enough. A flag probe cannot tell an open port from a filtered one -
//! both are silent, and both come back [`PortState::OpenFiltered`]. An
//! [`Ack`](TcpScanTechnique::Ack) scan tells those two apart and never says
//! which is open. Only [`Syn`](TcpScanTechnique::Syn) identifies a listener
//! from the reply alone. [`Window`](TcpScanTechnique::Window) sends the ACK
//! scan's segment and reads one field further, which separates open from closed
//! on the stacks that still leak the difference and says nothing on the ones
//! that do not.
//!
//! Measured against a router with one open, one filtered and three closed
//! ports, that plays out exactly: the FIN scan reports the open port and the
//! filtered port identically, and it takes the ACK scan beside it to separate
//! them. A caller offering these to a user is offering complementary
//! instruments, not alternatives.

use std::fmt;
use std::str::FromStr;

use crate::model::port::PortState;

/// The two segments a TCP port probe can draw back, as classified off the wire
/// by [`crate::protocols::tcp::classify_probe_response`].
///
/// What either one *means* depends entirely on the probe that provoked it, which
/// is [`TcpScanTechnique::verdict`]'s job. A RST is a closed port to a FIN probe
/// and an unfiltered path to an ACK probe; naming the segment rather than the
/// conclusion is what keeps the two from being confused.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TcpReply {
    /// SYN+ACK: a listener accepting the connection attempt. Only a SYN can
    /// draw one.
    SynAck,
    /// RST: a refusal. Which refusal depends on what was asked.
    Rst {
        /// The receive window the reset announced.
        ///
        /// A stack resetting a connection it never held has no window to
        /// announce, so whatever it writes here is a property of the code path
        /// it took rather than of the segment it answered. BSD derivatives
        /// leave the listening socket's own window on a reset from an open
        /// port and zero on one from a closed port, which is the single field
        /// [`TcpScanTechnique::Window`] reads. Every other technique ignores
        /// it.
        window: u16,
    },

    /// ACK alone: a *challenge ACK*, and the only reply here that is not an
    /// answer to the probe that drew it.
    ///
    /// A stack sends one when a SYN arrives for a connection it is already
    /// half-open on and the sequence number does not fit that connection's
    /// window (RFC 793 §3.9 requires an acknowledgement for an unacceptable
    /// segment; RFC 5961 §4 makes it mandatory for a SYN specifically, to close
    /// the blind-reset window). It carries `RCV.NXT`, which acknowledges the
    /// earlier attempt that opened the connection rather than the one that
    /// provoked this.
    ///
    /// Only a host holding a half-open connection sends one, and only a
    /// listener holds one. A closed port has no state to challenge from; it
    /// resets. So this is positive evidence of an open port, arriving by a
    /// different route than a handshake.
    ChallengeAck,
}

/// The two chunks an SCTP port probe can draw back, as classified off the wire
/// by [`crate::protocols::sctp::classify_probe_response`].
///
/// Beside [`TcpReply`] and for its reason: what either chunk *means* depends on
/// the probe that provoked it, which is [`SctpScanTechnique::verdict`]'s job. An
/// ABORT is a closed port to either technique; an INIT-ACK is an open port to an
/// INIT probe and cannot be an answer to a COOKIE-ECHO at all.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SctpReply {
    /// An INIT-ACK: an endpoint accepted the association attempt. The SCTP
    /// analogue of a SYN+ACK, and the only positive answer either technique can
    /// draw.
    InitAck,
    /// An ABORT: a reachable stack refusing outright. The SCTP analogue of a
    /// RST, and what both techniques read as a closed port.
    Abort,
}

/// How an SCTP port is probed.
///
/// Two chunks, and the difference between them is the difference between the
/// SYN scan and the FIN family one protocol over. An INIT is answered whichever
/// way the port stands, so it names open ports and reads silence as a filter. A
/// COOKIE-ECHO is answered only by a port with nothing behind it, so it cannot
/// name an open port at all and reads silence as open-or-filtered.
///
/// Both need raw sockets. There is no unprivileged form of either, since no
/// kernel builds an SCTP chunk on a caller's behalf the way it completes a TCP
/// handshake, so a process without them has its SCTP ports refused rather than
/// answered a different way.
///
/// Host discovery is not governed by this. A sweep asks whether an address is
/// there, and only an INIT draws an answer from an address whose port is open,
/// so the discovery probe is an INIT whatever a port scan was asked for.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SctpScanTechnique {
    /// An INIT chunk. The default, and the only technique that identifies an
    /// open SCTP port positively.
    ///
    /// RFC 4960 fixes both answers: a listener accepts with an INIT-ACK (§5.1)
    /// and a stack with nothing on that port refuses with an ABORT (§8.4), so
    /// every live endpoint says something and silence is a filter. Neither
    /// answer completes an association, so no port is left half-open.
    #[default]
    Init,
    /// A COOKIE-ECHO chunk carrying a cookie no endpoint minted.
    ///
    /// RFC 4960 §8.4 sends an out-of-the-blue COOKIE-ECHO down two different
    /// paths depending on whether anything is listening. A listener
    /// authenticates the cookie (§5.1.5), fails to, and discards the packet
    /// without a word. A port with no endpoint behind it has nothing to
    /// authenticate against and falls through to the rule that answers an
    /// unrecognised packet with an ABORT. So the ABORT is a closed port and
    /// silence is everything else.
    ///
    /// What it buys is passage. A filter written against SCTP scanning blocks
    /// the INIT chunk, because that is the chunk a scan is expected to send and
    /// the one that opens an association; a COOKIE-ECHO is neither, and rules
    /// written for the first often say nothing about the second. What it costs
    /// is the positive result: an open port and a filtered one are both silent
    /// here, and no amount of waiting separates them. Run it to find out whether
    /// a range that came back entirely filtered under an INIT scan is filtered
    /// or merely INIT-filtered.
    CookieEcho,
}

impl SctpScanTechnique {
    /// Every technique, in the order they are documented.
    ///
    /// Here for the reason [`TcpScanTechnique::ALL`] is: a front end offering
    /// the choice enumerates it from the engine rather than from a list of its
    /// own that drifts the first time one is added.
    pub const ALL: [Self; 2] = [Self::Init, Self::CookieEcho];

    /// The canonical name, which is also what [`FromStr`] accepts and
    /// [`fmt::Display`] renders.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Init => "init",
            Self::CookieEcho => "cookie-echo",
        }
    }

    /// One line describing what the technique is for, short enough to sit
    /// beside the name wherever a front end offers the choice.
    pub const fn summary(self) -> &'static str {
        match self {
            Self::Init => "association attempt; the only one that confirms a listener",
            Self::CookieEcho => "unminted cookie; a closed port answers, an open one stays silent",
        }
    }

    /// What the technique concludes from `reply`, or `None` if that chunk
    /// answers nothing this probe asked.
    ///
    /// The `None` case carries the same weight it does for TCP. Nothing a
    /// COOKIE-ECHO can send provokes an INIT-ACK, so one arriving at that scan
    /// is somebody else's association rather than an open port, and resolving a
    /// port on it would report a listener on the strength of a coincidence.
    pub const fn verdict(self, reply: SctpReply) -> Option<PortState> {
        match (self, reply) {
            (Self::Init, SctpReply::InitAck) => Some(PortState::Open),
            (Self::Init | Self::CookieEcho, SctpReply::Abort) => Some(PortState::Closed),
            (Self::CookieEcho, SctpReply::InitAck) => None,
        }
    }

    /// What the technique concludes when every attempt goes unanswered.
    ///
    /// The same split the TCP techniques make. An INIT that draws nothing was
    /// dropped, since a live stack answers one whichever way the port stands. A
    /// COOKIE-ECHO that draws nothing was either dropped or handed to a listener
    /// that discarded it in silence, and the probe cannot tell those apart.
    pub const fn silence_means(self) -> PortState {
        match self {
            Self::Init => PortState::Filtered,
            Self::CookieEcho => PortState::OpenFiltered,
        }
    }

    /// Whether this technique can report a port [`PortState::Open`].
    ///
    /// [`Init`](Self::Init) alone, from the INIT-ACK a listener sends. A
    /// COOKIE-ECHO scan's best answer is open-or-filtered, so anything that
    /// wants open SCTP ports has to ask for the other one.
    pub const fn finds_open_ports(self) -> bool {
        matches!(self, Self::Init)
    }

    /// How a port nothing answered for is described in an audit line.
    pub const fn silence_label(self) -> &'static str {
        match self {
            Self::Init => "filtered",
            Self::CookieEcho => "open-filtered",
        }
    }
}

impl fmt::Display for SctpScanTechnique {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// The error [`SctpScanTechnique::from_str`] returns, carrying the list of names
/// that would have worked.
///
/// Built the way [`UnknownTechnique`] is, and separate from it so a message
/// naming the alternatives names the ones for the right protocol.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unknown SCTP scan technique '{input}', expected one of: {}",
    Self::expected()
)]
pub struct UnknownSctpTechnique {
    /// What the caller wrote.
    pub input: String,
}

impl UnknownSctpTechnique {
    /// The accepted names, comma-separated, in the order they are documented.
    fn expected() -> String {
        SctpScanTechnique::ALL
            .iter()
            .map(|technique| technique.name())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl FromStr for SctpScanTechnique {
    type Err = UnknownSctpTechnique;

    /// Parses a technique name, ignoring case and surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::model::technique::SctpScanTechnique;
    ///
    /// assert_eq!("Cookie-Echo".parse(), Ok(SctpScanTechnique::CookieEcho));
    /// assert!("cookie".parse::<SctpScanTechnique>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|technique| technique.name() == name)
            .ok_or_else(|| UnknownSctpTechnique {
                input: s.to_string(),
            })
    }
}

/// How a TCP port is probed.
///
/// Every technique here needs raw sockets, and so root; the unprivileged connect
/// fallback can only complete handshakes, which is [`Syn`](Self::Syn) and
/// nothing else. A caller asking for another technique without privileges is
/// told so rather than quietly given a connect scan, because the two answer
/// different questions.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TcpScanTechnique {
    /// A lone SYN. The default, and the only technique that identifies an open
    /// port positively: a SYN+ACK means a listener accepted the connection
    /// attempt, and a RST means nothing is there.
    ///
    /// Fast, accurate against every stack, and the most widely recognized -
    /// which is also its weakness, since it is what a filter is most likely to
    /// block and an IDS most likely to log.
    #[default]
    Syn,
    /// A lone FIN. A closed port answers RST, an open one is required to ignore
    /// it, so silence is the closest thing to a positive result.
    ///
    /// The plainest of the flag probes and the one most likely to pass a
    /// stateless filter that blocks SYN.
    Fin,
    /// No flags at all. Semantically identical to [`Fin`](Self::Fin) at the
    /// target - neither carries SYN, ACK or RST - but a segment with an
    /// empty flag field is unlike anything a real connection produces, so it
    /// gets past filters that match on FIN and is trivially matched by any
    /// filter that thinks to look.
    Null,
    /// FIN, PSH and URG together, lit up like a Christmas tree. Classified
    /// exactly as [`Fin`](Self::Fin) is, since PSH and URG occupy no sequence
    /// space and no stack reads them on a segment for a port it is not holding
    /// open.
    ///
    /// Its value over the other two is diagnostic: three unusual flags at once
    /// is a combination filters and stacks disagree about more than either
    /// alone.
    Xmas,
    /// FIN and ACK together, after Uriel Maimon's finding in *Phrack* 49.
    ///
    /// The one technique whose usefulness is a property of the target rather
    /// than of the RFC, and the one to reach for last. BSD-derived stacks drop
    /// the segment when the port is open, and against those it works like a FIN
    /// scan while looking far more like ordinary connection teardown.
    ///
    /// Against a conformant stack it is actively misleading. RFC 793
    /// requires a reset for any ACK-carrying segment on a connection that does
    /// not exist, whether or not the port is listening, so an open port answers
    /// exactly as a closed one does and is reported [`PortState::Closed`].
    /// That is not a missing result but a wrong one, and nothing in the scan
    /// distinguishes it from the truth: measured against a router whose port 80
    /// is open and answers a SYN with SYN+ACK, this technique reported that
    /// port closed. Use it where a FIN scan has already shown the target does
    /// *not* reset everything, and read a `Closed` from it against a second
    /// technique before believing it.
    Maimon,
    /// A lone ACK. Never establishes whether a port is open - it maps the
    /// firewall in front of it.
    ///
    /// A RST means the probe reached the host's stack, which is
    /// [`PortState::Unfiltered`]: something is there and nothing dropped the
    /// segment on the way. Silence or an ICMP error means something did. Running
    /// this beside a SYN scan is what separates "no listener" from "never
    /// arrived".
    Ack,
    /// A lone ACK, read for the window on the reset it draws.
    ///
    /// The probe is [`Ack`](Self::Ack)'s exactly, and so is the RST that comes
    /// back from every port a filter did not swallow. One field separates them:
    /// a stack that announces its listening socket's window on the reset from
    /// an open port, and zero on the reset from a closed one, has said which is
    /// which without a SYN having been sent. It is the only technique here that
    /// finds a listener from a refusal.
    ///
    /// BSD derivatives, a great deal of network hardware and many embedded
    /// stacks still carry the distinction. Linux and current Windows do not:
    /// both reset with a zero window whichever the port was, and against them
    /// this reports the entire range closed. Two shapes of result say the
    /// answer is about the stack rather than the ports, and neither is a
    /// failure the scan can detect for itself: a range that comes back almost
    /// entirely open, and one that comes back closed to the last port. Read
    /// either against a [`Syn`](Self::Syn) scan before believing it.
    Window,
}

impl TcpScanTechnique {
    /// Every technique, in the order they are documented.
    ///
    /// Exists so a front end offering the choice enumerates it from the engine
    /// rather than from a list of its own that drifts the first time one is
    /// added.
    pub const ALL: [Self; 7] = [
        Self::Syn,
        Self::Fin,
        Self::Null,
        Self::Xmas,
        Self::Maimon,
        Self::Ack,
        Self::Window,
    ];

    /// The canonical name, which is also what [`FromStr`] accepts and
    /// [`fmt::Display`] renders.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Syn => "syn",
            Self::Fin => "fin",
            Self::Null => "null",
            Self::Xmas => "xmas",
            Self::Maimon => "maimon",
            Self::Ack => "ack",
            Self::Window => "window",
        }
    }

    /// One line describing what the technique is for, short enough to sit
    /// beside the name wherever a front end offers the choice.
    pub const fn summary(self) -> &'static str {
        match self {
            Self::Syn => "half-open connection attempt; the only one that confirms a listener",
            Self::Fin => "bare FIN; a closed port answers, an open one stays silent",
            Self::Null => "no flags set; like FIN, but unlike any real connection",
            Self::Xmas => "FIN, PSH and URG at once; the most unusual segment of the three",
            Self::Maimon => {
                "FIN with ACK; only meaningful against BSD-derived stacks, misleading elsewhere"
            }
            Self::Ack => "bare ACK; maps the firewall rather than the ports behind it",
            Self::Window => {
                "bare ACK read for the reset's window; tells open from closed where a stack leaks it"
            }
        }
    }

    /// What the technique concludes from `reply`, or `None` if that segment
    /// answers nothing this probe asked.
    ///
    /// The `None` cases are as load-bearing as the others. A SYN+ACK reaching an
    /// ACK scan did not answer its probe - nothing this scan sent could provoke
    /// one - and reading it as an open port would report a listener on the
    /// strength of somebody else's traffic.
    pub const fn verdict(self, reply: TcpReply) -> Option<PortState> {
        match (self, reply) {
            // A SYN is the only probe a listener answers, and a RST to it is the
            // stack saying nothing holds that port.
            (Self::Syn, TcpReply::SynAck) => Some(PortState::Open),
            (Self::Syn, TcpReply::Rst { .. }) => Some(PortState::Closed),

            // A challenge ACK means a stack is already half-open on this
            // connection, which only a listener is. It reaches this scan on the
            // path that matters: when a SYN+ACK is lost, this host never resets
            // it, the peer stays in SYN-RECEIVED, and every retransmission draws
            // one of these instead of a fresh handshake. Reading it as noise
            // reported those ports filtered, which is an open port on a lossy
            // path and the case retransmission exists for.
            (Self::Syn, TcpReply::ChallengeAck) => Some(PortState::Open),

            // No other technique opens a connection, so none can legitimately
            // provoke a challenge. A bare ACK drawn by a FIN or an ACK probe is
            // somebody else's traffic that happened to carry the right nonce, and
            // resolving a port on it would be resolving it on a coincidence.

            // A RST is what only a closed port is obliged to send; the silence
            // of an open one is handled by `silence_means`.
            (Self::Fin | Self::Null | Self::Xmas | Self::Maimon, TcpReply::Rst { .. }) => {
                Some(PortState::Closed)
            }

            // The probe reached a real stack, which is all an ACK scan claims to
            // establish. Whether anything is listening it cannot say.
            (Self::Ack, TcpReply::Rst { .. }) => Some(PortState::Unfiltered),

            // The same reset the ACK scan reads as an unfiltered path, one
            // field further. A window the resetting stack had no connection to
            // announce it for is the listening socket's, and zero is what a
            // port with no socket behind it has to announce.
            (Self::Window, TcpReply::Rst { window }) => Some(if window == 0 {
                PortState::Closed
            } else {
                PortState::Open
            }),

            _ => None,
        }
    }

    /// What the technique concludes when every attempt goes unanswered.
    ///
    /// The difference between the two answers is the difference between the
    /// families. A SYN or an ACK that draws nothing was dropped - both are
    /// answered by any live stack, so silence is a filter. A flag probe that
    /// draws nothing was either dropped *or* delivered to an open port that was
    /// required to ignore it, and no amount of waiting separates those.
    pub const fn silence_means(self) -> PortState {
        match self {
            Self::Syn | Self::Ack | Self::Window => PortState::Filtered,
            Self::Fin | Self::Null | Self::Xmas | Self::Maimon => PortState::OpenFiltered,
        }
    }

    /// Whether this technique can report a port [`PortState::Open`].
    ///
    /// [`Syn`](Self::Syn) from a handshake it drew, [`Window`](Self::Window)
    /// from a refusal it read a field of. It is worth asking before promising a
    /// user open ports, and it is why the service-detection pass, which
    /// fingerprints open TCP ports, finds nothing to do after the other five.
    ///
    /// Not the same question as [`has_connect_fallback`](Self::has_connect_fallback),
    /// which asks whether an unprivileged scan may stand in for this one. Both
    /// were this method for a while, and a window scan would have been quietly
    /// answered with a handshake it never asked for.
    pub const fn finds_open_ports(self) -> bool {
        matches!(self, Self::Syn | Self::Window)
    }

    /// Whether a TCP connect scan asks the same question, and so may stand in
    /// for this technique where the process has no raw sockets.
    ///
    /// [`Syn`](Self::Syn) alone. A completed handshake finds the listeners a
    /// half-open one finds, paying for them by being logged. Every other
    /// technique turns on a segment no kernel sends on a caller's behalf, so
    /// there is nothing to fall back to and the scan is refused instead.
    pub const fn has_connect_fallback(self) -> bool {
        matches!(self, Self::Syn)
    }

    /// Whether this technique needs ICMP errors as well as TCP segments to
    /// reach its verdict.
    ///
    /// False for [`Syn`](Self::Syn) alone. Admitting ICMP copies every ICMP
    /// packet on every captured interface into userspace, an error carrying no
    /// ports to narrow a kernel filter with. The flag-probe techniques buy a
    /// changed verdict for that, [`PortState::Filtered`] where silence would
    /// have said open-filtered, and an ACK scan buys the identity of the device
    /// doing the filtering, which is the question it was asked. A SYN scan
    /// reaches the same verdict either way.
    ///
    /// The evidence still differs, and a caller who wants it can ask through
    /// [`ZondConfig::icmp_evidence`](crate::config::ZondConfig::icmp_evidence):
    /// a filtered port then records the refusal that arrived rather than only
    /// that nothing did.
    pub const fn reads_icmp_errors(self) -> bool {
        !matches!(self, Self::Syn)
    }
}

impl fmt::Display for TcpScanTechnique {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.name())
    }
}

/// The error [`TcpScanTechnique::from_str`] returns, carrying the list of names
/// that would have worked so a front end can print it verbatim.
///
/// The list is built from [`TcpScanTechnique::ALL`] rather than written out, so
/// a technique added there appears in the error that exists to enumerate them.
///
/// Open rather than `#[non_exhaustive]`, for the reason
/// [`MacAddrParseError`](crate::model::mac::MacAddrParseError) gives: one way to
/// fail, one thing to say about it, and the list of alternatives derived rather
/// than stored.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unknown TCP scan technique '{input}', expected one of: {}",
    Self::expected()
)]
pub struct UnknownTechnique {
    /// What the caller wrote.
    pub input: String,
}

impl UnknownTechnique {
    /// The accepted names, comma-separated, in the order they are documented.
    fn expected() -> String {
        TcpScanTechnique::ALL
            .iter()
            .map(|technique| technique.name())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl FromStr for TcpScanTechnique {
    type Err = UnknownTechnique;

    /// Parses a technique name, ignoring case and surrounding whitespace, so a
    /// choice arriving as text - from an argument, a form field, a config file -
    /// needs no mapping table of its own.
    ///
    /// # Examples
    ///
    /// ```
    /// use zond_engine::model::technique::TcpScanTechnique;
    ///
    /// assert_eq!("Xmas".parse(), Ok(TcpScanTechnique::Xmas));
    /// assert!("stealth".parse::<TcpScanTechnique>().is_err());
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|technique| technique.name() == name)
            .ok_or_else(|| UnknownTechnique {
                input: s.to_string(),
            })
    }
}

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

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

    /// Every technique round-trips through its own name, so the name a caller
    /// asks by and the one a report answers with can never drift apart.
    #[test]
    fn every_technique_parses_back_from_the_name_it_prints() {
        for technique in TcpScanTechnique::ALL {
            assert_eq!(technique.to_string().parse(), Ok(technique));
        }
    }

    #[test]
    fn parsing_ignores_case_and_surrounding_space() {
        assert_eq!("  MAIMON ".parse(), Ok(TcpScanTechnique::Maimon));
    }

    /// The error names the alternatives, being printed straight at a user who has
    /// just mistyped a flag, and it names every one, since it is built from `ALL`
    /// rather than from a list somebody has to remember.
    #[test]
    fn an_unknown_name_is_rejected_with_the_ones_that_would_work() {
        let error = "stealth"
            .parse::<TcpScanTechnique>()
            .unwrap_err()
            .to_string();

        assert!(error.contains("stealth"));
        for technique in TcpScanTechnique::ALL {
            assert!(
                error.contains(technique.name()),
                "{technique} is missing: {error}"
            );
        }
    }

    /// The near-miss the whole table exists to prevent: a RST is a closed port
    /// to one technique and an unfiltered path to another, and only the probe
    /// that drew it says which.
    #[test]
    fn a_rst_means_something_different_per_technique() {
        use TcpScanTechnique::*;
        let rst = TcpReply::Rst { window: 8192 };
        assert_eq!(Syn.verdict(rst), Some(PortState::Closed));
        assert_eq!(Fin.verdict(rst), Some(PortState::Closed));
        assert_eq!(Ack.verdict(rst), Some(PortState::Unfiltered));
        assert_eq!(Window.verdict(rst), Some(PortState::Open));
    }

    /// The whole of the window scan: the same reset, read for one field. Zero
    /// is a port with no socket behind it to announce a window for, and
    /// anything else is the socket that had one.
    #[test]
    fn a_window_scan_reads_the_reset_the_ack_scan_only_counts() {
        use TcpScanTechnique::*;
        assert_eq!(
            Window.verdict(TcpReply::Rst { window: 0 }),
            Some(PortState::Closed)
        );
        assert_eq!(
            Window.verdict(TcpReply::Rst { window: 1 }),
            Some(PortState::Open)
        );
        assert_eq!(
            Ack.verdict(TcpReply::Rst { window: 0 }),
            Ack.verdict(TcpReply::Rst { window: 1 }),
            "an ack scan reads the window it has no use for"
        );
    }

    /// An unprivileged process may be given a handshake in place of a SYN scan
    /// and nothing else. A window scan reports open ports too, so reading that
    /// as licence to substitute a connect scan would answer a question about
    /// reset windows with one about connections.
    #[test]
    fn only_a_syn_scan_falls_back_to_connect() {
        for technique in TcpScanTechnique::ALL {
            assert_eq!(
                technique.has_connect_fallback(),
                technique == TcpScanTechnique::Syn,
                "{technique} would have been answered by a connect scan"
            );
        }
        assert!(TcpScanTechnique::Window.finds_open_ports());
        assert!(!TcpScanTechnique::Window.has_connect_fallback());
    }

    /// Only a SYN can provoke a SYN+ACK, so one arriving at any other scan
    /// answered something else and must not be read as an open port.
    #[test]
    fn only_a_syn_scan_reads_a_syn_ack() {
        for technique in TcpScanTechnique::ALL {
            let verdict = technique.verdict(TcpReply::SynAck);
            assert_eq!(
                verdict.is_some(),
                technique == TcpScanTechnique::Syn,
                "{technique} read a SYN+ACK it could not have provoked"
            );
        }
    }

    /// Silence is a filter only where every live stack would have answered.
    /// Getting this backwards would report open ports as filtered on the
    /// techniques whose positive result *is* silence.
    #[test]
    fn silence_is_open_filtered_exactly_for_the_flag_probes() {
        use TcpScanTechnique::*;
        assert_eq!(Syn.silence_means(), PortState::Filtered);
        assert_eq!(Ack.silence_means(), PortState::Filtered);
        assert_eq!(Window.silence_means(), PortState::Filtered);
        for technique in [Fin, Null, Xmas, Maimon] {
            assert_eq!(technique.silence_means(), PortState::OpenFiltered);
        }
    }

    /// An ICMP error changes a flag probe's verdict and names an ACK scan's
    /// firewall; for a SYN scan it confirms what silence already concluded, and
    /// admitting ICMP costs every ICMP packet on the host.
    #[test]
    fn only_a_syn_scan_declines_icmp_errors() {
        for technique in TcpScanTechnique::ALL {
            assert_eq!(
                technique.reads_icmp_errors(),
                technique != TcpScanTechnique::Syn
            );
        }
    }

    // ── SCTP ─────────────────────────────────────────────────────────────────

    /// The same round trip the TCP techniques hold to, so a name in a settings
    /// file and a name in a report cannot drift apart.
    #[test]
    fn every_sctp_technique_parses_back_from_the_name_it_prints() {
        for technique in SctpScanTechnique::ALL {
            assert_eq!(technique.to_string().parse(), Ok(technique));
        }
    }

    #[test]
    fn an_unknown_sctp_name_is_rejected_with_the_ones_that_would_work() {
        let error = "cookie".parse::<SctpScanTechnique>().expect_err("refused");
        let message = error.to_string();
        for technique in SctpScanTechnique::ALL {
            assert!(
                message.contains(technique.name()),
                "the error should name {}",
                technique.name()
            );
        }
    }

    /// An abort is a closed port whichever chunk drew it. An init-ack is an open
    /// port to an init probe and nothing at all to a cookie-echo, which cannot
    /// provoke one: reading it would report a listener on a coincidence.
    #[test]
    fn an_abort_closes_a_port_for_both_and_an_init_ack_only_for_one() {
        assert_eq!(
            SctpScanTechnique::Init.verdict(SctpReply::Abort),
            Some(PortState::Closed)
        );
        assert_eq!(
            SctpScanTechnique::CookieEcho.verdict(SctpReply::Abort),
            Some(PortState::Closed)
        );
        assert_eq!(
            SctpScanTechnique::Init.verdict(SctpReply::InitAck),
            Some(PortState::Open)
        );
        assert_eq!(
            SctpScanTechnique::CookieEcho.verdict(SctpReply::InitAck),
            None
        );
    }

    /// The trade the quieter chunk makes, and the reason it is not the default.
    /// A listener answers an init and discards a cookie it cannot authenticate,
    /// so only one of the two can name an open port and only one reads silence
    /// as a filter.
    #[test]
    fn only_an_init_scan_names_an_open_sctp_port() {
        assert!(SctpScanTechnique::Init.finds_open_ports());
        assert!(!SctpScanTechnique::CookieEcho.finds_open_ports());

        assert_eq!(SctpScanTechnique::Init.silence_means(), PortState::Filtered);
        assert_eq!(
            SctpScanTechnique::CookieEcho.silence_means(),
            PortState::OpenFiltered
        );
    }

    /// The audit line's word for silence is the state silence actually
    /// produces, so a run's own summary cannot contradict its port table.
    #[test]
    fn the_silence_label_names_the_state_silence_produces() {
        assert_eq!(SctpScanTechnique::Init.silence_label(), "filtered");
        assert_eq!(
            SctpScanTechnique::CookieEcho.silence_label(),
            "open-filtered"
        );
    }
}