zond-engine 0.14.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # What a TLS endpoint may be asked to accept
//!
//! The vocabulary an enumeration speaks: the protocol versions worth offering,
//! the cipher suites worth offering under each, and what is wrong with the ones
//! that are wrong. No I/O and no wire format; [`protocols::tls`](crate::protocols::tls)
//! builds the packet and [`fingerprint`](crate::fingerprint) sends it.
//!
//! ## Why a suite's faults are derived rather than stored
//!
//! A cipher suite is not an opaque name. `TLS_RSA_WITH_3DES_EDE_CBC_SHA` says,
//! in order, that it exchanges keys with static RSA, encrypts with 3DES in CBC
//! mode, and authenticates with SHA-1, and each of those three is a separate
//! thing a report should say about it. So a suite here is its parts, and
//! [`CipherSuite::faults`] reads the parts rather than a verdict written beside
//! them. A table of verdicts drifts from the suites it grades the first time one
//! is added; a derivation cannot.
//!
//! ## The list is curated, and says so
//!
//! IANA's registry holds several hundred suites, most of them never deployed.
//! [`CipherSuite::ALL`] is the ones a scan has any reason to offer: everything a
//! current server negotiates, and everything with a fault worth reporting, so
//! that a range coming back clean is evidence rather than a gap in the list. A
//! suite nobody has ever configured is absent, and a server that somehow
//! negotiates one is reported by its number; see
//! [`CipherSuite::from_code`].

use std::fmt;
use std::str::FromStr;
use std::sync::OnceLock;

use crate::model::confidence::Confidence;
use crate::model::finding::{
    DetectionClass, DetectionId, Excerpt, Finding, Reference, Severity, Version,
};

// ---------------------------------------------------------------------------
// Versions
// ---------------------------------------------------------------------------

/// A TLS protocol version, by the number it carries on the wire.
///
/// Ordered oldest to newest, so a scan reporting the range an endpoint accepts
/// can name its floor and ceiling by comparison rather than by a table.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TlsVersion {
    /// SSL 3.0. Prohibited by RFC 7568 and broken by POODLE; no current client
    /// offers it and no current server should accept it.
    Ssl30,
    /// TLS 1.0. Deprecated by RFC 8996.
    Tls10,
    /// TLS 1.1. Deprecated by RFC 8996 alongside 1.0.
    Tls11,
    /// TLS 1.2. Still the floor most deployments sit on.
    Tls12,
    /// TLS 1.3. The version whose handshake is negotiated through an extension
    /// rather than through the version field; see
    /// [`protocols::tls`](crate::protocols::tls).
    Tls13,
}

impl TlsVersion {
    /// Every version worth offering, oldest first.
    ///
    /// An enumeration walks this in order, so the report's version list is in
    /// the same order for every endpoint and two scans diff cleanly.
    pub const ALL: [Self; 5] = [
        Self::Ssl30,
        Self::Tls10,
        Self::Tls11,
        Self::Tls12,
        Self::Tls13,
    ];

    /// The two-byte number this version carries on the wire.
    ///
    /// TLS 1.3's is `0x0304`, which never appears in a record header or in a
    /// ClientHello's version field: RFC 8446 §4.1.2 puts it in the
    /// `supported_versions` extension and leaves the legacy field reading
    /// `0x0303`. The number is still this one, and the wire module is what knows
    /// where to write it.
    pub const fn code(self) -> u16 {
        match self {
            Self::Ssl30 => 0x0300,
            Self::Tls10 => 0x0301,
            Self::Tls11 => 0x0302,
            Self::Tls12 => 0x0303,
            Self::Tls13 => 0x0304,
        }
    }

    /// The version a wire number names, or `None` for a number no version here
    /// claims.
    pub const fn from_code(code: u16) -> Option<Self> {
        match code {
            0x0300 => Some(Self::Ssl30),
            0x0301 => Some(Self::Tls10),
            0x0302 => Some(Self::Tls11),
            0x0303 => Some(Self::Tls12),
            0x0304 => Some(Self::Tls13),
            _ => None,
        }
    }

    /// The name this version is written under, in a report and wherever it
    /// arrives as text.
    ///
    /// The spelling every other tool prints, so a reader comparing two scanners'
    /// output is comparing findings rather than formatting.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Ssl30 => "SSLv3",
            Self::Tls10 => "TLSv1.0",
            Self::Tls11 => "TLSv1.1",
            Self::Tls12 => "TLSv1.2",
            Self::Tls13 => "TLSv1.3",
        }
    }

    /// Whether a standards body has withdrawn this version.
    ///
    /// RFC 7568 prohibits SSL 3.0; RFC 8996 deprecates TLS 1.0 and 1.1. An
    /// endpoint still accepting one of these is the single most quotable line a
    /// TLS enumeration produces, because the remedy is a configuration change
    /// rather than an upgrade.
    pub const fn is_deprecated(self) -> bool {
        matches!(self, Self::Ssl30 | Self::Tls10 | Self::Tls11)
    }

    /// How much a report should make of an endpoint that still accepts this
    /// version.
    ///
    /// SSL 3.0 outranks the other two because POODLE is a practical attack
    /// against it rather than a deprecation on paper: an attacker who can make a
    /// client retry recovers plaintext a byte at a time. TLS 1.0 and 1.1 are
    /// withdrawn and, on their own, are a compliance failure rather than a way
    /// in. `None` for a version still in good standing.
    pub const fn severity(self) -> Option<Severity> {
        match self {
            Self::Ssl30 => Some(Severity::High),
            Self::Tls10 | Self::Tls11 => Some(Severity::Medium),
            Self::Tls12 | Self::Tls13 => None,
        }
    }

    /// The document that withdrew this version, for a finding that has to cite
    /// one. `None` for a version still in good standing.
    pub const fn deprecated_by(self) -> Option<&'static str> {
        match self {
            Self::Ssl30 => Some("RFC 7568"),
            Self::Tls10 | Self::Tls11 => Some("RFC 8996"),
            Self::Tls12 | Self::Tls13 => None,
        }
    }
}

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

/// The error [`TlsVersion::from_str`] returns, naming the versions that would
/// have worked.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "unknown TLS version '{input}', expected one of: {}",
    TlsVersion::expected()
)]
pub struct UnknownTlsVersion {
    /// What the caller wrote.
    pub input: String,
}

impl TlsVersion {
    /// The accepted names, comma-separated, oldest first.
    fn expected() -> String {
        Self::ALL
            .iter()
            .map(|version| version.name())
            .collect::<Vec<_>>()
            .join(", ")
    }
}

impl FromStr for TlsVersion {
    type Err = UnknownTlsVersion;

    /// Parses a version by the name it prints, ignoring case and surrounding
    /// space, so a report read back names the same version it recorded.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let name = s.trim().to_ascii_lowercase();
        Self::ALL
            .into_iter()
            .find(|version| version.name().to_ascii_lowercase() == name)
            .ok_or_else(|| UnknownTlsVersion {
                input: s.to_string(),
            })
    }
}

// ---------------------------------------------------------------------------
// What a suite is made of
// ---------------------------------------------------------------------------

/// How a suite establishes the shared secret.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum KeyExchange {
    /// Ephemeral elliptic-curve Diffie-Hellman. Forward secret.
    Ecdhe,
    /// Ephemeral finite-field Diffie-Hellman. Forward secret, and the one Logjam
    /// is about where the group is small.
    Dhe,
    /// The client encrypts the premaster secret to the server's long-term RSA
    /// key. Not forward secret: one key recovered later decrypts every session
    /// ever recorded.
    Rsa,
    /// Static elliptic-curve Diffie-Hellman, the server's share fixed in its
    /// certificate. Not forward secret.
    Ecdh,
    /// Anonymous Diffie-Hellman, finite-field or elliptic-curve. Forward secret
    /// and worthless: nothing authenticates the peer, so anyone in the path is
    /// the peer.
    Anonymous,
    /// TLS 1.3, where key exchange is negotiated by extension and is not part of
    /// the suite at all. Always ephemeral.
    Negotiated,
}

impl KeyExchange {
    /// Whether a key recovered afterwards leaves past sessions unreadable.
    pub const fn is_forward_secret(self) -> bool {
        matches!(
            self,
            Self::Ecdhe | Self::Dhe | Self::Anonymous | Self::Negotiated
        )
    }
}

/// What proves the server is who it claims to be.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Authentication {
    /// An RSA signature or an RSA key exchange against the certificate's key.
    Rsa,
    /// An ECDSA signature.
    Ecdsa,
    /// A DSA signature, under the name TLS gives it. Effectively extinct, and
    /// bound to SHA-1 in every suite that carries it.
    Dss,
    /// Nothing at all. The suite completes a handshake with a peer that proved
    /// nothing, which makes the channel confidential against a passive observer
    /// and transparent to an active one.
    Anonymous,
    /// TLS 1.3, where the signature algorithm is negotiated by extension rather
    /// than fixed by the suite.
    Negotiated,
}

/// What encrypts the records.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BulkCipher {
    /// AES in Galois/Counter mode, 128- or 256-bit. Authenticated encryption.
    AesGcm(u16),
    /// AES in CCM mode. Authenticated encryption, and the shortened-tag variant
    /// is the one worth telling apart.
    AesCcm {
        /// The key size in bits.
        bits: u16,
        /// Whether the authentication tag is truncated to eight bytes.
        short_tag: bool,
    },
    /// ChaCha20-Poly1305. Authenticated encryption.
    ChaCha20Poly1305,
    /// AES in CBC mode with a separate MAC. Sound in principle and the source of
    /// BEAST, Lucky13 and every padding-oracle variant in practice.
    AesCbc(u16),
    /// Camellia in CBC mode. The same structural problem as AES-CBC, with far
    /// less scrutiny behind the primitive.
    CamelliaCbc(u16),
    /// Triple DES. A 64-bit block, which is what Sweet32 (CVE-2016-2183) turns
    /// into a plaintext recovery against a long-lived connection.
    TripleDes,
    /// Single DES. A 56-bit key, brute-forced in public since 1998.
    Des,
    /// RC4. Prohibited by RFC 7465: its keystream is biased and the biases
    /// recover plaintext from enough sessions.
    Rc4,
    /// SEED in CBC mode, a Korean national cipher.
    SeedCbc,
    /// IDEA in CBC mode. A 64-bit block, so Sweet32 applies here too.
    IdeaCbc,
    /// No encryption at all. The handshake authenticates and the records go out
    /// in the clear.
    Null,
}

impl BulkCipher {
    /// Whether the cipher authenticates its own records, so the suite needs no
    /// separate MAC.
    pub const fn is_aead(self) -> bool {
        matches!(
            self,
            Self::AesGcm(_) | Self::AesCcm { .. } | Self::ChaCha20Poly1305
        )
    }

    /// Whether records are encrypted in cipher-block-chaining mode, which is
    /// what every padding oracle in TLS has needed.
    pub const fn is_cbc(self) -> bool {
        matches!(
            self,
            Self::AesCbc(_)
                | Self::CamelliaCbc(_)
                | Self::TripleDes
                | Self::Des
                | Self::SeedCbc
                | Self::IdeaCbc
        )
    }

    /// Whether the block is 64 bits, which is the precondition for Sweet32.
    pub const fn has_64_bit_block(self) -> bool {
        matches!(self, Self::TripleDes | Self::Des | Self::IdeaCbc)
    }
}

/// What authenticates a record where the cipher does not.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Mac {
    /// The cipher authenticates its own records; the suite carries no separate
    /// MAC. The hash named in an AEAD suite is the one its key schedule uses,
    /// not a record MAC.
    Aead,
    /// HMAC-MD5. Collision resistance gone since 2004, and unfit even where a
    /// MAC needs less than that.
    Md5,
    /// HMAC-SHA-1. Not broken as a MAC, and carried only by suites old enough to
    /// have other problems.
    Sha1,
    /// HMAC-SHA-256.
    Sha256,
    /// HMAC-SHA-384.
    Sha384,
    /// No integrity protection whatsoever.
    Null,
}

// ---------------------------------------------------------------------------
// What is wrong with a suite
// ---------------------------------------------------------------------------

/// One thing wrong with a cipher suite, in the terms a report states it.
///
/// A suite may carry several: `TLS_RSA_EXPORT_WITH_RC4_40_MD5` is export-grade,
/// uses RC4, has no forward secrecy and MACs with MD5, and a reader deciding
/// what to do about it is served by all four rather than by whichever one an
/// engine happened to rank first.
///
/// Ordered by how much each costs the endpoint, so
/// [`CipherSuite::worst_fault`] is a comparison rather than a table.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SuiteFault {
    /// The key exchange is not ephemeral, so a long-term key recovered at any
    /// point in the future decrypts every session recorded before it.
    NoForwardSecrecy,
    /// Records are authenticated with HMAC-SHA-1.
    Sha1Mac,
    /// Records are encrypted in CBC mode with a separate MAC, the construction
    /// behind BEAST, Lucky13 and the padding oracles.
    CbcMode,
    /// The block cipher has a 64-bit block, which Sweet32 (CVE-2016-2183) turns
    /// into plaintext recovery over a long-lived connection.
    SmallBlock,
    /// Records are encrypted with RC4, which RFC 7465 prohibits.
    Rc4,
    /// Records are authenticated with HMAC-MD5.
    Md5Mac,
    /// The key is deliberately shortened to the length an export regulation once
    /// required. FREAK and Logjam are both about servers that still offer these.
    Export,
    /// Nothing authenticates the peer, so an active attacker in the path is
    /// indistinguishable from the server.
    Anonymous,
    /// Records are not encrypted at all.
    NullCipher,
}

impl SuiteFault {
    /// Every fault this build recognises, least costly first.
    pub const ALL: [Self; 9] = [
        Self::NoForwardSecrecy,
        Self::Sha1Mac,
        Self::CbcMode,
        Self::SmallBlock,
        Self::Rc4,
        Self::Md5Mac,
        Self::Export,
        Self::Anonymous,
        Self::NullCipher,
    ];

    /// The name this fault is written under wherever it reaches text.
    pub const fn name(self) -> &'static str {
        match self {
            Self::NoForwardSecrecy => "no_forward_secrecy",
            Self::Sha1Mac => "sha1_mac",
            Self::CbcMode => "cbc_mode",
            Self::SmallBlock => "small_block",
            Self::Rc4 => "rc4",
            Self::Md5Mac => "md5_mac",
            Self::Export => "export_grade",
            Self::Anonymous => "anonymous",
            Self::NullCipher => "null_cipher",
        }
    }

    /// One sentence a report can print beside the suite, saying what the fault
    /// costs rather than restating its name.
    pub const fn summary(self) -> &'static str {
        match self {
            Self::NoForwardSecrecy => {
                "the server's long-term key decrypts every session recorded under it"
            }
            Self::Sha1Mac => "records are authenticated with HMAC-SHA-1",
            Self::CbcMode => "CBC with a separate MAC, the construction behind Lucky13 and BEAST",
            Self::SmallBlock => "a 64-bit block, which Sweet32 recovers plaintext from",
            Self::Rc4 => "RC4, prohibited by RFC 7465",
            Self::Md5Mac => "records are authenticated with HMAC-MD5",
            Self::Export => "a deliberately shortened key, from the export era",
            Self::Anonymous => "nothing authenticates the server",
            Self::NullCipher => "records are not encrypted",
        }
    }

    /// How much a report should make of an endpoint that accepts a suite
    /// carrying this fault.
    ///
    /// Graded against what the fault buys somebody who is already in a position
    /// to use it, which is what separates the three tiers here. The top tier
    /// needs a position in the path and then hands over the traffic or the
    /// identity; the middle needs a position and a great deal of patience; the
    /// bottom is a hardening step left undone.
    ///
    /// Nothing here reaches [`Critical`](Severity::Critical). Every fault below
    /// costs an attacker a position on the network first, and the crate reserves
    /// that level for what needs nothing the internet does not already have.
    pub const fn severity(self) -> Severity {
        match self {
            // The channel is not what it claims to be at all: unencrypted, or
            // authenticated by nobody, or shortened to a length that has been
            // brute-forceable for thirty years.
            Self::NullCipher | Self::Anonymous | Self::Export => Severity::High,
            // Published attacks that work, and need a great deal of traffic or a
            // very long-lived connection to do it.
            Self::Rc4 | Self::SmallBlock | Self::Md5Mac => Severity::Medium,
            // Structural weaknesses worth removing, none of which is a way in on
            // its own.
            Self::CbcMode | Self::Sha1Mac | Self::NoForwardSecrecy => Severity::Low,
        }
    }

    /// Whether this fault alone makes the suite unfit for use, rather than
    /// merely worth replacing.
    ///
    /// The line between [`SuiteStrength::Weak`] and
    /// [`SuiteStrength::Insecure`]: below it a suite has a structural weakness
    /// somebody should plan to remove, and at or above it the suite provides
    /// materially less than it appears to.
    pub const fn is_disqualifying(self) -> bool {
        matches!(
            self,
            Self::SmallBlock
                | Self::Rc4
                | Self::Md5Mac
                | Self::Export
                | Self::Anonymous
                | Self::NullCipher
        )
    }
}

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

/// How much a suite is worth, in three steps a report can act on.
///
/// Derived from [`CipherSuite::faults`] and never stored, so a suite added to
/// the registry is graded by the same rule as every other one.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum SuiteStrength {
    /// Authenticated encryption with forward secrecy, and nothing against it.
    Strong,
    /// Usable, with a structural weakness worth planning out: no forward
    /// secrecy, CBC mode, or a SHA-1 MAC.
    Weak,
    /// Provides materially less than it appears to. Somebody should have removed
    /// it already.
    Insecure,
}

impl SuiteStrength {
    /// Every grade, strongest first.
    pub const ALL: [Self; 3] = [Self::Strong, Self::Weak, Self::Insecure];

    /// The name this grade is written under wherever it reaches text.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Strong => "strong",
            Self::Weak => "weak",
            Self::Insecure => "insecure",
        }
    }
}

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

// ---------------------------------------------------------------------------
// The suite itself
// ---------------------------------------------------------------------------

/// One cipher suite: the number it is offered under, the name it is known by,
/// and the four parts that decide what it is worth.
///
/// Construction is closed to the registry below. A suite assembled by hand could
/// name one thing and describe another, and every finding this module produces
/// rests on the name and the parts agreeing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CipherSuite {
    code: u16,
    name: &'static str,
    kex: KeyExchange,
    auth: Authentication,
    cipher: BulkCipher,
    mac: Mac,
    export: bool,
}

impl CipherSuite {
    /// The two-byte number this suite is offered and selected under.
    pub const fn code(self) -> u16 {
        self.code
    }

    /// The name IANA registers it under, which is the name every other tool
    /// prints.
    pub const fn name(self) -> &'static str {
        self.name
    }

    /// How the shared secret is established.
    pub const fn key_exchange(self) -> KeyExchange {
        self.kex
    }

    /// What proves the server's identity.
    pub const fn authentication(self) -> Authentication {
        self.auth
    }

    /// What encrypts the records.
    pub const fn bulk_cipher(self) -> BulkCipher {
        self.cipher
    }

    /// What authenticates them, where the cipher does not.
    pub const fn mac(self) -> Mac {
        self.mac
    }

    /// Whether the key is deliberately shortened to an export-era length.
    pub const fn is_export(self) -> bool {
        self.export
    }

    /// Whether a key recovered later leaves past sessions unreadable.
    pub const fn is_forward_secret(self) -> bool {
        self.kex.is_forward_secret()
    }

    /// Whether the suite carries this fault.
    ///
    /// Read off the parts every time rather than from a table beside them, so a
    /// suite added to the registry is judged by the same rule as the rest and
    /// cannot arrive ungraded.
    pub const fn has_fault(self, fault: SuiteFault) -> bool {
        match fault {
            // Anonymous key exchange is forward secret and proves nothing, so it
            // is reported under its own fault rather than this one.
            SuiteFault::NoForwardSecrecy => !self.kex.is_forward_secret(),
            SuiteFault::Sha1Mac => matches!(self.mac, Mac::Sha1),
            SuiteFault::CbcMode => self.cipher.is_cbc(),
            SuiteFault::SmallBlock => self.cipher.has_64_bit_block(),
            SuiteFault::Rc4 => matches!(self.cipher, BulkCipher::Rc4),
            SuiteFault::Md5Mac => matches!(self.mac, Mac::Md5),
            SuiteFault::Export => self.export,
            SuiteFault::Anonymous => matches!(self.auth, Authentication::Anonymous),
            SuiteFault::NullCipher => matches!(self.cipher, BulkCipher::Null),
        }
    }

    /// Everything wrong with this suite, least costly first. Empty for a suite
    /// with nothing against it.
    pub fn faults(self) -> Vec<SuiteFault> {
        SuiteFault::ALL
            .into_iter()
            .filter(|fault| self.has_fault(*fault))
            .collect()
    }

    /// The costliest thing wrong with this suite, or `None` for one with
    /// nothing against it.
    pub fn worst_fault(self) -> Option<SuiteFault> {
        SuiteFault::ALL
            .into_iter()
            .rev()
            .find(|fault| self.has_fault(*fault))
    }

    /// What the suite is worth, from its faults.
    ///
    /// A suite with no fault is [`Strong`](SuiteStrength::Strong); one whose
    /// worst fault is disqualifying is [`Insecure`](SuiteStrength::Insecure);
    /// anything else is [`Weak`](SuiteStrength::Weak).
    pub fn strength(self) -> SuiteStrength {
        match self.worst_fault() {
            None => SuiteStrength::Strong,
            Some(fault) if fault.is_disqualifying() => SuiteStrength::Insecure,
            Some(_) => SuiteStrength::Weak,
        }
    }

    /// Whether this suite can be offered under `version`.
    ///
    /// The two families do not mix. RFC 8446 §B.4 gives TLS 1.3 its own suites,
    /// which name only the AEAD and the hash because everything else moved into
    /// extensions; offering one under TLS 1.2 names a suite that version has
    /// never heard of, and offering a 1.2 suite under 1.3 is equally meaningless.
    /// An enumeration that mixed them would report a whole version unsupported
    /// on the strength of having asked the wrong question.
    pub const fn is_offered_under(self, version: TlsVersion) -> bool {
        let tls13_suite = matches!(self.kex, KeyExchange::Negotiated);
        match version {
            TlsVersion::Tls13 => tls13_suite,
            // A suite whose MAC is SHA-256 or SHA-384 needs the PRF that arrived
            // with TLS 1.2 (RFC 5246 §5), and so does every AEAD suite. Offering
            // one to a 1.0 or 1.1 server asks for something the version cannot
            // express.
            TlsVersion::Ssl30 | TlsVersion::Tls10 | TlsVersion::Tls11 => {
                !tls13_suite && matches!(self.mac, Mac::Md5 | Mac::Sha1 | Mac::Null)
            }
            TlsVersion::Tls12 => !tls13_suite,
        }
    }

    /// The suite a wire number names, or `None` for one this build does not
    /// carry.
    ///
    /// A server selecting a number absent from [`ALL`](Self::ALL) has selected
    /// something it was never offered, which an enumeration treats as the end of
    /// that version rather than as a suite.
    pub fn from_code(code: u16) -> Option<Self> {
        Self::ALL.into_iter().find(|suite| suite.code == code)
    }
}

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

/// Builds one registry entry, so that a row is its wire number, its name and its
/// four parts and nothing else can be written between them.
macro_rules! suite {
    ($code:literal, $name:literal, $kex:expr, $auth:expr, $cipher:expr, $mac:expr) => {
        CipherSuite {
            code: $code,
            name: $name,
            kex: $kex,
            auth: $auth,
            cipher: $cipher,
            mac: $mac,
            export: false,
        }
    };
    (export $code:literal, $name:literal, $kex:expr, $auth:expr, $cipher:expr, $mac:expr) => {
        CipherSuite {
            code: $code,
            name: $name,
            kex: $kex,
            auth: $auth,
            cipher: $cipher,
            mac: $mac,
            export: true,
        }
    };
}

use Authentication as A;
use BulkCipher as C;
use KeyExchange as K;
use Mac as M;

impl CipherSuite {
    /// Every suite a scan offers, grouped by the document that defines it.
    ///
    /// Curated rather than complete; see the module documentation for the
    /// criterion. Ordered strongest first within each group, which is the order
    /// they go into a ClientHello: a server with its own preference ignores the
    /// order, and one that takes the client's should be handed the best suite it
    /// can accept rather than the worst.
    pub const ALL: [Self; 85] = [
        // ── TLS 1.3 (RFC 8446 §B.4) ──────────────────────────────────────────
        // Named for their AEAD and hash alone: key exchange and authentication
        // moved into extensions, so they are properties of the connection rather
        // than of the suite.
        suite!(
            0x1302,
            "TLS_AES_256_GCM_SHA384",
            K::Negotiated,
            A::Negotiated,
            C::AesGcm(256),
            M::Aead
        ),
        suite!(
            0x1303,
            "TLS_CHACHA20_POLY1305_SHA256",
            K::Negotiated,
            A::Negotiated,
            C::ChaCha20Poly1305,
            M::Aead
        ),
        suite!(
            0x1301,
            "TLS_AES_128_GCM_SHA256",
            K::Negotiated,
            A::Negotiated,
            C::AesGcm(128),
            M::Aead
        ),
        suite!(
            0x1304,
            "TLS_AES_128_CCM_SHA256",
            K::Negotiated,
            A::Negotiated,
            C::AesCcm {
                bits: 128,
                short_tag: false
            },
            M::Aead
        ),
        suite!(
            0x1305,
            "TLS_AES_128_CCM_8_SHA256",
            K::Negotiated,
            A::Negotiated,
            C::AesCcm {
                bits: 128,
                short_tag: true
            },
            M::Aead
        ),
        // ── ECDHE with AEAD (RFC 5289, RFC 7905) ─────────────────────────────
        // What a current TLS 1.2 deployment should be negotiating and nothing
        // else.
        suite!(
            0xC030,
            "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
            K::Ecdhe,
            A::Rsa,
            C::AesGcm(256),
            M::Aead
        ),
        suite!(
            0xC02C,
            "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
            K::Ecdhe,
            A::Ecdsa,
            C::AesGcm(256),
            M::Aead
        ),
        suite!(
            0xC02F,
            "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
            K::Ecdhe,
            A::Rsa,
            C::AesGcm(128),
            M::Aead
        ),
        suite!(
            0xC02B,
            "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
            K::Ecdhe,
            A::Ecdsa,
            C::AesGcm(128),
            M::Aead
        ),
        suite!(
            0xCCA8,
            "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
            K::Ecdhe,
            A::Rsa,
            C::ChaCha20Poly1305,
            M::Aead
        ),
        suite!(
            0xCCA9,
            "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
            K::Ecdhe,
            A::Ecdsa,
            C::ChaCha20Poly1305,
            M::Aead
        ),
        // ── DHE with AEAD (RFC 5288, RFC 7905) ───────────────────────────────
        suite!(
            0x009F,
            "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384",
            K::Dhe,
            A::Rsa,
            C::AesGcm(256),
            M::Aead
        ),
        suite!(
            0x009E,
            "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
            K::Dhe,
            A::Rsa,
            C::AesGcm(128),
            M::Aead
        ),
        suite!(
            0xCCAA,
            "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
            K::Dhe,
            A::Rsa,
            C::ChaCha20Poly1305,
            M::Aead
        ),
        // ── Static RSA with AEAD (RFC 5288) ──────────────────────────────────
        // Modern encryption on a key exchange that has none of its own: the
        // records are fine and the secrecy is only as durable as the server's
        // private key.
        suite!(
            0x009D,
            "TLS_RSA_WITH_AES_256_GCM_SHA384",
            K::Rsa,
            A::Rsa,
            C::AesGcm(256),
            M::Aead
        ),
        suite!(
            0x009C,
            "TLS_RSA_WITH_AES_128_GCM_SHA256",
            K::Rsa,
            A::Rsa,
            C::AesGcm(128),
            M::Aead
        ),
        // ── ECDHE with CBC and a SHA-2 MAC (RFC 5289) ────────────────────────
        suite!(
            0xC028,
            "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384",
            K::Ecdhe,
            A::Rsa,
            C::AesCbc(256),
            M::Sha384
        ),
        suite!(
            0xC024,
            "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384",
            K::Ecdhe,
            A::Ecdsa,
            C::AesCbc(256),
            M::Sha384
        ),
        suite!(
            0xC027,
            "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
            K::Ecdhe,
            A::Rsa,
            C::AesCbc(128),
            M::Sha256
        ),
        suite!(
            0xC023,
            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
            K::Ecdhe,
            A::Ecdsa,
            C::AesCbc(128),
            M::Sha256
        ),
        // ── DHE and static RSA with CBC and a SHA-2 MAC (RFC 5246) ───────────
        suite!(
            0x006B,
            "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256",
            K::Dhe,
            A::Rsa,
            C::AesCbc(256),
            M::Sha256
        ),
        suite!(
            0x0067,
            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256",
            K::Dhe,
            A::Rsa,
            C::AesCbc(128),
            M::Sha256
        ),
        suite!(
            0x003D,
            "TLS_RSA_WITH_AES_256_CBC_SHA256",
            K::Rsa,
            A::Rsa,
            C::AesCbc(256),
            M::Sha256
        ),
        suite!(
            0x003C,
            "TLS_RSA_WITH_AES_128_CBC_SHA256",
            K::Rsa,
            A::Rsa,
            C::AesCbc(128),
            M::Sha256
        ),
        suite!(
            0x006A,
            "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256",
            K::Dhe,
            A::Dss,
            C::AesCbc(256),
            M::Sha256
        ),
        suite!(
            0x0040,
            "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256",
            K::Dhe,
            A::Dss,
            C::AesCbc(128),
            M::Sha256
        ),
        // ── CBC with a SHA-1 MAC (RFC 5246, RFC 4492) ────────────────────────
        // The floor a great many deployments still sit on, and the reason a
        // report needs the MAC as well as the cipher.
        suite!(
            0xC014,
            "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
            K::Ecdhe,
            A::Rsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0xC00A,
            "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA",
            K::Ecdhe,
            A::Ecdsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0xC013,
            "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
            K::Ecdhe,
            A::Rsa,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0xC009,
            "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA",
            K::Ecdhe,
            A::Ecdsa,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0x0039,
            "TLS_DHE_RSA_WITH_AES_256_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0x0033,
            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0x0038,
            "TLS_DHE_DSS_WITH_AES_256_CBC_SHA",
            K::Dhe,
            A::Dss,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0x0032,
            "TLS_DHE_DSS_WITH_AES_128_CBC_SHA",
            K::Dhe,
            A::Dss,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0x0035,
            "TLS_RSA_WITH_AES_256_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0x002F,
            "TLS_RSA_WITH_AES_128_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::AesCbc(128),
            M::Sha1
        ),
        // ── Static ECDH (RFC 4492) ───────────────────────────────────────────
        // The server's Diffie-Hellman share fixed in its certificate, so the
        // exchange looks ephemeral and is not.
        suite!(
            0xC00F,
            "TLS_ECDH_RSA_WITH_AES_256_CBC_SHA",
            K::Ecdh,
            A::Rsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0xC00E,
            "TLS_ECDH_RSA_WITH_AES_128_CBC_SHA",
            K::Ecdh,
            A::Rsa,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0xC005,
            "TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA",
            K::Ecdh,
            A::Ecdsa,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0xC004,
            "TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA",
            K::Ecdh,
            A::Ecdsa,
            C::AesCbc(128),
            M::Sha1
        ),
        // ── Camellia and SEED (RFC 5932, RFC 4162) ───────────────────────────
        suite!(
            0x0088,
            "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::CamelliaCbc(256),
            M::Sha1
        ),
        suite!(
            0x0084,
            "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::CamelliaCbc(256),
            M::Sha1
        ),
        suite!(
            0x0045,
            "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::CamelliaCbc(128),
            M::Sha1
        ),
        suite!(
            0x0041,
            "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::CamelliaCbc(128),
            M::Sha1
        ),
        suite!(
            0x0096,
            "TLS_RSA_WITH_SEED_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::SeedCbc,
            M::Sha1
        ),
        // ── Triple DES (RFC 5246, RFC 4492) ──────────────────────────────────
        // A 64-bit block, and Sweet32 is a practical attack rather than a
        // theoretical one.
        suite!(
            0xC012,
            "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
            K::Ecdhe,
            A::Rsa,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0xC008,
            "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA",
            K::Ecdhe,
            A::Ecdsa,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0x0016,
            "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0x0013,
            "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA",
            K::Dhe,
            A::Dss,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0x000A,
            "TLS_RSA_WITH_3DES_EDE_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0xC00D,
            "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA",
            K::Ecdh,
            A::Rsa,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0x0007,
            "TLS_RSA_WITH_IDEA_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::IdeaCbc,
            M::Sha1
        ),
        // ── RC4 (RFC 7465 prohibits every one of these) ──────────────────────
        suite!(
            0xC011,
            "TLS_ECDHE_RSA_WITH_RC4_128_SHA",
            K::Ecdhe,
            A::Rsa,
            C::Rc4,
            M::Sha1
        ),
        suite!(
            0xC007,
            "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA",
            K::Ecdhe,
            A::Ecdsa,
            C::Rc4,
            M::Sha1
        ),
        suite!(
            0x0005,
            "TLS_RSA_WITH_RC4_128_SHA",
            K::Rsa,
            A::Rsa,
            C::Rc4,
            M::Sha1
        ),
        suite!(
            0x0004,
            "TLS_RSA_WITH_RC4_128_MD5",
            K::Rsa,
            A::Rsa,
            C::Rc4,
            M::Md5
        ),
        suite!(
            0xC016,
            "TLS_ECDH_anon_WITH_RC4_128_SHA",
            K::Anonymous,
            A::Anonymous,
            C::Rc4,
            M::Sha1
        ),
        suite!(
            0x0018,
            "TLS_DH_anon_WITH_RC4_128_MD5",
            K::Anonymous,
            A::Anonymous,
            C::Rc4,
            M::Md5
        ),
        // ── Anonymous key exchange (RFC 5246 §A.5, RFC 4492) ─────────────────
        // Confidential against a passive observer and transparent to an active
        // one, which is the worse of the two to be wrong about.
        suite!(
            0x006D,
            "TLS_DH_anon_WITH_AES_256_CBC_SHA256",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(256),
            M::Sha256
        ),
        suite!(
            0x006C,
            "TLS_DH_anon_WITH_AES_128_CBC_SHA256",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(128),
            M::Sha256
        ),
        suite!(
            0x003A,
            "TLS_DH_anon_WITH_AES_256_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0x0034,
            "TLS_DH_anon_WITH_AES_128_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0xC019,
            "TLS_ECDH_anon_WITH_AES_256_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(256),
            M::Sha1
        ),
        suite!(
            0xC018,
            "TLS_ECDH_anon_WITH_AES_128_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::AesCbc(128),
            M::Sha1
        ),
        suite!(
            0x001B,
            "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::TripleDes,
            M::Sha1
        ),
        suite!(
            0xC017,
            "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::TripleDes,
            M::Sha1
        ),
        // ── No encryption (RFC 5246, RFC 4492) ───────────────────────────────
        // A handshake that authenticates and then sends everything in the clear.
        // Offered by more management interfaces than anyone expects.
        suite!(
            0x003B,
            "TLS_RSA_WITH_NULL_SHA256",
            K::Rsa,
            A::Rsa,
            C::Null,
            M::Sha256
        ),
        suite!(
            0x0002,
            "TLS_RSA_WITH_NULL_SHA",
            K::Rsa,
            A::Rsa,
            C::Null,
            M::Sha1
        ),
        suite!(
            0x0001,
            "TLS_RSA_WITH_NULL_MD5",
            K::Rsa,
            A::Rsa,
            C::Null,
            M::Md5
        ),
        suite!(
            0xC010,
            "TLS_ECDHE_RSA_WITH_NULL_SHA",
            K::Ecdhe,
            A::Rsa,
            C::Null,
            M::Sha1
        ),
        suite!(
            0xC006,
            "TLS_ECDHE_ECDSA_WITH_NULL_SHA",
            K::Ecdhe,
            A::Ecdsa,
            C::Null,
            M::Sha1
        ),
        suite!(
            0xC001,
            "TLS_ECDH_ECDSA_WITH_NULL_SHA",
            K::Ecdh,
            A::Ecdsa,
            C::Null,
            M::Sha1
        ),
        suite!(
            0xC00B,
            "TLS_ECDH_RSA_WITH_NULL_SHA",
            K::Ecdh,
            A::Rsa,
            C::Null,
            M::Sha1
        ),
        suite!(
            0xC015,
            "TLS_ECDH_anon_WITH_NULL_SHA",
            K::Anonymous,
            A::Anonymous,
            C::Null,
            M::Sha1
        ),
        // ── Export grade (RFC 4346 §A.5, withdrawn in RFC 5246) ──────────────
        // Keys shortened to satisfy an export regulation that has not existed
        // since 2000. FREAK and Logjam are both about servers that still offer
        // them.
        suite!(export 0x0003, "TLS_RSA_EXPORT_WITH_RC4_40_MD5", K::Rsa, A::Rsa, C::Rc4, M::Md5),
        suite!(export 0x0006, "TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5", K::Rsa, A::Rsa, C::Des, M::Md5),
        suite!(export 0x0008, "TLS_RSA_EXPORT_WITH_DES40_CBC_SHA", K::Rsa, A::Rsa, C::Des, M::Sha1),
        suite!(export 0x0014, "TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", K::Dhe, A::Rsa, C::Des, M::Sha1),
        suite!(export 0x0011, "TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", K::Dhe, A::Dss, C::Des, M::Sha1),
        suite!(export 0x0017, "TLS_DH_anon_EXPORT_WITH_RC4_40_MD5", K::Anonymous, A::Anonymous, C::Rc4, M::Md5),
        suite!(export 0x0019, "TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA", K::Anonymous, A::Anonymous, C::Des, M::Sha1),
        // ── Single DES (RFC 4346 §A.5) ───────────────────────────────────────
        suite!(
            0x0009,
            "TLS_RSA_WITH_DES_CBC_SHA",
            K::Rsa,
            A::Rsa,
            C::Des,
            M::Sha1
        ),
        suite!(
            0x0015,
            "TLS_DHE_RSA_WITH_DES_CBC_SHA",
            K::Dhe,
            A::Rsa,
            C::Des,
            M::Sha1
        ),
        suite!(
            0x0012,
            "TLS_DHE_DSS_WITH_DES_CBC_SHA",
            K::Dhe,
            A::Dss,
            C::Des,
            M::Sha1
        ),
        suite!(
            0x001A,
            "TLS_DH_anon_WITH_DES_CBC_SHA",
            K::Anonymous,
            A::Anonymous,
            C::Des,
            M::Sha1
        ),
    ];

    /// Every suite that may be offered under `version`, in registry order.
    pub fn offered_under(version: TlsVersion) -> impl Iterator<Item = Self> {
        Self::ALL
            .into_iter()
            .filter(move |suite| suite.is_offered_under(version))
    }
}

// ---------------------------------------------------------------------------
// What an endpoint turned out to accept
// ---------------------------------------------------------------------------

/// What one endpoint accepted under one protocol version.
///
/// The suites are in the order the server chose them, which is worth keeping.
/// An enumeration offers its list strongest first and removes each suite as it
/// is selected, so a server with a preference of its own reveals it: the first
/// entry is that server's favourite among everything offered, not the scan's.
///
/// A server taking the *client's* preference produces the same list in the same
/// order, and nothing here tells the two apart. Separating them needs the offer
/// repeated in a second order, which is a question this does not yet ask.
#[must_use]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionSupport {
    version: TlsVersion,
    suites: Vec<CipherSuite>,
    unrecognised: Vec<u16>,
}

impl VersionSupport {
    /// Records that `version` was accepted, with the suites chosen under it.
    ///
    /// `unrecognised` holds any suite the server selected by a number
    /// [`CipherSuite::ALL`] does not carry. Kept rather than dropped: it is a
    /// server negotiating something this build cannot grade, and a reader who
    /// sees an empty suite list beside an accepted version would otherwise
    /// conclude the endpoint negotiated nothing.
    pub fn new(version: TlsVersion, suites: Vec<CipherSuite>, unrecognised: Vec<u16>) -> Self {
        Self {
            version,
            suites,
            unrecognised,
        }
    }

    /// The version this describes.
    pub fn version(&self) -> TlsVersion {
        self.version
    }

    /// The suites accepted under it, in the order the server chose them.
    pub fn suites(&self) -> &[CipherSuite] {
        &self.suites
    }

    /// Suites the server chose that this build does not carry, by number.
    pub fn unrecognised(&self) -> &[u16] {
        &self.unrecognised
    }

    /// The worst grade among the suites accepted here, or `None` where the
    /// version was accepted and no suite was ever named.
    pub fn weakest(&self) -> Option<SuiteStrength> {
        self.suites.iter().map(|suite| suite.strength()).max()
    }
}

/// What an endpoint accepts, version by version.
///
/// The answer a TLS enumeration exists to produce, and a different question from
/// the one a single handshake answers. [`Security`](super::port::Security)
/// records what *was* negotiated; this records what *would be*, which is what a
/// PCI scan, an ASV report or an internal audit is actually asking.
///
/// Empty for an endpoint that accepted nothing under any version, which is a
/// real outcome rather than a failure: a server refusing every offer is either
/// very strictly configured or was asked without the name it insists on. See
/// [`Offer::server_name`](crate::protocols::tls::Offer::server_name).
#[must_use]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TlsSupport {
    versions: Vec<VersionSupport>,
}

impl TlsSupport {
    /// An empty record, for an endpoint nothing has been established about yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds what one version turned out to accept, keeping the list oldest
    /// first however the caller walked them.
    pub fn record(&mut self, support: VersionSupport) {
        let at = self
            .versions
            .partition_point(|held| held.version < support.version);
        match self.versions.get(at) {
            Some(held) if held.version == support.version => self.versions[at] = support,
            _ => self.versions.insert(at, support),
        }
    }

    /// Builder form of [`record`](Self::record).
    pub fn accepting(mut self, support: VersionSupport) -> Self {
        self.record(support);
        self
    }

    /// Every version accepted, oldest first.
    pub fn versions(&self) -> &[VersionSupport] {
        &self.versions
    }

    /// Whether anything was established at all.
    pub fn is_empty(&self) -> bool {
        self.versions.is_empty()
    }

    /// Whether `version` was accepted.
    pub fn accepts(&self, version: TlsVersion) -> bool {
        self.versions.iter().any(|held| held.version == version)
    }

    /// The oldest version accepted, which is the one a report leads with: it is
    /// the floor an attacker gets to choose from.
    pub fn floor(&self) -> Option<TlsVersion> {
        self.versions.first().map(|held| held.version)
    }

    /// The newest version accepted.
    pub fn ceiling(&self) -> Option<TlsVersion> {
        self.versions.last().map(|held| held.version)
    }

    /// Every accepted version a standards body has withdrawn, oldest first.
    pub fn deprecated_versions(&self) -> impl Iterator<Item = TlsVersion> + '_ {
        self.versions
            .iter()
            .map(|held| held.version)
            .filter(|version| version.is_deprecated())
    }

    /// Every suite accepted anywhere, deduplicated, in registry order.
    ///
    /// For a reader asking what the endpoint will negotiate rather than what it
    /// will negotiate under which version.
    pub fn suites(&self) -> Vec<CipherSuite> {
        let mut all: Vec<CipherSuite> = self
            .versions
            .iter()
            .flat_map(|held| held.suites.iter().copied())
            .collect();
        all.sort_unstable_by_key(|suite| suite.code());
        all.dedup();
        all
    }

    /// The worst grade among every suite accepted anywhere, or `None` where no
    /// suite was named.
    pub fn weakest(&self) -> Option<SuiteStrength> {
        self.versions
            .iter()
            .filter_map(VersionSupport::weakest)
            .max()
    }

    /// Every distinct fault carried by any accepted suite, least costly first.
    ///
    /// What a finding is written from: a reader acts on "this endpoint still
    /// negotiates RC4" rather than on the nine suite names that establish it.
    pub fn faults(&self) -> Vec<SuiteFault> {
        SuiteFault::ALL
            .into_iter()
            .filter(|fault| {
                self.versions
                    .iter()
                    .flat_map(|held| held.suites.iter())
                    .any(|suite| suite.has_fault(*fault))
            })
            .collect()
    }
}

// ---------------------------------------------------------------------------
// What to report about it
// ---------------------------------------------------------------------------

/// The identity every finding this module produces is stamped with.
///
/// A built-in derivation rather than a dataset, so its identity is this build
/// and the rules compiled into it. The content hash is taken over the registry
/// itself, which means a suite added, removed or reclassified changes the hash
/// and two reports drawn by different rules can be told apart. The engine
/// version alone would not do that: the registry can move within a patch
/// release.
fn detection_id() -> DetectionId {
    static ID: OnceLock<DetectionId> = OnceLock::new();
    ID.get_or_init(|| {
        let version = env!("CARGO_PKG_VERSION")
            .parse::<Version>()
            .unwrap_or(Version::new(0, 0, 0));

        // The registry as a string, in declaration order: every number, name,
        // and derived grade. The grade is included so that a change to the fault
        // rules moves the hash even when no suite did.
        let mut census = String::with_capacity(CipherSuite::ALL.len() * 64);
        for suite in CipherSuite::ALL {
            use std::fmt::Write;
            let _ = write!(
                census,
                "{:04x}:{}:{};",
                suite.code(),
                suite.name(),
                suite.strength().name()
            );
        }
        let digest = ring::digest::digest(&ring::digest::SHA256, census.as_bytes());
        let mut hash = String::with_capacity(digest.as_ref().len() * 2);
        for byte in digest.as_ref() {
            use std::fmt::Write;
            let _ = write!(hash, "{byte:02x}");
        }

        DetectionId::new("zond:tls", version, hash).expect("the identifier is a non-empty literal")
    })
    .clone()
}

impl TlsSupport {
    /// Everything about this endpoint's configuration worth reporting, one
    /// finding per thing wrong with it.
    ///
    /// Grouped by the fault rather than by the suite, which is the difference
    /// between a report somebody reads and a list somebody scrolls past. An
    /// endpoint accepting nine RC4 suites has one problem, not nine, and the
    /// remedy is one line of configuration; the suite names are carried in the
    /// finding's excerpt for whoever needs to see them.
    ///
    /// A withdrawn version is its own finding, separately from whatever suites
    /// sit under it, because the two are fixed by different edits: one removes a
    /// protocol version and the other removes ciphers.
    ///
    /// Empty for an endpoint with nothing against it, which is the answer a
    /// clean scan should produce rather than an `Info` finding saying so.
    pub fn findings(&self) -> Vec<Finding> {
        let mut findings = Vec::new();

        for version in self.deprecated_versions() {
            let Some(severity) = version.severity() else {
                continue;
            };
            let withdrawn_by = version.deprecated_by().unwrap_or("a published standard");

            let Ok(finding) = Finding::new(
                detection_id(),
                format!("{version} is still accepted"),
                severity,
                // The server negotiated it. There is no inference between the
                // evidence and the claim.
                Confidence::Certain,
                DetectionClass::ActiveBenign,
            ) else {
                continue;
            };

            let mut finding = finding.with_excerpt(Excerpt::new(format!(
                "the endpoint completed a {version} negotiation; {withdrawn_by} withdrew it"
            )));
            if let Some(reference) = rfc_reference(withdrawn_by) {
                finding = finding.with_reference(reference);
            }
            findings.push(finding);
        }

        for fault in self.faults() {
            let carriers: Vec<&'static str> = self
                .versions
                .iter()
                .flat_map(|held| held.suites.iter())
                .filter(|suite| suite.has_fault(fault))
                .map(|suite| suite.name())
                .collect();

            let Ok(finding) = Finding::new(
                detection_id(),
                format!("cipher suites accepted with {}", fault.summary()),
                fault.severity(),
                Confidence::Certain,
                DetectionClass::ActiveBenign,
            ) else {
                continue;
            };

            let mut finding = finding.with_excerpt(Excerpt::new(format!(
                "{} of the accepted suites carry this: {}",
                carriers.len(),
                carriers.join(", ")
            )));
            if let Some(reference) = fault_reference(fault) {
                finding = finding.with_reference(reference);
            }
            findings.push(finding);
        }

        findings
    }
}

/// The reference a version's withdrawal cites, where the document is an RFC.
fn rfc_reference(document: &str) -> Option<Reference> {
    let number = document.strip_prefix("RFC ")?;
    Some(Reference::url(format!(
        "https://www.rfc-editor.org/rfc/rfc{number}"
    )))
}

/// The document a fault is best read against, where one says it plainly.
fn fault_reference(fault: SuiteFault) -> Option<Reference> {
    match fault {
        SuiteFault::Rc4 => Some(Reference::url("https://www.rfc-editor.org/rfc/rfc7465")),
        SuiteFault::SmallBlock => Reference::cve("CVE-2016-2183"),
        _ => None,
    }
}

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

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

    /// A number appearing twice would make one of the two unreachable through
    /// [`CipherSuite::from_code`], so a server selecting it would be reported as
    /// the wrong suite: the wrong name, and the wrong faults under it.
    #[test]
    fn every_suite_has_a_number_of_its_own() {
        let mut seen = BTreeSet::new();
        for suite in CipherSuite::ALL {
            assert!(
                seen.insert(suite.code()),
                "0x{:04X} is registered twice, the second as {}",
                suite.code(),
                suite.name()
            );
        }
    }

    /// The same for names, which is what a reader and a diff key on.
    #[test]
    fn every_suite_has_a_name_of_its_own() {
        let mut seen = BTreeSet::new();
        for suite in CipherSuite::ALL {
            assert!(seen.insert(suite.name()), "{} is registered twice", suite);
        }
    }

    /// The registry's own consistency check, and the one that earns its keep.
    ///
    /// An IANA suite name states its parts in order, so the name and the fields
    /// beside it are two statements of the same fact. A transcription error in
    /// the fields is otherwise invisible: the scan offers a real suite, a server
    /// accepts it, and the report names the right suite with the wrong faults
    /// under it, which is worse than not asking. This reads the name and holds
    /// the fields to it.
    ///
    /// It cannot check the number, which nothing but the registry states. The
    /// numbers are grouped by their defining document above so that a reader can.
    #[test]
    fn every_suite_describes_what_its_name_says() {
        for suite in CipherSuite::ALL {
            let name = suite.name();

            // TLS 1.3 names its AEAD and hash and nothing else, RFC 8446 §B.4.
            if matches!(suite.key_exchange(), KeyExchange::Negotiated) {
                assert!(
                    !name.contains("_WITH_"),
                    "{name} is a 1.3 suite and should not name a key exchange"
                );
                assert!(suite.bulk_cipher().is_aead(), "{name} must be AEAD");
                assert_eq!(suite.mac(), Mac::Aead, "{name} carries no separate MAC");
                continue;
            }

            let (kex_part, cipher_part) = name
                .strip_prefix("TLS_")
                .and_then(|rest| rest.split_once("_WITH_"))
                .unwrap_or_else(|| panic!("{name} is not an IANA suite name"));

            // Key exchange and authentication, which the name states together.
            let expected_kex = if kex_part.starts_with("ECDHE_") {
                KeyExchange::Ecdhe
            } else if kex_part.starts_with("DHE_") {
                KeyExchange::Dhe
            } else if kex_part.contains("anon") {
                KeyExchange::Anonymous
            } else if kex_part.starts_with("ECDH_") {
                KeyExchange::Ecdh
            } else {
                KeyExchange::Rsa
            };
            assert_eq!(suite.key_exchange(), expected_kex, "key exchange of {name}");

            let expected_auth = if kex_part.contains("anon") {
                Authentication::Anonymous
            } else if kex_part.contains("ECDSA") {
                Authentication::Ecdsa
            } else if kex_part.contains("DSS") {
                Authentication::Dss
            } else {
                Authentication::Rsa
            };
            assert_eq!(
                suite.authentication(),
                expected_auth,
                "authentication of {name}"
            );

            assert_eq!(
                suite.is_export(),
                kex_part.contains("EXPORT"),
                "export grade of {name}"
            );

            // The MAC is the last element of the name for every non-AEAD suite.
            let expected_mac = if cipher_part.ends_with("_SHA256") {
                Mac::Sha256
            } else if cipher_part.ends_with("_SHA384") {
                Mac::Sha384
            } else if cipher_part.ends_with("_SHA") {
                Mac::Sha1
            } else if cipher_part.ends_with("_MD5") {
                Mac::Md5
            } else {
                panic!("{name} names no MAC this test can read")
            };
            let expected_mac = match suite.bulk_cipher().is_aead() {
                true => Mac::Aead,
                false => expected_mac,
            };
            assert_eq!(suite.mac(), expected_mac, "MAC of {name}");

            // And the cipher, which the middle of the name states.
            let cipher = suite.bulk_cipher();
            let claims = |needle: &str| cipher_part.contains(needle);
            match cipher {
                C::AesGcm(bits) => {
                    assert!(claims("AES_") && claims("_GCM_"), "cipher of {name}");
                    assert!(claims(&bits.to_string()), "key size of {name}");
                }
                C::AesCbc(bits) => {
                    assert!(claims("AES_") && claims("_CBC_"), "cipher of {name}");
                    assert!(claims(&bits.to_string()), "key size of {name}");
                }
                C::CamelliaCbc(bits) => {
                    assert!(claims("CAMELLIA_") && claims("_CBC_"), "cipher of {name}");
                    assert!(claims(&bits.to_string()), "key size of {name}");
                }
                C::ChaCha20Poly1305 => assert!(claims("CHACHA20_POLY1305"), "cipher of {name}"),
                C::TripleDes => assert!(claims("3DES_EDE_CBC"), "cipher of {name}"),
                // RC2 is carried as DES: both are export-era block ciphers this
                // engine only needs to recognise and report, and neither is
                // worth a variant of its own.
                C::Des => assert!(
                    claims("DES") || claims("RC2"),
                    "cipher of {name} is not a DES-class cipher"
                ),
                C::Rc4 => assert!(claims("RC4_"), "cipher of {name}"),
                C::SeedCbc => assert!(claims("SEED_CBC"), "cipher of {name}"),
                C::IdeaCbc => assert!(claims("IDEA_CBC"), "cipher of {name}"),
                C::Null => assert!(claims("NULL"), "cipher of {name}"),
                C::AesCcm { .. } => panic!("{name} is a CCM suite outside TLS 1.3"),
            }
        }
    }

    /// The grading rule, stated once here so that a change to it is a change to
    /// a test rather than a silent reclassification of ninety suites.
    #[test]
    fn a_suite_is_graded_by_the_worst_thing_about_it() {
        let named = |name: &str| {
            CipherSuite::ALL
                .into_iter()
                .find(|suite| suite.name() == name)
                .unwrap_or_else(|| panic!("{name} is in the registry"))
        };

        // Nothing against it: AEAD over an ephemeral exchange.
        let strong = named("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384");
        assert_eq!(strong.strength(), SuiteStrength::Strong);
        assert!(strong.faults().is_empty());

        // Modern records, no forward secrecy. Usable, worth removing.
        let no_fs = named("TLS_RSA_WITH_AES_128_GCM_SHA256");
        assert_eq!(no_fs.strength(), SuiteStrength::Weak);
        assert_eq!(no_fs.faults(), vec![SuiteFault::NoForwardSecrecy]);

        // Ephemeral and CBC with a SHA-1 MAC: two faults, neither disqualifying.
        let cbc = named("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA");
        assert_eq!(cbc.strength(), SuiteStrength::Weak);
        assert_eq!(
            cbc.faults(),
            vec![SuiteFault::Sha1Mac, SuiteFault::CbcMode],
            "both faults are reported, not only the worst"
        );

        // A 64-bit block disqualifies whatever else is right about the suite.
        let sweet32 = named("TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA");
        assert_eq!(sweet32.strength(), SuiteStrength::Insecure);
        assert_eq!(sweet32.worst_fault(), Some(SuiteFault::SmallBlock));

        // And the ones that are simply broken.
        for name in [
            "TLS_RSA_WITH_RC4_128_SHA",
            "TLS_DH_anon_WITH_AES_128_CBC_SHA",
            "TLS_RSA_WITH_NULL_SHA",
            "TLS_RSA_EXPORT_WITH_RC4_40_MD5",
        ] {
            assert_eq!(
                named(name).strength(),
                SuiteStrength::Insecure,
                "{name} is not usable"
            );
        }
    }

    /// Anonymous suites are reported for what they are rather than filed under
    /// the missing forward secrecy they do not have: an anonymous exchange *is*
    /// ephemeral, and calling it "no forward secrecy" would be both wrong and
    /// the less alarming of the two things to say.
    #[test]
    fn an_anonymous_suite_is_not_reported_as_lacking_forward_secrecy() {
        let anon = CipherSuite::from_code(0x0034).expect("TLS_DH_anon_WITH_AES_128_CBC_SHA");
        assert!(anon.is_forward_secret());
        assert!(!anon.has_fault(SuiteFault::NoForwardSecrecy));
        assert!(anon.has_fault(SuiteFault::Anonymous));
    }

    /// The two families never mix, and the split is what keeps an enumeration
    /// from reporting a whole version unsupported because it asked with suites
    /// that version cannot express.
    #[test]
    fn each_version_is_offered_the_suites_it_can_express() {
        let thirteen: Vec<_> = CipherSuite::offered_under(TlsVersion::Tls13).collect();
        assert_eq!(thirteen.len(), 5, "RFC 8446 §B.4 defines five");
        assert!(thirteen.iter().all(
            |suite| suite.name().starts_with("TLS_A") || suite.name().starts_with("TLS_CHACHA")
        ));

        for version in [TlsVersion::Ssl30, TlsVersion::Tls10, TlsVersion::Tls11] {
            for suite in CipherSuite::offered_under(version) {
                assert!(
                    matches!(suite.mac(), Mac::Md5 | Mac::Sha1 | Mac::Null),
                    "{suite} needs the TLS 1.2 PRF and cannot be offered under {version}"
                );
            }
        }

        let twelve: Vec<_> = CipherSuite::offered_under(TlsVersion::Tls12).collect();
        assert_eq!(
            twelve.len(),
            CipherSuite::ALL.len() - 5,
            "everything but the 1.3 suites"
        );
    }

    /// Every version round-trips through its wire number and through its name,
    /// so a report read back names the version it recorded.
    #[test]
    fn every_version_round_trips_through_its_number_and_its_name() {
        for version in TlsVersion::ALL {
            assert_eq!(TlsVersion::from_code(version.code()), Some(version));
            assert_eq!(version.to_string().parse(), Ok(version));
        }
        assert_eq!(TlsVersion::from_code(0x0305), None);
        assert!("TLSv1.4".parse::<TlsVersion>().is_err());
    }

    /// The withdrawn versions are exactly the three that were withdrawn, and
    /// each names the document that did it.
    #[test]
    fn the_deprecated_versions_are_the_ones_a_standard_withdrew() {
        for version in TlsVersion::ALL {
            assert_eq!(
                version.is_deprecated(),
                version.deprecated_by().is_some(),
                "{version} must cite a document exactly when it is deprecated"
            );
        }
        assert_eq!(TlsVersion::Ssl30.deprecated_by(), Some("RFC 7568"));
        assert_eq!(TlsVersion::Tls10.deprecated_by(), Some("RFC 8996"));
        assert_eq!(TlsVersion::Tls11.deprecated_by(), Some("RFC 8996"));
        assert_eq!(TlsVersion::Tls12.deprecated_by(), None);
        assert_eq!(TlsVersion::Tls13.deprecated_by(), None);
    }

    /// Every suite is reachable by the number a server would select it with.
    #[test]
    fn every_suite_is_found_by_its_number() {
        for suite in CipherSuite::ALL {
            assert_eq!(CipherSuite::from_code(suite.code()), Some(suite));
        }
        assert_eq!(CipherSuite::from_code(0xFFFF), None);
    }

    /// A fault is disqualifying or it is not, and the grade follows from that
    /// alone. Stated as a property over the whole registry so a suite added
    /// later cannot land outside the rule.
    #[test]
    fn the_grade_follows_from_the_worst_fault_for_every_suite() {
        for suite in CipherSuite::ALL {
            let expected = match suite.worst_fault() {
                None => SuiteStrength::Strong,
                Some(fault) if fault.is_disqualifying() => SuiteStrength::Insecure,
                Some(_) => SuiteStrength::Weak,
            };
            assert_eq!(suite.strength(), expected, "grade of {suite}");

            // And the faults reported are exactly the ones the parts imply.
            for fault in suite.faults() {
                assert!(suite.has_fault(fault), "{suite} reported {fault} it lacks");
            }
        }
    }

    // ── What an enumeration turns into ───────────────────────────────────────

    fn suite(code: u16) -> CipherSuite {
        CipherSuite::from_code(code).expect("a suite in the registry")
    }

    /// The record keeps its versions oldest first however they were recorded,
    /// so a report's version list is in the same order for every endpoint and
    /// two scans diff cleanly.
    #[test]
    fn recorded_versions_are_ordered_oldest_first() {
        let support = TlsSupport::new()
            .accepting(VersionSupport::new(TlsVersion::Tls13, vec![], vec![]))
            .accepting(VersionSupport::new(TlsVersion::Tls10, vec![], vec![]))
            .accepting(VersionSupport::new(TlsVersion::Tls12, vec![], vec![]));

        let order: Vec<_> = support.versions().iter().map(|v| v.version()).collect();
        assert_eq!(
            order,
            vec![TlsVersion::Tls10, TlsVersion::Tls12, TlsVersion::Tls13]
        );
        assert_eq!(support.floor(), Some(TlsVersion::Tls10));
        assert_eq!(support.ceiling(), Some(TlsVersion::Tls13));
    }

    /// Recording a version twice replaces it rather than listing it twice: a
    /// second enumeration of one endpoint answers the same question.
    #[test]
    fn recording_a_version_twice_keeps_one_entry() {
        let mut support = TlsSupport::new();
        support.record(VersionSupport::new(TlsVersion::Tls12, vec![], vec![]));
        support.record(VersionSupport::new(
            TlsVersion::Tls12,
            vec![suite(0xC030)],
            vec![],
        ));

        assert_eq!(support.versions().len(), 1);
        assert_eq!(support.suites().len(), 1);
    }

    /// A suite accepted under two versions is one suite, and the faults it
    /// carries are reported once.
    #[test]
    fn a_suite_accepted_twice_is_counted_once() {
        let support = TlsSupport::new()
            .accepting(VersionSupport::new(
                TlsVersion::Tls11,
                vec![suite(0x002F)],
                vec![],
            ))
            .accepting(VersionSupport::new(
                TlsVersion::Tls12,
                vec![suite(0x002F)],
                vec![],
            ));

        assert_eq!(support.suites().len(), 1);
    }

    /// An endpoint with nothing against it produces no findings at all. A clean
    /// scan should be quiet rather than carry an `Info` saying it is clean.
    #[test]
    fn a_sound_endpoint_produces_no_findings() {
        let support = TlsSupport::new()
            .accepting(VersionSupport::new(
                TlsVersion::Tls13,
                vec![suite(0x1302)],
                vec![],
            ))
            .accepting(VersionSupport::new(
                TlsVersion::Tls12,
                vec![suite(0xC030), suite(0xC02B)],
                vec![],
            ));

        assert_eq!(support.weakest(), Some(SuiteStrength::Strong));
        assert!(support.faults().is_empty());
        assert!(support.findings().is_empty());
    }

    /// A withdrawn version is its own finding, separate from the suites under
    /// it: the two are fixed by different edits, one removing a protocol version
    /// and one removing ciphers.
    #[test]
    fn a_withdrawn_version_is_reported_on_its_own_terms() {
        let support = TlsSupport::new().accepting(VersionSupport::new(
            TlsVersion::Tls10,
            // Nothing wrong with the suite beyond what its era implies, so the
            // version finding cannot be confused with a suite finding.
            vec![suite(0x002F)],
            vec![],
        ));

        let findings = support.findings();
        let version_finding = findings
            .iter()
            .find(|finding| finding.title().contains("TLSv1.0"))
            .expect("the version is reported");

        assert_eq!(version_finding.severity(), Severity::Medium);
        assert!(
            version_finding
                .references()
                .any(|reference| matches!(reference, Reference::Url(url) if url.contains("8996"))),
            "the finding cites the document that withdrew the version"
        );
    }

    /// Nine RC4 suites are one problem and one line of configuration, so they
    /// are one finding with the suites in its excerpt rather than nine findings.
    #[test]
    fn one_fault_across_many_suites_is_one_finding() {
        let rc4: Vec<CipherSuite> = CipherSuite::ALL
            .into_iter()
            .filter(|suite| suite.has_fault(SuiteFault::Rc4) && !suite.is_export())
            .collect();
        assert!(rc4.len() > 3, "the registry carries several RC4 suites");

        let support = TlsSupport::new().accepting(VersionSupport::new(
            TlsVersion::Tls12,
            rc4.clone(),
            vec![],
        ));

        let rc4_findings: Vec<_> = support
            .findings()
            .into_iter()
            .filter(|finding| finding.title().contains("RC4"))
            .collect();

        assert_eq!(rc4_findings.len(), 1, "one problem, one finding");
        assert!(
            rc4_findings[0]
                .excerpt()
                .as_str()
                .contains("TLS_RSA_WITH_RC4_128_SHA"),
            "the suites are carried in the excerpt for whoever needs them"
        );
    }

    /// The severity a fault earns is the one the report prints, and the ceiling
    /// is deliberate: every fault here costs an attacker a position on the
    /// network first, which is not what this crate calls critical.
    #[test]
    fn no_tls_fault_is_reported_as_critical() {
        for fault in SuiteFault::ALL {
            assert!(
                fault.severity() < Severity::Critical,
                "{fault} reached critical"
            );
        }
        assert_eq!(SuiteFault::NullCipher.severity(), Severity::High);
        assert_eq!(SuiteFault::Rc4.severity(), Severity::Medium);
        assert_eq!(SuiteFault::CbcMode.severity(), Severity::Low);
    }

    /// Every finding is stamped with the same identity, and the hash moves with
    /// the registry rather than only with the release: the rules can change
    /// inside a patch version and two reports have to be tellable apart.
    #[test]
    fn every_finding_carries_the_registry_it_was_drawn_from() {
        let support = TlsSupport::new().accepting(VersionSupport::new(
            TlsVersion::Ssl30,
            vec![suite(0x0004)],
            vec![],
        ));

        let findings = support.findings();
        assert!(!findings.is_empty());
        for finding in &findings {
            assert_eq!(finding.detection().id(), "zond:tls");
            assert_eq!(
                finding.detection().content_hash().len(),
                64,
                "a SHA-256 of the registry, in hex"
            );
        }
    }

    /// Every finding this produces survives being filed against one port.
    ///
    /// The assumption the whole reporting path rests on, and it is not obvious:
    /// a port deduplicates findings by claim, which is the producing detection's
    /// id paired with its first CVE or, failing that, its title. Every finding
    /// here carries the same detection id, so what keeps them apart is the
    /// title alone. Two faults whose summaries read the same, or two versions
    /// phrased alike, would collapse into one and the rest would be silently
    /// lost.
    #[test]
    fn every_finding_survives_being_filed_against_one_port() {
        use crate::model::port::{Port, PortState, Protocol};

        // A thoroughly bad endpoint: three withdrawn versions and a suite from
        // every fault class the registry can produce.
        let mut support = TlsSupport::new();
        for version in [TlsVersion::Ssl30, TlsVersion::Tls10, TlsVersion::Tls11] {
            let carriers: Vec<CipherSuite> = SuiteFault::ALL
                .into_iter()
                .filter_map(|fault| {
                    CipherSuite::offered_under(version).find(|suite| suite.has_fault(fault))
                })
                .collect();
            support.record(VersionSupport::new(version, carriers, vec![]));
        }

        let findings = support.findings();
        assert_eq!(
            findings.len(),
            support.faults().len() + 3,
            "one per fault, plus one per withdrawn version"
        );

        let mut port = Port::new(443, Protocol::Tcp, PortState::Open);
        for finding in findings.clone() {
            port.add_finding(finding);
        }

        assert_eq!(
            port.findings().count(),
            findings.len(),
            "two findings collapsed into one claim and the difference was lost"
        );
    }

    /// The version this build reports itself as, which is what stamps a finding.
    #[test]
    fn the_detection_identity_names_this_build() {
        let id = detection_id();
        let expected: Version = env!("CARGO_PKG_VERSION").parse().expect("a valid version");
        assert_eq!(id.version(), expected);
    }
}