zond-engine 0.17.0

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

use std::time::{Duration, Instant};

/// One reply, reduced to what the series classifiers read.
///
/// Built from a captured segment by whoever is collecting the series; this
/// type holds no packets and knows nothing about how the samples were drawn.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SeriesSample {
    /// When the reply arrived, as near the wire as its collector could stamp
    /// it. The interval between two of these is what a clock rate and an
    /// identifier step are computed against, a nominal spacing is what the
    /// sender intended, not what happened, and a stamp taken when the reply
    /// was later read carries the reader's scheduling as well.
    pub at: Instant,
    /// The TCP flag byte, so a series can say whether it is reading SYN+ACKs or
    /// resets.
    pub flags: u8,
    /// The sequence number as it arrived: the peer's initial sequence number in
    /// a SYN+ACK, and usually zero in a reset.
    pub sequence: u32,
    /// The IPv4 identification field. `None` over IPv6, which has none.
    pub ip_id: Option<u16>,
    /// The peer's own clock, where it sent a timestamp option.
    pub tsval: Option<u32>,
}

impl SeriesSample {
    /// Whether this reply is a handshake answer rather than a refusal.
    ///
    /// The distinction is load-bearing: a reset opens no connection, so there
    /// is no generator behind its sequence number to describe.
    pub fn is_syn_ack(&self) -> bool {
        use crate::protocols::tcp::flags;
        self.flags & flags::SYN != 0 && self.flags & flags::ACK != 0
    }
}

/// How long two samples may sit apart and still support an identifier reading.
///
/// A 16-bit identifier counter wraps every 65 536 packets. Sampled across a gap
/// long enough for a busy host to wrap it, a counter and a random number are
/// the same observation, and a handful of samples cannot separate them. Longer
/// gaps are reported as [`IdClass::Unclear`] with the raw values, rather than
/// as a class the series cannot support.
pub const MAX_INTERVAL_FOR_ID: Duration = Duration::from_millis(500);

/// How fast a host's other traffic may advance an identifier counter between
/// two samples, in identifiers a second, and leave it read as a counter.
///
/// A counter can be advanced by other traffic between two samples, the host was
/// busy, but not by more than its own output can plausibly account for. 20 000
/// identifiers a second is far beyond any interface a scanner shares a segment
/// with, so a larger step is noise or randomness wearing a counter's shape. The
/// one step the sampled reply itself takes is allowed on top, since it is owed
/// however little time passed.
const PLAUSIBLE_ID_RATE: f64 = 20_000.0;

/// The largest interval still consistent with reading a clock rate.
///
/// The same reasoning as [`MAX_INTERVAL_FOR_ID`] one field over: a wider gap
/// cannot separate a real tick from a coincidence, and the reading is refused
/// rather than guessed.
const MAX_INTERVAL_FOR_CLOCK: Duration = Duration::from_millis(500);

/// The fastest tick still reported as a frequency. Above this the values are
/// random or corrupted rather than a clock: real timestamp clocks run at 100 Hz
/// to
/// 1 kHz, and anything beyond an order of magnitude past that is the
/// per-connection offset of RFC 7323 §5.4.
const CLOCK_CEILING: f64 = 10_000.0;

/// Two readings of one clock whose implied rates differ by less than this
/// factor are one clock. Real stacks tick at a small set of frequencies (100,
/// 250, 1000 Hz); a key that kept more precision than this would report one
/// machine as two because the sampling was jittered.
const CLOCK_SPREAD: f64 = 2.0;

/// The smallest common step still read as a pattern in sequence numbers.
///
/// Differences below this are consistent with a hashed generator that happened
/// to produce near neighbours, and calling them "multiples of 4" would be
/// finding structure in noise.
const MEANINGFUL_ISN_STEP: u32 = 1_024;

/// What a series of IP identifiers turned out to be.
///
/// The name is what a rule predicates on; the class itself is what a report
/// prints, which is the separation the [comparison key](IdClass::name) exists
/// to hold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IdClass {
    /// IPv6, which has no identification field to have a policy about.
    Absent,
    /// Fewer values than a policy can be read from.
    TooFew,
    /// Sampled too slowly for the question to have an answer. The bound is
    /// `MAX_INTERVAL_FOR_ID`: a 16-bit counter wraps inside it, and past that a
    /// counter and a random number are the same observation.
    Unclear,
    /// Zero on every reply. Several stacks write zero on non-fragmentable
    /// datagrams, which RFC 6864 §4.1 permits.
    Zero,
    /// One value across every reply. A per-socket identifier that never
    /// advanced within the window.
    Constant,
    /// Advancing by small steps, wrapping at the field's edge. One counter the
    /// whole host shares.
    Counting,
    /// Values with no relation to each other. A randomised identifier.
    Scattered,
}

impl IdClass {
    /// The class a stable name refers to, or `None` for a name nothing here
    /// produces.
    ///
    /// The inverse of [`name`](Self::name), for reading back a class somebody
    /// wrote down: a recorded example, a translated corpus. See
    /// [`IsnClass::from_name`] for what a rebuilt class does not carry.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "absent" => IdClass::Absent,
            "too-few" => IdClass::TooFew,
            "unclear" => IdClass::Unclear,
            "zero" => IdClass::Zero,
            "constant" => IdClass::Constant,
            "counting" => IdClass::Counting,
            "scattered" => IdClass::Scattered,
            _ => return None,
        })
    }

    /// The stable name a rule or a comparison matches on.
    pub const fn name(self) -> &'static str {
        match self {
            IdClass::Absent => "absent",
            IdClass::TooFew => "too-few",
            IdClass::Unclear => "unclear",
            IdClass::Zero => "zero",
            IdClass::Constant => "constant",
            IdClass::Counting => "counting",
            IdClass::Scattered => "scattered",
        }
    }
}

/// What a series of initial sequence numbers turned out to be.
///
/// Not read from resets: a reset opens no connection, so there is no generator
/// behind its sequence number to describe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IsnClass {
    /// A reset carries no generator to read.
    NotRead,
    /// Fewer than three handshake answers, which cannot show whether the
    /// differences between them repeat.
    TooFew,
    /// Zero throughout, a stack that generates no initial sequence numbers,
    /// which is a quirk worth a rule of its own.
    Zero,
    /// The generator advances by a constant, which *is* a stack constant.
    /// The step is carried for the report and kept out of the
    /// [name](Self::name): two machines running one build differ in load, not
    /// in step.
    FixedStep(u32),
    /// Not a constant step, but every difference is a multiple of one.
    Multiples(u32),
    /// No common step: a hashed generator, per RFC 6528.
    Hashed,
}

impl IsnClass {
    /// The class a stable name refers to, or `None` for a name nothing here
    /// produces.
    ///
    /// A rebuilt class carries no figure. [`name`](Self::name)
    /// drops the step, because how fast a stepping generator advances is a fact
    /// about the machine's activity rather than about the stack, and a rule
    /// matches on the name alone. So a class read back from one is the right
    /// class for matching and the wrong one for [`detail`](Self::detail); use
    /// the reading itself where the figure matters.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "not-read" => IsnClass::NotRead,
            "too-few" => IsnClass::TooFew,
            "zero" => IsnClass::Zero,
            "fixed-step" => IsnClass::FixedStep(0),
            "multiples" => IsnClass::Multiples(0),
            "hashed" => IsnClass::Hashed,
            _ => return None,
        })
    }

    /// The class with the figure behind it, for a person reading a report.
    ///
    /// The other half of what [`name`](Self::name) drops. A rule must not key on
    /// the step, which is the machine's activity rather than the stack's, but
    /// somebody disputing the class, or authoring a rule from it, needs the
    /// number in front of them.
    pub fn detail(self) -> String {
        match self {
            IsnClass::FixedStep(step) => format!("fixed-step({step})"),
            IsnClass::Multiples(step) => format!("multiples({step})"),
            other => other.name().to_owned(),
        }
    }

    /// The stable name a rule or a comparison matches on. Carries no step: how
    /// *fast* a stepping generator advances is a fact about the machine's
    /// activity, not about the stack.
    pub const fn name(self) -> &'static str {
        match self {
            IsnClass::NotRead => "not-read",
            IsnClass::TooFew => "too-few",
            IsnClass::Zero => "zero",
            IsnClass::FixedStep(_) => "fixed-step",
            IsnClass::Multiples(_) => "multiples",
            IsnClass::Hashed => "hashed",
        }
    }
}

/// What a series of timestamp values turned out to be.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClockClass {
    /// The peer offered no timestamp option.
    None,
    /// It sent the option and left the value at zero, which is a stack policy
    /// rather than a clock.
    Zero,
    /// Fewer than two timestamps to compare, samples more than half a second
    /// apart, past which a tick and a coincidence read the same, or two samples
    /// that arrived at the same instant and so span no time to have ticked in.
    /// All three come to the same answer: no rate can be taken from this series.
    TooFew,
    /// The values move, but not as one clock read repeatedly does.
    ///
    /// This is a finding, not a failure. RFC 7323 §5.4 recommends a sender
    /// add a *per-connection* random offset to its timestamp clock, and every
    /// sample in a series drawn by separate connections sees a different
    /// offset. Whether a stack does this is itself a discriminator, and it
    /// means the clock's *rate* cannot be recovered from separate connections
    /// at all. Recovering that needs two timestamps from **one** connection,
    /// which needs a completed handshake.
    Randomised,
    /// The clock ticks more slowly than the sampling: the values are nonzero
    /// and never changed. A real reading, and one that needs a longer run to
    /// put a number on.
    Slower,
    /// The clock's frequency, rounded to the nearest ten hertz.
    ///
    /// Rounded because the raw figure carries the sampling's own timing
    /// jitter: two readings a few milliseconds off across a half-second span
    /// move the answer by well under one percent, and a key built on the exact
    /// number would report one machine as two. Ten hertz is coarse enough to
    /// absorb that and fine enough to keep the frequencies stacks actually use
    /// apart.
    Hertz(u32),
}

impl ClockClass {
    /// The class a stable name refers to, or `None` for a name nothing here
    /// produces.
    ///
    /// Carries no frequency, for the reason [`IsnClass::from_name`] gives.
    pub fn from_name(name: &str) -> Option<Self> {
        Some(match name {
            "none" => ClockClass::None,
            "zero" => ClockClass::Zero,
            "too-few" => ClockClass::TooFew,
            "randomised" => ClockClass::Randomised,
            "slower" => ClockClass::Slower,
            "ticking" => ClockClass::Hertz(0),
            _ => return None,
        })
    }

    /// The class with the frequency behind it, for a person reading a report.
    ///
    /// The rate is the whole reason to look: it is a stack-build constant, and
    /// the one that moved when Linux stopped deriving its timestamp clock from
    /// the tick rate. A rule cannot key on it, the sampling's own jitter is in
    /// the figure, so an exact hertz would match one network and not the next,
    /// but a person deciding *what rule to write* has nothing else to go on.
    pub fn detail(self) -> String {
        match self {
            ClockClass::Hertz(hz) => format!("ticking({hz}Hz)"),
            other => other.name().to_owned(),
        }
    }

    /// The stable name a rule or a comparison matches on.
    pub const fn name(self) -> &'static str {
        match self {
            ClockClass::None => "none",
            ClockClass::Zero => "zero",
            ClockClass::TooFew => "too-few",
            ClockClass::Randomised => "randomised",
            ClockClass::Slower => "slower",
            ClockClass::Hertz(_) => "ticking",
        }
    }
}

/// The three series readings for one host, in the form a rule and a report
/// consume.
///
/// Built from the samples by whoever collected them; a passive path has no
/// series and no `SeriesClasses`, which is the ordinary case, a rule naming a
/// series predicate then fails to match by the same "the peer did not say" rule
/// that governs every other absent field.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SeriesClasses {
    /// What the IP identifier series turned out to be.
    pub identifiers: IdClass,
    /// What the initial-sequence-number series turned out to be.
    pub sequences: IsnClass,
    /// What the timestamp series turned out to be.
    pub clock: ClockClass,
}

impl SeriesClasses {
    /// Reads all three series from one set of samples.
    ///
    /// The classifiers refuse more than they answer, too few samples, sampled
    /// too slowly, the field absent, and a refusal is a class like any other:
    /// it matches no rule that predicates on the field, which is exactly the
    /// behaviour a series collected badly should have.
    pub fn from_samples(series: &[SeriesSample]) -> Self {
        Self {
            identifiers: read_identifiers(series).class,
            sequences: read_sequences(series).class,
            clock: read_clock(series).class,
        }
    }

    /// One line saying what the series held, for a report to carry beside a
    /// verdict. Written for a person, to the same rule as
    /// [`StackObservation::summary`](super::StackObservation::summary).
    ///
    /// Figures included, where a class has one. This is the display half, not
    /// the comparison key: a rule still matches on the bare names, and the
    /// module documentation's promise that "the raw figures are kept beside it
    /// for the report" is only kept if the report actually shows them. A reading
    /// of `ticking` alone cannot tell somebody whether they are looking at the
    /// 1 kHz clock of one build or the tick-derived one of an older kernel,
    /// which is the single question this series is best placed to answer.
    pub fn summary(&self) -> String {
        format!(
            "id={} isn={} ts={}",
            self.identifiers.name(),
            self.sequences.detail(),
            self.clock.detail()
        )
    }
}

/// What one classifier made of one series: the class, and the raw values for a
/// report to carry beside it.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Reading<T> {
    /// The class itself.
    pub class: T,
    /// The raw values, rendered for a person. A class this classifier declined
    /// to give, or gave wrongly, can be overruled by reading these.
    pub line: String,
}

/// Reads the identifier series.
///
/// Each sample's value is paired with its arrival time, because the step each
/// interval implies is what decides the class; a filter on values and a window
/// on times applied separately can fall out of step the first time a reply
/// arrives without the field.
pub fn read_identifiers(series: &[SeriesSample]) -> Reading<IdClass> {
    let sampled: Vec<(Instant, u16)> = series
        .iter()
        .filter_map(|sample| sample.ip_id.map(|id| (sample.at, id)))
        .collect();

    let values: Vec<u16> = sampled.iter().map(|(_, id)| *id).collect();
    if values.is_empty() {
        return Reading {
            class: IdClass::Absent,
            line: "none - IPv6 has no identification field".to_string(),
        };
    }
    if values.len() < 3 {
        return Reading {
            class: IdClass::TooFew,
            line: format!("{values:?} - too few to read a policy from"),
        };
    }

    let raw = format!("{values:?}");
    let widest = sampled
        .windows(2)
        .map(|pair| pair[1].0.duration_since(pair[0].0))
        .max()
        .unwrap_or_default();
    if widest > MAX_INTERVAL_FOR_ID {
        return Reading {
            class: IdClass::Unclear,
            line: format!("{raw} - unclear"),
        };
    }

    if values.iter().all(|&value| value == 0) {
        return Reading {
            class: IdClass::Zero,
            line: format!("{raw} - zero throughout"),
        };
    }
    if values.windows(2).all(|pair| pair[0] == pair[1]) {
        return Reading {
            class: IdClass::Constant,
            line: format!("{raw} - constant"),
        };
    }

    // Wrapping, because a counter crossing 65535 is still a counter and a naive
    // subtraction turns one step into a jump of sixty-five thousand.
    //
    // Judged per interval, not over the whole span. A counter never jumps, so
    // one step implying an implausible rate is enough to say this is not one
    // being followed, where a total advance divided by a total span would let a
    // single large jump hide behind several small ones and report a tidy
    // average describing nothing that happened.
    let steps: Vec<u16> = sampled
        .windows(2)
        .map(|pair| pair[1].1.wrapping_sub(pair[0].1))
        .collect();
    // **Every** interval has to be one a counter could have covered. Asking
    // instead whether *any* interval looks like a counter is a question a
    // random series answers by accident: measured, 284 of 2000 purely random
    // six-sample series read as `counting` that way, and one clean counter with
    // a single forty-thousand jump read as one too.
    //
    // Bounded by multiplying the interval rather than dividing by it. Two
    // replies can be stamped at one instant, and a step over no time is an
    // infinity or a NaN, which would read a real counter as scattered and pass
    // over a still one in silence. A counter the host shares advances by one
    // for its own next reply however soon that follows, so that step is
    // allowed at any interval, and only the traffic past it has to fit the
    // time.
    //
    // Not dropped, as `read_clock` drops an interval of no length. A clock's
    // rate is ticks over time and there is none without both, where a
    // counter's step says something alone: forty thousand between two replies
    // read together is no counter, and dropping the pair would let a random
    // value hide in exactly the interval that gives it away.
    let plausible = sampled.windows(2).zip(&steps).all(|(pair, &step)| {
        let elapsed = pair[1].0.duration_since(pair[0].0).as_secs_f64();
        f64::from(step) <= 1.0 + PLAUSIBLE_ID_RATE * elapsed
    });

    if plausible {
        return Reading {
            class: IdClass::Counting,
            line: format!("{raw} - counting"),
        };
    }
    Reading {
        class: IdClass::Scattered,
        line: format!("{raw} - scattered"),
    }
}

/// Reads the sequence-number series, from handshake answers only.
pub fn read_sequences(series: &[SeriesSample]) -> Reading<IsnClass> {
    if series.iter().all(|sample| !sample.is_syn_ack()) {
        return Reading {
            class: IsnClass::NotRead,
            line: "not read - a reset opens no connection to number".to_string(),
        };
    }

    let syn_acks: Vec<&SeriesSample> = series.iter().filter(|s| s.is_syn_ack()).collect();
    let values: Vec<u32> = syn_acks.iter().map(|sample| sample.sequence).collect();
    if values.iter().all(|&value| value == 0) {
        return Reading {
            class: IsnClass::Zero,
            line: "zero throughout".to_string(),
        };
    }
    if values.len() < 3 {
        return Reading {
            class: IsnClass::TooFew,
            line: format!("{values:?} - too few to read a generator from"),
        };
    }

    let steps: Vec<u32> = values
        .windows(2)
        .map(|pair| pair[1].wrapping_sub(pair[0]))
        .collect();
    if steps.windows(2).all(|pair| pair[0] == pair[1]) {
        return Reading {
            class: IsnClass::FixedStep(steps[0]),
            line: format!("fixed step of {}", steps[0]),
        };
    }
    let divisor = steps.iter().copied().fold(0u32, gcd);
    if divisor >= MEANINGFUL_ISN_STEP {
        return Reading {
            class: IsnClass::Multiples(divisor),
            line: format!("stepping in multiples of {divisor}"),
        };
    }
    Reading {
        class: IsnClass::Hashed,
        line: format!("no common step (divisor {divisor}) - consistent with a hashed generator"),
    }
}

/// Reads the peer's clock, where it sent one.
///
/// Every interval is checked, not just the span from first to last. A stack
/// that randomises its offset per connection can produce a first-to-last
/// difference that looks perfectly reasonable by chance while every step in
/// between is nonsense, and reading only the endpoints would report a
/// confident frequency for a host that has no comparable clock at all.
pub fn read_clock(series: &[SeriesSample]) -> Reading<ClockClass> {
    let sampled: Vec<(Instant, u32)> = series
        .iter()
        .filter_map(|sample| sample.tsval.map(|ts| (sample.at, ts)))
        .collect();

    if sampled.is_empty() {
        return Reading {
            class: ClockClass::None,
            line: "none sent".to_string(),
        };
    }
    let values: Vec<u32> = sampled.iter().map(|(_, ts)| *ts).collect();
    if values.iter().all(|&value| value == 0) {
        return Reading {
            class: ClockClass::Zero,
            line: "sent, but always zero".to_string(),
        };
    }
    if values.len() < 2 {
        return Reading {
            class: ClockClass::TooFew,
            line: format!("{values:?} - too few to read a rate from"),
        };
    }

    let raw = format!("{values:?}");
    let widest = sampled
        .windows(2)
        .map(|pair| pair[1].0.duration_since(pair[0].0))
        .max()
        .unwrap_or_default();
    if widest > MAX_INTERVAL_FOR_CLOCK {
        return Reading {
            class: ClockClass::TooFew,
            line: format!("{raw} - sampled too slowly for a rate"),
        };
    }

    // Per interval, wrapping at the 32-bit edge. A clock crossing its wrap is
    // still a clock, and the endpoint-only reading would turn one into a
    // ten-digit rate.
    //
    // Intervals of no length are dropped rather than divided by. Two replies can
    // be read at one instant, and the quotient is then an infinity or, where the
    // clock did not move either, a NaN that compares false against every bound
    // below and left the series reported as ticking at "NaN Hz".
    let rates: Vec<f64> = sampled
        .windows(2)
        .filter_map(|pair| {
            let ticks = pair[1].1.wrapping_sub(pair[0].1);
            let secs = pair[1].0.duration_since(pair[0].0).as_secs_f64();
            (secs > 0.0).then(|| f64::from(ticks) / secs)
        })
        .collect();
    if rates.is_empty() {
        return Reading {
            class: ClockClass::TooFew,
            line: format!("{raw} - no interval to read a rate over"),
        };
    }

    // The spread check is the whole defence against the plausible-endpoints
    // trap: every interval has to agree with every other, not just the
    // endpoints with themselves.
    let slowest = rates.iter().copied().fold(f64::INFINITY, f64::min);
    let fastest = rates.iter().copied().fold(0.0, f64::max);
    if fastest > CLOCK_CEILING || fastest / slowest.max(f64::MIN_POSITIVE) > CLOCK_SPREAD {
        return Reading {
            class: ClockClass::Randomised,
            line: format!("{raw} - randomised per connection"),
        };
    }

    let hertz = rates.iter().sum::<f64>() / rates.len() as f64;
    if hertz < 1.0 {
        return Reading {
            class: ClockClass::Slower,
            line: format!("{raw} - slower than sampled"),
        };
    }
    let rounded = (hertz / 10.0).round() * 10.0;
    Reading {
        class: ClockClass::Hertz(rounded as u32),
        line: format!("{raw} - about {rounded:.0} Hz"),
    }
}

/// Greatest common divisor, for finding a fixed step in a set of differences.
fn gcd(a: u32, b: u32) -> u32 {
    let (mut a, mut b) = (a, b);
    while b != 0 {
        let remainder = a % b;
        a = b;
        b = remainder;
    }
    a
}

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

#[cfg(test)]
mod tests {

    /// Two replies read at one instant span no time, and a clock rate over no
    /// time is not a rate.
    ///
    /// The quotient is an infinity where the clock moved and a NaN where it did
    /// not, and a NaN compares false against every bound the rate is checked
    /// against: not above the ceiling, not outside the spread, not below one
    /// hertz. Unchecked, it reaches the end and casts to zero, so a series that
    /// measured nothing would be reported as ticking, at "NaN Hz" in the line a
    /// person reads.
    #[test]
    fn an_interval_of_no_length_yields_no_rate() {
        let t0 = Instant::now();
        let sample = |at: Instant, tsval: u32| SeriesSample {
            at,
            flags: 0x12,
            sequence: 1,
            ip_id: None,
            tsval: Some(tsval),
        };

        // Non-zero throughout, so the all-zero branch above does not take it.
        let stopped = read_clock(&[sample(t0, 7), sample(t0, 7)]);
        assert_eq!(stopped.class, ClockClass::TooFew, "{}", stopped.line);
        assert!(
            !stopped.line.contains("NaN"),
            "and the line says so in words: {}",
            stopped.line
        );

        let moved = read_clock(&[sample(t0, 7), sample(t0, 9)]);
        assert_eq!(moved.class, ClockClass::TooFew, "{}", moved.line);

        // The ordinary reading is untouched: 100 ticks in 100 ms is a kilohertz.
        let t1 = t0 + Duration::from_millis(100);
        let ordinary = read_clock(&[sample(t0, 4096), sample(t1, 4196)]);
        assert_eq!(ordinary.class, ClockClass::Hertz(1000), "{}", ordinary.line);
    }

    /// The failure the fastest-interval reading exists for.
    ///
    /// A counter never jumps, so one step implying an implausible rate settles
    /// it. Reading the *slowest* interval instead asks whether any step looks
    /// like a counter, which a random series answers by accident often enough to
    /// matter: this measured 284 of 2000 six-sample random series as `counting`.
    ///
    /// The threshold is a ceiling on the whole series, not a floor somewhere in
    /// it.
    #[test]
    fn a_randomised_identifier_series_is_not_a_counter() {
        let t0 = Instant::now();
        let at = |ms: u64| t0 + Duration::from_millis(ms);
        let sample = |ms: u64, id: u16| SeriesSample {
            at: at(ms),
            flags: 0x12,
            sequence: 1,
            ip_id: Some(id),
            tsval: None,
        };

        // Two tiny steps and one enormous jump. The jump alone disqualifies it.
        let jumpy = vec![
            sample(0, 1000),
            sample(100, 1001),
            sample(200, 1002),
            sample(300, 41_002),
        ];
        assert_eq!(
            read_identifiers(&jumpy).class,
            IdClass::Scattered,
            "a counter does not jump forty thousand in a tenth of a second"
        );

        // A random series that happens to contain one near-neighbour pair, which
        // is what a slowest-interval reading is fooled by.
        let random = vec![
            sample(0, 51_234),
            sample(100, 8_123),
            sample(200, 8_223),
            sample(300, 61_999),
            sample(400, 3),
            sample(500, 40_000),
        ];
        assert_eq!(read_identifiers(&random).class, IdClass::Scattered);

        // Measured rather than asserted by example: a purely random series must
        // almost never read as a counter. The bound is generous so the test does
        // not depend on this particular generator.
        let mut state: u64 = 0x2545_F491_4F6C_DD1D;
        let mut counting = 0;
        for _ in 0..2_000 {
            let series: Vec<SeriesSample> = (0..6u64)
                .map(|i| {
                    state ^= state << 13;
                    state ^= state >> 7;
                    state ^= state << 17;
                    sample(i * 100, (state >> 16) as u16)
                })
                .collect();
            if read_identifiers(&series).class == IdClass::Counting {
                counting += 1;
            }
        }
        assert!(
            counting < 20,
            "{counting} of 2000 random series read as a counter; the slowest-interval \
             reading this replaced scored 284"
        );
    }

    /// And a real counter is still a counter, including one the host's other
    /// traffic advanced between samples.
    #[test]
    fn a_counter_is_still_read_as_one() {
        let t0 = Instant::now();
        let sample = |ms: u64, id: u16| SeriesSample {
            at: t0 + Duration::from_millis(ms),
            flags: 0x12,
            sequence: 1,
            ip_id: Some(id),
            tsval: None,
        };

        let steady = vec![
            sample(0, 100),
            sample(100, 103),
            sample(200, 107),
            sample(300, 111),
        ];
        assert_eq!(read_identifiers(&steady).class, IdClass::Counting);

        // Wrapping at the field's edge is still a counter.
        let wrapping = vec![
            sample(0, 65_530),
            sample(100, 65_534),
            sample(200, 2),
            sample(300, 6),
        ];
        assert_eq!(read_identifiers(&wrapping).class, IdClass::Counting);
    }
    use super::*;
    use std::time::Duration;

    /// Builds a series with `offsets` between samples, carrying whichever of
    /// the three fields each reply held. Absent slices mean the field was not
    /// present in those replies, which is a different thing from a zero.
    ///
    /// The base instant is read **once**. Reading it per sample would make the
    /// offsets approximate rather than exact, each call advancing by however
    /// long the loop took, and every reading here divides a counter's movement
    /// by the interval between samples, so a machine under load could push a
    /// rate across a bucket boundary and fail a test about arithmetic for
    /// reasons that have nothing to do with it.
    fn series(
        offsets: &[Duration],
        identifiers: &[u16],
        sequences: &[u32],
        stamps: &[u32],
    ) -> Vec<SeriesSample> {
        use crate::protocols::tcp::flags;
        let base = Instant::now();
        offsets
            .iter()
            .enumerate()
            .map(|(index, offset)| SeriesSample {
                at: base + *offset,
                flags: flags::SYN | flags::ACK,
                sequence: sequences.get(index).copied().unwrap_or(0),
                ip_id: identifiers.get(index).copied(),
                tsval: stamps.get(index).copied(),
            })
            .collect()
    }

    fn spaced(count: usize) -> Vec<Duration> {
        (0..count)
            .map(|i| Duration::from_millis(100 * i as u64))
            .collect()
    }

    #[test]
    fn identifiers_zero_constant_and_absent() {
        let zero = series(&spaced(4), &[0, 0, 0, 0], &[], &[]);
        assert_eq!(read_identifiers(&zero).class, IdClass::Zero);

        let constant = series(&spaced(4), &[7, 7, 7, 7], &[], &[]);
        assert_eq!(read_identifiers(&constant).class, IdClass::Constant);

        let absent = series(&spaced(4), &[], &[], &[]);
        assert_eq!(read_identifiers(&absent).class, IdClass::Absent);

        let too_few = series(&spaced(2), &[5, 6], &[], &[]);
        assert_eq!(read_identifiers(&too_few).class, IdClass::TooFew);
    }

    /// A counter wrapping at the field's edge is still a counter: the naive
    /// subtraction turns one step into a jump of sixty-five thousand.
    #[test]
    fn a_wrapping_counter_is_still_counting() {
        let wrapping = series(&spaced(4), &[65_530, 65_532, 65_534, 0], &[], &[]);
        assert_eq!(read_identifiers(&wrapping).class, IdClass::Counting);
    }

    /// A gap wider than the counter can wrap inside makes the reading
    /// unanswerable, and the class says so rather than guessing.
    #[test]
    fn a_slowly_sampled_series_is_unclear() {
        let gaps = vec![
            Duration::ZERO,
            Duration::from_millis(100),
            Duration::from_millis(900),
        ];
        let slow = series(&gaps, &[10, 11, 12], &[], &[]);
        assert_eq!(read_identifiers(&slow).class, IdClass::Unclear);
    }

    /// Two replies stamped at one instant are still two readings of a counter.
    ///
    /// A step divided by an interval of no length is an infinity where the
    /// counter moved, which would read a genuine counter as scattered, and a
    /// NaN where it did not, which every comparison passes over in silence.
    /// Replies taken off a capture together arrive stamped close together, so
    /// this is the ordinary case for a prompt answer rather than a curiosity.
    ///
    /// The interval is not dropped either, as the clock reading drops one: a
    /// counter's step means something at no interval, and forty thousand
    /// between two replies read together is nothing a counter does.
    #[test]
    fn replies_stamped_at_one_instant_are_still_read_as_a_counter() {
        let together = [Duration::ZERO, Duration::ZERO, Duration::from_millis(100)];

        let counter = read_identifiers(&series(&together, &[100, 101, 102], &[], &[]));
        assert_eq!(counter.class, IdClass::Counting, "{}", counter.line);

        let unmoved = read_identifiers(&series(&together, &[100, 100, 101], &[], &[]));
        assert_eq!(unmoved.class, IdClass::Counting, "{}", unmoved.line);

        let jumped = read_identifiers(&series(&together, &[100, 40_100, 40_101], &[], &[]));
        assert_eq!(jumped.class, IdClass::Scattered, "{}", jumped.line);
    }

    /// Random values have no step a counter could follow, and the fastest
    /// implied rate is beyond anything a host outputs.
    #[test]
    fn randomised_identifiers_are_scattered() {
        let scattered = series(&spaced(4), &[4_000, 61_000, 12_000, 33_000], &[], &[]);
        assert_eq!(read_identifiers(&scattered).class, IdClass::Scattered);
    }

    #[test]
    fn sequences_fixed_step_multiples_and_hashed() {
        let stepping = series(
            &spaced(4),
            &[],
            &[1_000_000, 1_064_000, 1_128_000, 1_192_000],
            &[],
        );
        assert_eq!(read_sequences(&stepping).class, IsnClass::FixedStep(64_000));

        let hashed = series(
            &spaced(4),
            &[],
            &[2_147_483_647, 91_827_361, 3_918_273_645, 771_293_811],
            &[],
        );
        assert_eq!(read_sequences(&hashed).class, IsnClass::Hashed);

        let zero = series(&spaced(4), &[], &[0, 0, 0, 0], &[]);
        assert_eq!(read_sequences(&zero).class, IsnClass::Zero);
    }

    /// A reset opens no connection, so there is no generator behind its
    /// sequence number to describe, whatever the values happen to be.
    #[test]
    fn a_resets_sequence_number_is_not_read() {
        use crate::protocols::tcp::flags;
        let mut reset_series = series(
            &spaced(4),
            &[],
            &[1_000_000, 1_064_000, 1_128_000, 1_192_000],
            &[],
        );
        for sample in &mut reset_series {
            sample.flags = flags::RST | flags::ACK;
        }
        assert_eq!(read_sequences(&reset_series).class, IsnClass::NotRead);
    }

    #[test]
    fn clocks_none_zero_and_ticking() {
        let none = series(&spaced(4), &[], &[], &[]);
        assert_eq!(read_clock(&none).class, ClockClass::None);

        let zero = series(&spaced(4), &[], &[], &[0, 0, 0, 0]);
        assert_eq!(read_clock(&zero).class, ClockClass::Zero);

        let ticking = series(
            &spaced(6),
            &[],
            &[],
            &[500_000, 500_100, 500_200, 500_300, 500_400, 500_500],
        );
        assert_eq!(read_clock(&ticking).class, ClockClass::Hertz(1000));
    }

    /// The same clock, crossing the end of its 32-bit counter. Wrapping or not
    /// is the difference between 1000 Hz and a number with ten digits.
    #[test]
    fn a_clock_crossing_its_wrap_is_still_that_clock() {
        let wrapping = series(
            &spaced(6),
            &[],
            &[],
            &[u32::MAX - 200, u32::MAX - 100, u32::MAX, 99, 199, 299],
        );
        assert_eq!(read_clock(&wrapping).class, ClockClass::Hertz(1000));
    }

    /// RFC 7323 §5.4: a per-connection random offset makes every sample a
    /// different clock. Real hardware produces exactly this, and read as one
    /// clock it measured as a clock running at 1.9 GHz.
    #[test]
    fn a_per_connection_random_offset_is_not_a_clock() {
        let randomised = series(
            &spaced(6),
            &[],
            &[],
            &[
                1_913_402_881,
                88_120_004,
                3_774_119_855,
                412_998_002,
                2_660_001_913,
                955_218_744,
            ],
        );
        assert_eq!(read_clock(&randomised).class, ClockClass::Randomised);
    }

    /// The case that makes checking every interval worth it. The endpoints are
    /// five hundred ticks apart across half a second, so an endpoint-only
    /// reading reports a tidy 1000 Hz while every step in between is nonsense.
    #[test]
    fn endpoints_that_agree_do_not_make_the_middle_a_clock() {
        let plausible = series(
            &spaced(6),
            &[],
            &[],
            &[500_000, 900_000, 100_000, 700_000, 200_000, 500_500],
        );
        assert_eq!(read_clock(&plausible).class, ClockClass::Randomised);
    }

    /// A clock ticking more slowly than the sampling: a real reading that a
    /// longer run would put a number on, not a failure.
    #[test]
    fn a_clock_slower_than_the_sampling_says_so() {
        let slow = series(&spaced(6), &[], &[], &[77_777; 6]);
        assert_eq!(read_clock(&slow).class, ClockClass::Slower);
    }

    /// The comparison key is coarse in the right places: two counters at
    /// different rates are one policy, and one clock measured with sampling
    /// jitter is one clock.
    #[test]
    fn the_names_are_coarse_where_the_values_vary() {
        let slow_counter = series(&spaced(6), &[10, 11, 12, 13, 14, 15], &[], &[]);
        let fast_counter = series(&spaced(6), &[900, 950, 1000, 1050, 1100, 1150], &[], &[]);
        assert_eq!(
            read_identifiers(&slow_counter).class.name(),
            read_identifiers(&fast_counter).class.name(),
            "two counters at different rates share one policy name"
        );

        // Both intervals sit inside `MAX_INTERVAL_FOR_CLOCK`, which is the
        // point: this test is about the *naming* being coarse, and a sample
        // spaced beyond that ceiling is refused a rate before any naming
        // happens. A pair straddling it, 500 ms and 502 ms, would have both
        // readings refused, and the assertion would compare one rejection
        // against another, agreeing for a reason that has nothing to do with
        // clocks.
        let jittered = series(
            &[Duration::ZERO, Duration::from_millis(251)],
            &[],
            &[],
            &[500_000, 500_250],
        );
        let exact = series(
            &[Duration::ZERO, Duration::from_millis(250)],
            &[],
            &[],
            &[700_000, 700_250],
        );
        assert_eq!(
            read_clock(&jittered).class,
            ClockClass::Hertz(1_000),
            "996 Hz measured is a 1000 Hz clock, and the rounding is what says so"
        );
        assert_eq!(
            read_clock(&jittered).class.name(),
            read_clock(&exact).class.name(),
            "one clock measured with jitter reads as one clock"
        );
    }

    #[test]
    fn a_series_sample_knows_whether_it_answered_a_handshake() {
        use crate::protocols::tcp::flags;
        let handshake = series(&spaced(1), &[], &[], &[]);
        assert!(handshake[0].is_syn_ack());

        let mut reset = series(&spaced(1), &[], &[], &[]);
        reset[0].flags = flags::RST;
        assert!(!reset[0].is_syn_ack());
    }

    #[test]
    fn gcd_finds_the_common_step() {
        assert_eq!(gcd(0, 0), 0);
        assert_eq!(gcd(64_000, 64_000), 64_000);
        assert_eq!(gcd(48, 18), 6);
    }

    /// The type is public vocabulary and must stay constructible from plain
    /// values, pinned so an accidental private-field refactor does not strand
    /// the collectors that build these.
    #[test]
    fn samples_are_buildable_from_plain_values() {
        let sample = SeriesSample {
            at: Instant::now(),
            flags: 0x12,
            sequence: 42,
            ip_id: Some(7),
            tsval: None,
        };
        assert_eq!(sample.ip_id, Some(7));
    }
}