netfp 0.1.1

Rust primitives and implementations for network fingerprinting
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
//! Rust implementation of the JARM active TLS server fingerprinting algorithm.
//!
//! This implementation is based on the original Salesforce JARM 1.0 project:
//! <https://github.com/salesforce/jarm>. The reference Python implementation is
//! included in this repository at `jarm/jarm.py`.
//!
//! Original JARM is Copyright (c) 2020, Salesforce.com, Inc. and licensed
//! under the BSD 3-Clause License:
//! <https://github.com/salesforce/jarm/blob/master/LICENSE.txt>.

use sha2::{Digest, Sha256};

use crate::{
    error::Error,
    tls::{
        AlpnProtocol, Grease, TlsCipherSuite, TlsClientHello, TlsExtension, TlsExtensionType,
        TlsPskKeyExchangeMode, TlsServerHello, TlsSignatureAlgorithm, TlsSupportedGroup,
        TlsVersion,
    },
    utils::random_32_bytes,
};

/// Canonical cipher-suite order used to encode the cipher portion of a JARM
/// fingerprint.
const JARM_CIPHER_ORDER: &[TlsCipherSuite] = &[
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_MD5,
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_RSA_WITH_IDEA_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_SEED_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::OLD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    // TLS 1.3 suites deliberately appear last, as required by JARM.
    TlsCipherSuite::TLS_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_AES_128_CCM_SHA256,
    TlsCipherSuite::TLS_AES_128_CCM_8_SHA256,
];

/// Complete cipher-suite list offered by standard JARM probes.
const ALL_CIPHER_SUITES: &[TlsCipherSuite] = &[
    TlsCipherSuite::TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_SEED_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    // TLS 1.3
    TlsCipherSuite::TLS_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_AES_128_GCM_SHA256,
    TlsCipherSuite::OLD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    // TLS 1.3
    TlsCipherSuite::TLS_AES_128_CCM_8_SHA256,
    TlsCipherSuite::TLS_AES_128_CCM_SHA256,
    TlsCipherSuite::TLS_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_IDEA_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_MD5,
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_SHA,
];

/// JARM cipher-suite list with all TLS 1.3 suites removed.
const NO_TLS13_CIPHER_SUITES: &[TlsCipherSuite] = &[
    TlsCipherSuite::TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_DHE_RSA_WITH_SEED_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::OLD_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::OLD_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
    TlsCipherSuite::TLS_ECDHE_RSA_WITH_RC4_128_SHA,
    TlsCipherSuite::TLS_RSA_WITH_3DES_EDE_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_CCM_8,
    TlsCipherSuite::TLS_RSA_WITH_AES_128_GCM_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_CCM_8,
    TlsCipherSuite::TLS_RSA_WITH_AES_256_GCM_SHA384,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256,
    TlsCipherSuite::TLS_RSA_WITH_IDEA_CBC_SHA,
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_MD5,
    TlsCipherSuite::TLS_RSA_WITH_RC4_128_SHA,
];

/// Signature algorithms advertised by JARM probes, in canonical order.
const SIGNATURE_ALGORITHMS: &[TlsSignatureAlgorithm] = &[
    TlsSignatureAlgorithm::ECDSA_SECP256R1_SHA256,
    TlsSignatureAlgorithm::RSA_PSS_RSAE_SHA256,
    TlsSignatureAlgorithm::RSA_PKCS1_SHA256,
    TlsSignatureAlgorithm::ECDSA_SECP384R1_SHA384,
    TlsSignatureAlgorithm::RSA_PSS_RSAE_SHA384,
    TlsSignatureAlgorithm::RSA_PKCS1_SHA384,
    TlsSignatureAlgorithm::RSA_PSS_RSAE_SHA512,
    TlsSignatureAlgorithm::RSA_PKCS1_SHA512,
    TlsSignatureAlgorithm::RSA_PKCS1_SHA1,
];

/// PSK key-exchange modes advertised by JARM probes.
const PSK_KEY_EXCHANGE_MODES: &[TlsPskKeyExchangeMode] = &[TlsPskKeyExchangeMode::PSK_DHE_KE];

/// Supported groups advertised by JARM probes, in canonical order.
const SUPPORTED_GROUPS: &[TlsSupportedGroup] = &[
    TlsSupportedGroup::X25519,
    TlsSupportedGroup::SECP256R1,
    TlsSupportedGroup::SECP384R1,
    TlsSupportedGroup::SECP521R1,
];

/// Version list used by probes that advertise support through TLS 1.2.
const TLS12_SUPPORTED_VERSIONS: &[TlsVersion] =
    &[TlsVersion::TLS10, TlsVersion::TLS11, TlsVersion::TLS12];

/// Version list used by probes that advertise support through TLS 1.3.
const TLS13_SUPPORTED_VERSIONS: &[TlsVersion] = &[
    TlsVersion::TLS10,
    TlsVersion::TLS11,
    TlsVersion::TLS12,
    TlsVersion::TLS13,
];

/// Full ALPN protocol list advertised by standard JARM probes.
const ALL_ALPNS: &[AlpnProtocol] = &[
    AlpnProtocol::HTTP_09,
    AlpnProtocol::HTTP_10,
    AlpnProtocol::HTTP_11,
    AlpnProtocol::SPDY_1,
    AlpnProtocol::SPDY_2,
    AlpnProtocol::SPDY_3,
    AlpnProtocol::H2,
    AlpnProtocol::H2C,
    AlpnProtocol::HQ,
];

/// Reduced ALPN list used by JARM's rare-ALPN probes.
const RARE_ALPNS: &[AlpnProtocol] = &[
    AlpnProtocol::HTTP_09,
    AlpnProtocol::HTTP_10,
    AlpnProtocol::SPDY_1,
    AlpnProtocol::SPDY_2,
    AlpnProtocol::SPDY_3,
    AlpnProtocol::H2C,
    AlpnProtocol::HQ,
];

/// Selects the base cipher-suite list for a JARM probe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CipherListKind {
    /// Includes all cipher suites used by JARM, including TLS 1.3 suites.
    All,
    /// Excludes TLS 1.3 cipher suites.
    NoTls13,
}

impl CipherListKind {
    /// Returns the canonical cipher-suite list represented by this selection.
    const fn as_slice(self) -> &'static [TlsCipherSuite] {
        match self {
            Self::All => ALL_CIPHER_SUITES,
            Self::NoTls13 => NO_TLS13_CIPHER_SUITES,
        }
    }
}

/// Selects the supported-version profile advertised by a JARM probe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum VersionSupport {
    /// Does not explicitly request an additional supported-version profile.
    None,
    /// Advertises versions from TLS 1.0 through TLS 1.2.
    Tls12,
    /// Advertises versions from TLS 1.0 through TLS 1.3.
    Tls13,
}

impl VersionSupport {
    /// Returns the version list to encode for the selected probe version.
    ///
    /// TLS 1.3 probes use the TLS 1.3 list even when the profile is [`Self::None`],
    /// matching the original JARM implementation.
    const fn supported_versions(self, protocol_version: TlsVersion) -> &'static [TlsVersion] {
        match (self, protocol_version) {
            (Self::Tls12, _) => TLS12_SUPPORTED_VERSIONS,
            (Self::Tls13, _) => TLS13_SUPPORTED_VERSIONS,

            // Match JARM behavior for TLS 1.3 probes
            (Self::None, TlsVersion::TLS13) => TLS13_SUPPORTED_VERSIONS,

            (Self::None, _) => &[],
        }
    }
}

/// Ordering transformation applied to a JARM probe's cipher-suite list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CipherListOrder {
    /// Preserves the canonical order.
    Forward,
    /// Reverses the canonical order.
    Reverse,
    /// Selects the upper half and orders it from the midpoint outward.
    TopHalf,
    /// Selects the lower half in canonical order.
    BottomHalf,
    /// Alternates around the midpoint, taking the upper item first.
    MiddleOut,
}

impl CipherListOrder {
    /// Applies this ordering transformation to `ciphers`.
    fn reorder(self, ciphers: &[TlsCipherSuite]) -> Vec<TlsCipherSuite> {
        match self {
            Self::Forward => ciphers.to_vec(),

            Self::Reverse => ciphers.iter().rev().copied().collect(),

            Self::BottomHalf => {
                let midpoint = ciphers.len() / 2;

                if ciphers.len() % 2 == 1 {
                    ciphers[midpoint + 1..].to_vec()
                } else {
                    ciphers[midpoint..].to_vec()
                }
            }

            Self::TopHalf => {
                let midpoint = ciphers.len() / 2;
                let mut reordered = Vec::with_capacity(ciphers.len().div_ceil(2));

                if ciphers.len() % 2 == 1 {
                    reordered.push(ciphers[midpoint]);
                }

                reordered.extend(ciphers[..midpoint].iter().rev().copied());

                reordered
            }

            Self::MiddleOut => {
                let cipher_count = ciphers.len();

                if cipher_count == 0 {
                    return Vec::new();
                }

                let midpoint = cipher_count / 2;
                let mut reordered = Vec::with_capacity(cipher_count);

                if cipher_count % 2 == 1 {
                    reordered.push(ciphers[midpoint]);

                    for offset in 1..=midpoint {
                        reordered.push(ciphers[midpoint + offset]);
                        reordered.push(ciphers[midpoint - offset]);
                    }
                } else {
                    for offset in 1..=midpoint {
                        reordered.push(ciphers[midpoint - 1 + offset]);
                        reordered.push(ciphers[midpoint - offset]);
                    }
                }

                reordered
            }
        }
    }
}

/// Ordering applied to order-sensitive values within JARM extensions.
///
/// This controls ALPN protocols and supported versions; it does not reorder the
/// extension blocks themselves.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ExtensionOrder {
    /// Preserves the canonical order.
    Forward,
    /// Reverses the canonical order.
    Reverse,
}

impl ExtensionOrder {
    /// Applies this ordering to a slice of copyable values.
    fn reorder<T: Copy>(self, values: &[T]) -> Vec<T> {
        match self {
            Self::Forward => values.to_vec(),
            Self::Reverse => values.iter().rev().copied().collect(),
        }
    }
}

/// Selects the ALPN protocol set advertised by a JARM probe.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AlpnProfile {
    /// Advertises the complete canonical JARM ALPN list.
    All,
    /// Advertises the reduced list that omits HTTP/1.1 and HTTP/2.
    Rare,
}

impl<'a> AlpnProfile {
    /// Returns the ALPN protocol list represented by this profile.
    const fn as_slice(self) -> &'static [AlpnProtocol<'a>] {
        match self {
            Self::All => ALL_ALPNS,
            Self::Rare => RARE_ALPNS,
        }
    }
}

#[derive(Debug)]
struct JarmProbeDefinition {
    host: String,
    protocol_version: TlsVersion,
    cipher_list_kind: CipherListKind,
    cipher_list_order: CipherListOrder,
    extension_order: ExtensionOrder,
    alpn_profile: AlpnProfile,
    version_support: VersionSupport,
    grease: bool,
}

impl JarmProbeDefinition {
    fn client_hello_probe(&self) -> Result<Vec<u8>, Error> {
        let mut cipher_suites = Vec::new();

        if self.grease {
            cipher_suites.push(TlsCipherSuite(Grease::random().as_u16()));
        }

        cipher_suites.extend(
            self.cipher_list_order
                .reorder(self.cipher_list_kind.as_slice()),
        );

        let record_version = if self.protocol_version == TlsVersion::TLS13 {
            TlsVersion::TLS10
        } else {
            self.protocol_version
        };

        TlsClientHello::new(
            self.protocol_version,
            record_version,
            cipher_suites,
            self.extensions()?,
        )?
        .to_bytes()
    }

    fn extensions(&self) -> Result<Vec<TlsExtension>, Error> {
        let mut extensions = Vec::new();

        if self.grease {
            extensions.push(self.grease_extension()?);
        }

        extensions.push(self.server_name_extension()?);
        extensions.push(self.extended_master_secret_extension()?);
        extensions.push(self.max_fragment_length_extension()?);
        extensions.push(self.renegotiation_info_extension()?);
        extensions.push(self.supported_groups_extension()?);
        extensions.push(self.ec_point_formats_extension()?);
        extensions.push(self.session_ticket_extension()?);
        extensions.push(self.alpn_extension()?);
        extensions.push(self.signature_algorithms_extension()?);
        extensions.push(self.key_share_extension()?);
        extensions.push(self.psk_key_exchange_modes_extension()?);

        if self.protocol_version == TlsVersion::TLS13
            || self.version_support != VersionSupport::None
        {
            extensions.push(self.supported_versions_extension()?);
        }

        Ok(extensions)
    }

    fn grease_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType(Grease::random().as_u16()), Vec::new())
    }

    fn server_name_extension(&self) -> Result<TlsExtension, Error> {
        let host_bytes = self.host.as_bytes();

        let mut extension_data = Vec::new();

        // ServerNameList length
        extension_data.extend_from_slice(&((host_bytes.len() + 3) as u16).to_be_bytes());

        // host_name
        extension_data.push(0x00);

        // HostName length
        extension_data.extend_from_slice(&(host_bytes.len() as u16).to_be_bytes());
        extension_data.extend_from_slice(host_bytes);

        TlsExtension::new(TlsExtensionType::SERVER_NAME, extension_data)
    }

    fn extended_master_secret_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType::EXTENDED_MASTER_SECRET, Vec::new())
    }

    fn max_fragment_length_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType::MAX_FRAGMENT_LENGTH, Vec::from([0x01]))
    }

    fn renegotiation_info_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType::RENEGOTIATION_INFO, Vec::from([0x00]))
    }

    fn supported_groups_extension(&self) -> Result<TlsExtension, Error> {
        let mut data = Vec::new();

        // named_group_list length
        data.extend_from_slice(&((SUPPORTED_GROUPS.len() * size_of::<u16>()) as u16).to_be_bytes());

        for group in SUPPORTED_GROUPS {
            data.extend_from_slice(&group.to_be_bytes());
        }

        TlsExtension::new(TlsExtensionType::SUPPORTED_GROUPS, data)
    }

    fn ec_point_formats_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType::EC_POINT_FORMATS, Vec::from([0x01, 0x00]))
    }

    fn session_ticket_extension(&self) -> Result<TlsExtension, Error> {
        TlsExtension::new(TlsExtensionType::SESSION_TICKET, Vec::new())
    }

    fn alpn_extension(&self) -> Result<TlsExtension, Error> {
        let mut protocols = Vec::new();

        for alpn in self.extension_order.reorder(self.alpn_profile.as_slice()) {
            let protocol = alpn.as_bytes();

            protocols.push(protocol.len() as u8);
            protocols.extend_from_slice(protocol);
        }

        let mut data = Vec::new();

        // ProtocolNameList length
        data.extend_from_slice(&(protocols.len() as u16).to_be_bytes());
        data.extend_from_slice(&protocols);

        TlsExtension::new(
            TlsExtensionType::APPLICATION_LAYER_PROTOCOL_NEGOTIATION,
            data,
        )
    }

    fn signature_algorithms_extension(&self) -> Result<TlsExtension, Error> {
        let mut algorithms = Vec::new();

        for algorithm in SIGNATURE_ALGORITHMS {
            algorithms.extend_from_slice(&algorithm.to_be_bytes());
        }

        let mut data = Vec::new();

        // supported_signature_algorithms length
        data.extend_from_slice(&(algorithms.len() as u16).to_be_bytes());
        data.extend_from_slice(&algorithms);

        TlsExtension::new(TlsExtensionType::SIGNATURE_ALGORITHMS, data)
    }

    fn key_share_extension(&self) -> Result<TlsExtension, Error> {
        let mut key_shares = Vec::new();

        if self.grease {
            key_shares.extend_from_slice(&Grease::random().to_be_bytes());

            // GREASE key exchange length
            key_shares.extend_from_slice(&1u16.to_be_bytes());
            key_shares.push(0x00);
        }

        key_shares.extend_from_slice(&TlsSupportedGroup::X25519.to_be_bytes());
        key_shares.extend_from_slice(&32u16.to_be_bytes());
        key_shares.extend_from_slice(&random_32_bytes());

        let mut data = Vec::new();

        // client_shares length
        data.extend_from_slice(&(key_shares.len() as u16).to_be_bytes());
        data.extend_from_slice(&key_shares);

        TlsExtension::new(TlsExtensionType::KEY_SHARE, data)
    }

    fn psk_key_exchange_modes_extension(&self) -> Result<TlsExtension, Error> {
        let mut data = Vec::with_capacity(PSK_KEY_EXCHANGE_MODES.len() + 1);

        // ke_modes length
        data.push(PSK_KEY_EXCHANGE_MODES.len() as u8);

        for mode in PSK_KEY_EXCHANGE_MODES {
            data.push(mode.as_u8());
        }

        TlsExtension::new(TlsExtensionType::PSK_KEY_EXCHANGE_MODES, data)
    }

    fn supported_versions_extension(&self) -> Result<TlsExtension, Error> {
        let mut versions = Vec::new();

        if self.grease {
            versions.extend_from_slice(&Grease::random().to_be_bytes());
        }

        for version in self.extension_order.reorder(
            self.version_support
                .supported_versions(self.protocol_version),
        ) {
            versions.extend_from_slice(&version.to_be_bytes());
        }

        let mut data = Vec::with_capacity(versions.len() + 1);

        // versions length
        data.push(versions.len() as u8);
        data.extend_from_slice(&versions);

        TlsExtension::new(TlsExtensionType::SUPPORTED_VERSIONS, data)
    }
}

/// Generates the ten TLS probes and combines their responses into a JARM
/// fingerprint.
///
/// JARM actively fingerprints a TLS server by sending ten specially ordered
/// `ClientHello` messages. The selected cipher suite, legacy TLS version,
/// ALPN protocol, and extension types from each response are combined into a
/// 62-character fingerprint.
///
/// # Examples
///
/// ```no_run
/// use std::{
///     io::{Read, Write},
///     net::TcpStream,
/// };
///
/// use netfp::{
///     Error, JarmFingerprint,
///     tls::{ServerHelloDecoder, TlsRecord, TlsServerHello},
/// };
///
/// fn scan_probe(
///     address: &str,
///     probe: &[u8],
/// ) -> Result<Option<TlsServerHello>, Box<dyn std::error::Error>> {
///     let mut stream = TcpStream::connect(address)?;
///     stream.write_all(probe)?;
///
///     let mut decoder = ServerHelloDecoder::new();
///     let mut buffered = Vec::new();
///     let mut read_buffer = [0; 4096];
///
///     loop {
///         let bytes_read = stream.read(&mut read_buffer)?;
///         if bytes_read == 0 {
///             return Ok(None);
///         }
///         buffered.extend_from_slice(&read_buffer[..bytes_read]);
///
///         let mut consumed = 0;
///         while consumed < buffered.len() {
///             let (record, record_length) =
///                 match TlsRecord::try_from_bytes(&buffered[consumed..]) {
///                     Ok(record) => record,
///                     Err(Error::UnexpectedEof { .. }) => break,
///                     Err(error) => return Err(error.into()),
///                 };
///             consumed += record_length;
///
///             if let Some(server_hello) = decoder.push_record(&record)? {
///                 return Ok(Some(server_hello));
///             }
///         }
///         buffered.drain(..consumed);
///     }
/// }
///
/// let jarm = JarmFingerprint::new("example.com");
/// let responses = jarm
///     .probes()?
///     .iter()
///     .map(|probe| scan_probe("example.com:443", probe))
///     .collect::<Result<Vec<_>, _>>()?;
/// let fingerprint = jarm.fingerprint(&responses);
///
/// println!("{fingerprint}");
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct JarmFingerprint {
    probes: Vec<JarmProbeDefinition>,
}

#[derive(Debug)]
struct JarmServerHello {
    cipher_suite: TlsCipherSuite,
    legacy_version_byte: u8,
    alpn: String,
    extension_types: Vec<TlsExtensionType>,
}

impl TryFrom<&TlsServerHello> for JarmServerHello {
    type Error = Error;

    fn try_from(value: &TlsServerHello) -> Result<Self, Self::Error> {
        Ok(Self {
            cipher_suite: *value.cipher_suite(),
            legacy_version_byte: value.legacy_version().to_be_bytes()[1],
            alpn: value.alpn_protocol()?.unwrap_or_default().to_owned(),
            extension_types: value.extension_types(),
        })
    }
}

impl JarmFingerprint {
    /// Creates a JARM fingerprint generator for `host`.
    ///
    /// The host is encoded in the SNI extension of all ten probes. This method
    /// does not resolve the host or open any network connections.
    pub fn new(host: impl Into<String>) -> Self {
        let host = host.into();

        let probes = vec![
            // 1. tls1_2_forward
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS12,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::Forward,
                extension_order: ExtensionOrder::Reverse,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls12,
                grease: false,
            },
            // 2. tls1_2_reverse
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS12,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::Reverse,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls12,
                grease: false,
            },
            // 3. tls1_2_top_half
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS12,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::TopHalf,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::None,
                grease: false,
            },
            // 4. tls1_2_bottom_half
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS12,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::BottomHalf,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::Rare,
                version_support: VersionSupport::None,
                grease: false,
            },
            // 5. tls1_2_middle_out
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS12,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::MiddleOut,
                extension_order: ExtensionOrder::Reverse,
                alpn_profile: AlpnProfile::Rare,
                version_support: VersionSupport::None,
                grease: true,
            },
            // 6. tls1_1_middle_out
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS11,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::Forward,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::None,
                grease: false,
            },
            // 7. tls1_3_forward
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS13,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::Forward,
                extension_order: ExtensionOrder::Reverse,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls13,
                grease: false,
            },
            // 8. tls1_3_reverse
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS13,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::Reverse,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls13,
                grease: false,
            },
            // 9. tls1_3_invalid
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS13,
                cipher_list_kind: CipherListKind::NoTls13,
                cipher_list_order: CipherListOrder::Forward,
                extension_order: ExtensionOrder::Forward,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls13,
                grease: false,
            },
            // 10. tls1_3_middle_out
            JarmProbeDefinition {
                host: host.clone(),
                protocol_version: TlsVersion::TLS13,
                cipher_list_kind: CipherListKind::All,
                cipher_list_order: CipherListOrder::MiddleOut,
                extension_order: ExtensionOrder::Reverse,
                alpn_profile: AlpnProfile::All,
                version_support: VersionSupport::Tls13,
                grease: true,
            },
        ];

        Self { probes }
    }

    /// Builds the ten JARM `ClientHello` probes in canonical order.
    ///
    /// Random fields and GREASE values are generated with the thread-local
    /// random number generator.
    ///
    /// Each returned byte vector is a complete TLS record ready to send over a
    /// separate TCP connection to the target server.
    ///
    /// # Errors
    ///
    /// Returns [`Error::LengthOverflow`] when the host or an encoded TLS field
    /// cannot fit in its protocol length field, or [`Error::Malformed`] if a
    /// generated `ClientHello` is invalid.
    pub fn probes(&self) -> Result<Vec<Vec<u8>>, Error> {
        self.probes
            .iter()
            .map(JarmProbeDefinition::client_hello_probe)
            .collect()
    }

    /// Produces the JARM fingerprint from the probe responses.
    ///
    /// Responses must be supplied in the same order as the records returned by
    /// [`Self::probes`]. A missing response is represented by `None`. Missing
    /// entries at the end of the slice are also treated as absent responses;
    /// entries beyond the first ten are ignored.
    ///
    /// The returned value is always 62 lowercase ASCII characters. If every
    /// response is absent, it consists of 62 zeroes.
    pub fn fingerprint(&self, server_hellos: &[Option<TlsServerHello>]) -> String {
        let mut received_server_hello = false;
        let mut cipher_and_version = String::with_capacity(self.probes.len() * 3);
        let mut alpn_and_extensions = String::new();

        for probe_index in 0..self.probes.len() {
            let server_hello = server_hellos
                .get(probe_index)
                .and_then(Option::as_ref)
                .and_then(|response| JarmServerHello::try_from(response).ok());

            let Some(server_hello) = server_hello else {
                cipher_and_version.push_str("000");
                continue;
            };
            received_server_hello = true;

            let cipher_ordinal = JARM_CIPHER_ORDER
                .iter()
                .position(|candidate| candidate == &server_hello.cipher_suite)
                .map_or(JARM_CIPHER_ORDER.len() + 1, |index| index + 1);
            let version = "abcdef"
                .chars()
                .nth(usize::from(server_hello.legacy_version_byte))
                .unwrap_or('0');

            let extension_types = server_hello
                .extension_types
                .iter()
                .map(|extension_type| format!("{:04x}", extension_type.as_u16()))
                .collect::<Vec<_>>()
                .join("-");

            cipher_and_version.push_str(&format!("{cipher_ordinal:02x}"));
            cipher_and_version.push(version);
            alpn_and_extensions.push_str(&server_hello.alpn);
            alpn_and_extensions.push_str(&extension_types);
        }

        if !received_server_hello {
            return "0".repeat(62);
        }

        let digest = Sha256::digest(alpn_and_extensions.as_bytes());
        let digest_hex = digest
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect::<String>();
        format!("{cipher_and_version}{digest_hex}")[..62].to_owned()
    }
}

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

    #[test]
    fn fingerprint_matches_known_digest_vector() {
        let responses = (0..10)
            .map(|_| Some(test_server_hello()))
            .collect::<Vec<_>>();

        assert_eq!(
            JarmFingerprint::new("example.com").fingerprint(&responses),
            "41d41d41d41d41d41d41d41d41d41da0bfb9dc5a7a50dfa51c2a70be11dda8"
        );
    }

    fn test_server_hello() -> TlsServerHello {
        let mut body = Vec::new();
        body.extend_from_slice(&TlsVersion::TLS12.to_be_bytes());
        body.extend_from_slice(&[0; 32]);
        body.push(0);
        body.extend_from_slice(&TlsCipherSuite::TLS_AES_128_GCM_SHA256.to_be_bytes());
        body.push(0);

        let extensions = [
            0x00, 0x2b, 0x00, 0x02, 0x03, 0x04, 0x00, 0x10, 0x00, 0x05, 0x00, 0x03, 0x02, b'h',
            b'2',
        ];
        body.extend_from_slice(&(extensions.len() as u16).to_be_bytes());
        body.extend_from_slice(&extensions);

        TlsServerHello::try_from_bytes(&body).unwrap()
    }
}