dimpl 0.7.1

DTLS 1.2/1.3 implementation (Sans‑IO, Sync)
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
//! Public error type returned by the high-level DTLS API.

use std::fmt;

use crate::dtls12::message::Dtls12CipherSuite;
use crate::types::CompressionMethod;
use crate::types::Dtls13CipherSuite;
use crate::types::HashAlgorithm;
use crate::types::NamedGroup;
use crate::types::ProtocolVersion;
use crate::types::SignatureAlgorithm;
use crate::types::SignatureScheme;

pub(crate) fn bounded_error_len(len: usize) -> u16 {
    len.min(u16::MAX as usize) as u16
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Errors returned by DTLS processing functions.
pub enum Error {
    /// Unexpected DTLS message.
    UnexpectedMessage(UnexpectedMessageError),
    /// Local state was missing data required for the requested operation.
    InvalidState(InvalidStateError),
    /// Cryptographic operation failed.
    CryptoError(CryptoError),
    /// Certificate validation failed.
    CertificateError(CertificateError),
    /// Security policy violation.
    SecurityError(SecurityError),
    /// PSK (Pre-Shared Key) error.
    PskError(PskError),
    /// Incoming queue exceeded capacity.
    ReceiveQueueFull,
    /// Outgoing queue exceeded capacity.
    TransmitQueueFull,
    /// Missing fields when parsing ServerHello.
    IncompleteServerHello,
    /// Something timed out.
    Timeout(TimeoutError),
    /// Configuration error (e.g., invalid crypto provider).
    ConfigError(ConfigError),
    /// Peer attempted renegotiation (not supported).
    RenegotiationAttempt,
    /// Application data cannot be sent because the handshake is not yet complete.
    ///
    /// For auto-sense instances this means the version has not yet been
    /// resolved.  Callers should buffer the data and retry once the
    /// handshake advances.
    HandshakePending,
    /// The connection has been closed (close_notify sent or received).
    ConnectionClosed,
    /// If we are in auto-sense mode for a server and we received too
    /// many client hello fragments that haven't made a packet.
    TooManyClientHelloFragments,
    /// The DTLS 1.3 server received a ClientHello that does not offer
    /// DTLS 1.3 in `supported_versions`. In auto-sense mode the caller
    /// should fall back to a DTLS 1.2 server and replay the buffered
    /// packets.
    ///
    /// This value should never be seen outside dimpl. It's an internal
    /// value to communicate from dtls13/server.rs to lib.rs.
    #[doc(hidden)]
    Dtls12Fallback,
}

/// Fine-grained reason for an [`Error::UnexpectedMessage`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum UnexpectedMessageError {
    /// Auto-detection received a server response that was neither DTLS 1.2 nor DTLS 1.3.
    UnrecognizedAutoServerResponse,
    /// A DTLS 1.2 `ServerKeyExchange` omitted its required signature.
    ServerKeyExchangeWithoutSignature,
    /// A PSK `ServerKeyExchange` was received while processing an ECDHE suite.
    PskServerKeyExchangeInEcdhePath,
    /// An ECDHE `ServerKeyExchange` was received while processing a PSK suite.
    EcdheServerKeyExchangeInPskPath,
    /// A PSK `ClientKeyExchange` was received while processing an ECDHE suite.
    PskClientKeyExchangeInEcdhePath,
    /// An ECDHE `ClientKeyExchange` was received while processing a PSK suite.
    EcdheClientKeyExchangeInPskPath,
    /// A DTLS 1.3 `CertificateRequest` context was shorter than declared.
    CertificateRequestContextTruncated,
    /// A DTLS 1.3 `CertificateRequest` extension block was shorter than declared.
    CertificateRequestExtensionsTruncated,
}

/// Fine-grained reason for an [`Error::InvalidState`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum InvalidStateError {
    /// No cipher suite has been selected for the connection.
    NoCipherSuiteSelected,
    /// A cipher suite was required but not available.
    NoCipherSuite,
    /// The client random was required but not available.
    NoClientRandom,
    /// The server random was required but not available.
    NoServerRandom,
    /// The handshake key schedule was used before a shared secret existed.
    NoSharedSecretForHandshakeKeyDerivation,
    /// The server handshake traffic secret was required but not available.
    NoServerHandshakeTrafficSecret,
    /// The server handshake traffic secret was required to verify or create `Finished`.
    NoServerHandshakeTrafficSecretForFinished,
    /// The client handshake traffic secret was required but not available.
    NoClientHandshakeTrafficSecret,
    /// The client handshake traffic secret was required to verify or create `Finished`.
    NoClientHandshakeTrafficSecretForFinished,
    /// Application traffic keys were requested before the handshake secret existed.
    NoHandshakeSecretForApplicationKeyDerivation,
    /// A key exchange was required but no exchange was active.
    NoActiveKeyExchange,
    /// A DTLS 1.3 key update was requested before current send keys existed.
    NoCurrentAppSendKeysForKeyUpdate,
    /// A DTLS 1.3 peer key update was processed before current receive keys existed.
    NoCurrentAppRecvKeysForKeyUpdate,
    /// Exported keying material was requested before the exporter secret was derived.
    ExporterMasterSecretNotDerived,
    /// Extended master secret was negotiated, but the session hash was not captured.
    ExtendedMasterSecretSessionHashMissing,
}

/// Fine-grained reason for an [`Error::CryptoError`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CryptoError {
    /// No supported key exchange group is available.
    NoSupportedKeyExchangeGroups,
    /// DTLS 1.2 needs a key exchange group but none is configured.
    NoDtls12KeyExchangeGroupsConfigured,
    /// The epoch 0 sequence number space has been exhausted.
    Epoch0SequenceNumberExhausted,
    /// The send sequence number space for an epoch has been exhausted.
    SendSequenceNumberExhausted {
        /// The epoch whose send sequence number was exhausted.
        epoch: u16,
    },
    /// Send keys are not available for an epoch.
    SendKeysNotAvailable {
        /// The epoch whose send keys are unavailable.
        epoch: u16,
    },
    /// Receive keys are not available for an epoch.
    RecvKeysNotAvailable {
        /// The epoch whose receive keys are unavailable.
        epoch: u16,
    },
    /// No provider key exchange group matches the negotiated group.
    KeyExchangeGroupNotFound(NamedGroup),
    /// A key exchange operation was requested before initialization.
    KeyExchangeNotInitialized,
    /// The requested key exchange group is unsupported.
    UnsupportedKeyExchangeGroup(NamedGroup),
    /// The requested ECDHE group is unsupported.
    UnsupportedEcdheNamedGroup(NamedGroup),
    /// The requested DTLS 1.2 cipher suite is unsupported.
    UnsupportedCipherSuite(Dtls12CipherSuite),
    /// The requested HMAC hash algorithm is unsupported.
    UnsupportedHmacHash(HashAlgorithm),
    /// The requested signature algorithm is unsupported.
    UnsupportedSignatureAlgorithm(SignatureAlgorithm),
    /// No locally supported signature algorithm was offered by the peer.
    SignatureAlgorithmNotOfferedByClient,
    /// The signature algorithm did not match the expected algorithm.
    SignatureAlgorithmMismatch {
        /// The signature algorithm expected for this operation.
        expected: SignatureAlgorithm,
        /// The signature algorithm actually present.
        actual: SignatureAlgorithm,
    },
    /// The signature and hash algorithm pair is unsupported.
    UnsupportedSignaturePair {
        /// The requested signature algorithm.
        signature: SignatureAlgorithm,
        /// The requested hash algorithm.
        hash: HashAlgorithm,
    },
    /// The signature, hash, and key group combination is unsupported for verification.
    UnsupportedSignatureVerification {
        /// The requested signature algorithm.
        signature: SignatureAlgorithm,
        /// The requested hash algorithm.
        hash: HashAlgorithm,
        /// The public key group used for verification.
        group: NamedGroup,
    },
    /// Signature verification failed for a supported signature/hash/group combination.
    SignatureVerificationFailed {
        /// The requested signature algorithm.
        signature: SignatureAlgorithm,
        /// The requested hash algorithm.
        hash: HashAlgorithm,
        /// The public key group used for verification.
        group: NamedGroup,
    },
    /// The public key algorithm is unsupported.
    UnsupportedPublicKeyAlgorithm,
    /// A certificate or key references an unsupported EC curve.
    UnsupportedEcCurve,
    /// Certificate parsing failed during a crypto operation.
    CertificateParseFailed,
    /// A certificate omitted its required EC curve parameter.
    MissingEcCurveParameter,
    /// A certificate had an invalid EC curve parameter.
    InvalidEcCurveParameter,
    /// A certificate had an invalid subject public key.
    InvalidSubjectPublicKey,
    /// A signature was not encoded in the expected format.
    InvalidSignatureFormat,
    /// A public key could not be parsed for the given group.
    InvalidPublicKey(NamedGroup),
    /// A private key could not be parsed in any supported format.
    InvalidPrivateKey,
    /// A signing key was used with a hash other than the one it is bound to.
    SigningKeyHashMismatch {
        /// The hash algorithm bound to the signing key.
        key_hash: HashAlgorithm,
        /// The hash algorithm requested by the caller.
        requested: HashAlgorithm,
    },
    /// A signing key group does not support the requested hash algorithm.
    SigningKeyUnsupportedHash {
        /// The key group used for signing.
        group: NamedGroup,
        /// The requested hash algorithm.
        hash: HashAlgorithm,
    },
    /// An AES-GCM key had the wrong length.
    InvalidAesGcmKeySize {
        /// The actual key length in bytes.
        ///
        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
        actual: u16,
    },
    /// A ChaCha20-Poly1305 key had the wrong length.
    InvalidChacha20Poly1305KeySize {
        /// The actual key length in bytes.
        ///
        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
        actual: u16,
    },
    /// An AES-128-CCM-8 key had the wrong length.
    InvalidAes128Ccm8KeySize {
        /// The actual key length in bytes.
        ///
        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
        actual: u16,
    },
    /// A nonce was invalid for the selected cipher.
    InvalidNonce,
    /// A ciphertext was shorter than the selected AEAD permits.
    CiphertextTooShort {
        /// The minimum accepted ciphertext length in bytes.
        minimum: u8,
        /// The actual ciphertext length in bytes.
        actual: u8,
    },
    /// The requested HKDF output length is too large.
    HkdfOutputTooLong,
    /// The HKDF label is too long to encode.
    HkdfLabelTooLong,
    /// The HKDF context is too long to encode.
    HkdfContextTooLong,
    /// The HKDF-Expand-Label output length is too large to encode.
    HkdfOutputLengthTooLarge,
    /// The `Finished` verify-data length was invalid.
    InvalidVerifyDataLength,
    /// The `Finished` verify-data is too long to encode.
    VerifyDataTooLong,
    /// The TLS 1.2 master secret is too long to encode.
    MasterSecretTooLong,
    /// The requested exported keying material is too long.
    KeyingMaterialTooLong,
    /// The TLS 1.2 pre-master secret is not available.
    PreMasterSecretNotAvailable,
    /// The TLS 1.2 master secret is not available.
    MasterSecretNotAvailable,
    /// The client random is not available.
    ClientRandomNotAvailable,
    /// The server random is not available.
    ServerRandomNotAvailable,
    /// The client cipher has not been initialized.
    ClientCipherNotInitialized,
    /// The server cipher has not been initialized.
    ServerCipherNotInitialized,
    /// A write IV is not available for the requested side.
    WriteIvNotAvailable {
        /// Whether the missing write IV is for the client side.
        is_client: bool,
    },
    /// The DTLS 1.2 record IV length is unsupported for the selected suite.
    UnsupportedDtls12RecordIvLen {
        /// The unsupported record IV length.
        ///
        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
        len: u16,
        /// The selected DTLS 1.2 cipher suite.
        suite: Dtls12CipherSuite,
    },
    /// No private key is configured.
    NoPrivateKeyConfigured,
    /// A PSK operation was requested before a PSK was set.
    PskNotSet,
    /// The exporter master secret is not available.
    ExporterMasterSecretNotDerived,
    /// A provider operation failed without a more specific reason.
    OperationFailed(CryptoOperation),
}

/// A cryptographic operation that can fail.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum CryptoOperation {
    /// Create an AEAD cipher instance.
    CreateCipher,
    /// Encrypt plaintext.
    Encrypt,
    /// Decrypt ciphertext.
    Decrypt,
    /// Sign a transcript or payload.
    Sign,
    /// Verify a signature.
    VerifySignature,
    /// Load a private key.
    LoadPrivateKey,
    /// Start a key exchange.
    StartKeyExchange,
    /// Complete a key exchange.
    CompleteKeyExchange,
    /// Generate an ephemeral key.
    GenerateEphemeralKey,
    /// Compute a public key.
    ComputePublicKey,
    /// Fill a buffer with random bytes.
    FillRandom,
    /// Compute an HMAC.
    ComputeHmac,
    /// Run the TLS 1.2 PRF.
    Prf,
    /// Run HKDF-Extract.
    HkdfExtract,
    /// Run HKDF-Expand.
    HkdfExpand,
    /// Run TLS HKDF-Expand-Label.
    HkdfExpandLabel,
    /// Derive a DTLS 1.3 early secret.
    DeriveEarlySecret,
    /// Derive a DTLS 1.3 derived secret.
    DeriveDerivedSecret,
    /// Derive a DTLS 1.3 handshake secret.
    DeriveHandshakeSecret,
    /// Derive a DTLS 1.3 traffic secret.
    DeriveTrafficSecret,
    /// Derive a DTLS 1.3 master secret.
    DeriveMasterSecret,
    /// Derive a DTLS 1.3 exporter master secret.
    DeriveExporterMasterSecret,
    /// Derive a DTLS 1.3 next-generation traffic secret.
    DeriveNextTrafficSecret,
    /// Derive an AEAD key.
    DeriveKey,
    /// Derive an AEAD IV.
    DeriveIv,
    /// Derive a record sequence-number encryption key.
    DeriveSequenceNumberKey,
    /// Derive a Finished-message key.
    DeriveFinishedKey,
    /// Compute Finished verify data.
    ComputeVerifyData,
    /// Verify Finished verify data.
    VerifyData,
    /// Compute a PSK pre-master secret.
    ComputePskPreMasterSecret,
    /// Compute a DTLS cookie.
    ComputeCookie,
    /// Extract SRTP keying material.
    ExtractSrtpKeyingMaterial,
    /// Encode a key.
    EncodeKey,
    /// Decode a key.
    DecodeKey,
}

/// Fine-grained reason for an [`Error::CertificateError`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CertificateError {
    /// The peer did not send a server certificate.
    NoServerCertificateReceived,
    /// Client certificate verification was requested with no client certificate.
    NoClientCertificateForVerification,
    /// Server certificate verification was requested with no server certificate.
    NoServerCertificateForVerification,
    /// A DTLS 1.3 server certificate carried a non-empty context.
    ServerCertificateContextMustBeEmpty,
    /// A DTLS 1.3 client certificate carried a non-empty context.
    ClientCertificateContextMustBeEmpty,
    /// The certificate operation needs an unsupported hash algorithm.
    UnsupportedHashAlgorithm(HashAlgorithm),
    /// Certificate parsing failed.
    ParseFailed,
    /// A certificate omitted its EC curve parameter.
    MissingEcCurveParameter,
    /// A certificate had an invalid EC curve parameter.
    InvalidEcCurveParameter,
    /// A certificate references an unsupported EC curve.
    UnsupportedEcCurve,
    /// A certificate had an invalid subject public key.
    InvalidSubjectPublicKey,
}

/// Fine-grained reason for an [`Error::SecurityError`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum SecurityError {
    /// `HelloVerifyRequest` used an unsupported protocol version.
    UnsupportedHelloVerifyRequestVersion(ProtocolVersion),
    /// A server selected an unsupported protocol version.
    UnsupportedServerVersion(ProtocolVersion),
    /// A client offered an unsupported protocol version.
    UnsupportedClientVersion(ProtocolVersion),
    /// A server selected an unsupported DTLS 1.2 compression method.
    UnsupportedServerCompression(CompressionMethod),
    /// A client did not offer null compression.
    UnsupportedClientCompression,
    /// The selected key exchange algorithm is unsupported.
    UnsupportedKeyExchangeAlgorithm,
    /// The server selected a cipher suite that was not offered or recognized.
    ServerSelectedUnknownCipherSuite,
    /// The server selected a DTLS 1.2 cipher suite incompatible with local mode.
    ServerSelectedIncompatibleCipherSuite(Dtls12CipherSuite),
    /// The server selected a DTLS 1.2 cipher suite disallowed by configuration.
    ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite),
    /// The server selected a DTLS 1.3 cipher suite disallowed by configuration.
    ServerSelectedDisallowedDtls13CipherSuite(Dtls13CipherSuite),
    /// DTLS 1.2 extended master secret was required but not negotiated.
    ExtendedMasterSecretNotNegotiated,
    /// No mutually acceptable cipher suite was found.
    NoMutuallyAcceptableCipherSuite,
    /// A DTLS 1.3 ClientHello did not use the required DTLS 1.2 legacy version.
    ClientHelloLegacyVersionNotDtls12,
    /// A DTLS 1.3 ServerHello did not use the required DTLS 1.2 legacy version.
    ServerHelloLegacyVersionNotDtls12,
    /// A DTLS 1.3 ClientHello did not contain a recognized DTLS 1.3 version.
    ClientHelloMissingDtls13SupportedVersions,
    /// A ClientHello did not offer null compression.
    ClientHelloMustOfferNullCompression,
    /// The ClientHello cookie did not match the expected cookie.
    InvalidCookieInClientHello,
    /// A DTLS 1.3 ClientHello carried a non-empty legacy_cookie field.
    InvalidLegacyCookieInClientHello,
    /// The server attempted to send a second HelloRetryRequest.
    CannotSendSecondHelloRetryRequest,
    /// The client received a second HelloRetryRequest.
    UnexpectedSecondHelloRetryRequest,
    /// No common DTLS 1.3 cipher suite was found.
    NoCommonCipherSuite,
    /// No common DTLS 1.3 key exchange group was found.
    NoCommonKeyExchangeGroup,
    /// A HelloRetryRequest selected a disallowed cipher suite.
    HrrSelectedDisallowedCipherSuite,
    /// A HelloRetryRequest did not select DTLS 1.3.
    HrrDidNotSelectDtls13,
    /// A ServerHello selected a non-null compression method.
    ServerHelloCompressionMustBeNull,
    /// A server did not negotiate DTLS 1.3.
    ServerDidNotNegotiateDtls13,
    /// A DTLS 1.3 server did not send a key share.
    ServerMissingKeyShare,
    /// The server key share group did not match the expected group.
    ServerKeyShareGroupMismatch {
        /// The expected key exchange group.
        expected: NamedGroup,
        /// The key exchange group in the server key share.
        actual: NamedGroup,
    },
    /// A signature was too large to encode.
    SignatureTooLarge,
    /// A signature scheme was used even though the peer did not offer it.
    SignatureSchemeNotOffered(SignatureScheme),
    /// A signature algorithm did not match the expected algorithm.
    SignatureAlgorithmMismatch {
        /// The expected signature algorithm.
        expected: SignatureAlgorithm,
        /// The actual signature algorithm.
        actual: SignatureAlgorithm,
    },
    /// The signature scheme is unsupported.
    UnsupportedSignatureScheme(SignatureScheme),
    /// The signature scheme and certificate curve are incompatible.
    SignatureSchemeCertificateCurveMismatch {
        /// The signature scheme used for the operation.
        scheme: SignatureScheme,
        /// The certificate curve required by the signature scheme.
        expected: NamedGroup,
        /// The actual certificate curve.
        actual: NamedGroup,
    },
    /// Server Finished verification failed.
    ServerFinishedVerificationFailed,
    /// Client Finished verification failed.
    ClientFinishedVerificationFailed,
    /// A fatal DTLS alert was received.
    FatalAlert {
        /// The DTLS alert description.
        description: u8,
    },
}

/// Fine-grained reason for an [`Error::PskError`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum PskError {
    /// No PSK resolver is configured.
    NoPskResolverConfigured,
    /// No PSK identity is configured.
    NoPskIdentityConfigured,
    /// The configured PSK resolver did not return a key.
    ResolverReturnedNoKey,
}

/// Fine-grained reason for an [`Error::Timeout`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeoutError {
    /// Timeout while waiting for an auto client hybrid ClientHello to resolve.
    HybridClientHello,
    /// Timeout while connecting.
    Connect,
    /// Timeout while handshaking.
    Handshake,
}

/// Fine-grained reason for an [`Error::ConfigError`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigError {
    /// The configured MTU is smaller than dimpl permits.
    MtuTooSmall {
        /// The configured MTU.
        mtu: u16,
        /// The minimum accepted MTU.
        minimum: u16,
    },
    /// The configured AEAD encryption limit is too small.
    AeadEncryptionLimitTooSmall,
    /// Cipher-suite filtering removed every available suite.
    NoCipherSuitesAfterFiltering,
    /// A PSK resolver is configured but no PSK cipher suite remains enabled.
    PskConfiguredWithoutPskCipherSuite,
    /// DTLS 1.2 suites are enabled but no compatible key exchange group remains enabled.
    NoDtls12KeyExchangeGroupsAfterFiltering,
    /// DTLS 1.3 suites are enabled but no key exchange group remains enabled.
    NoDtls13KeyExchangeGroupsAfterFiltering,
    /// Crypto provider validation failed.
    CryptoProvider(CryptoProviderValidationError),
}

/// Fine-grained reason for crypto provider validation failure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CryptoProviderValidationError {
    /// The provider has no cipher suites supported by dimpl.
    NoCipherSuites,
    /// The provider has ECDH cipher suites but no key exchange groups.
    EcdhCipherSuitesWithoutKeyExchangeGroups,
    /// The provider has no DTLS 1.3 cipher suites.
    NoDtls13CipherSuites,
    /// No hash test vector exists for the hash algorithm.
    MissingHashTestVector(HashAlgorithm),
    /// The provider hash implementation returned an unexpected value.
    HashProviderIncorrect(HashAlgorithm),
    /// The provider PRF operation failed.
    PrfFailed {
        /// The hash algorithm used by the PRF.
        hash: HashAlgorithm,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// No PRF test vector exists for the hash algorithm.
    MissingPrfTestVector(HashAlgorithm),
    /// The provider PRF returned incorrect output.
    PrfIncorrect(HashAlgorithm),
    /// No signature-validation vector exists for the algorithm pair.
    NoSignatureValidationVector {
        /// The hash algorithm used by the vector.
        hash: HashAlgorithm,
        /// The signature algorithm used by the vector.
        signature: SignatureAlgorithm,
    },
    /// Provider signature verification failed.
    SignatureVerificationFailed {
        /// The hash algorithm used for verification.
        hash: HashAlgorithm,
        /// The signature algorithm used for verification.
        signature: SignatureAlgorithm,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// Provider HKDF validation failed.
    HkdfFailed {
        /// The DTLS 1.3 cipher suite under validation.
        suite: Dtls13CipherSuite,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// Provider HKDF returned empty output.
    HkdfEmptyOutput(Dtls13CipherSuite),
    /// No AEAD test vector exists for the suite.
    NoAeadTestVector(Dtls13CipherSuite),
    /// Creating the AEAD cipher failed.
    AeadCreateFailed {
        /// The DTLS 1.3 cipher suite under validation.
        suite: Dtls13CipherSuite,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// AEAD encryption failed.
    AeadEncryptFailed {
        /// The DTLS 1.3 cipher suite under validation.
        suite: Dtls13CipherSuite,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// AEAD encryption returned the wrong output.
    AeadEncryptWrongOutput(Dtls13CipherSuite),
    /// AEAD decryption failed.
    AeadDecryptFailed {
        /// The DTLS 1.3 cipher suite under validation.
        suite: Dtls13CipherSuite,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// AEAD decryption returned the wrong output.
    AeadDecryptWrongOutput(Dtls13CipherSuite),
    /// No record-number-encryption vector exists for the suite.
    NoRecordNumberEncryptionTestVector(Dtls13CipherSuite),
    /// Record-number encryption returned the wrong mask.
    RecordNumberEncryptionWrongMask(Dtls13CipherSuite),
    /// Starting key exchange failed.
    KeyExchangeStartFailed {
        /// The key exchange group under validation.
        group: NamedGroup,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// Completing key exchange failed.
    KeyExchangeCompleteFailed {
        /// The key exchange group under validation.
        group: NamedGroup,
        /// The underlying crypto failure.
        source: CryptoError,
    },
    /// Two sides of a validation key exchange produced different shared secrets.
    KeyExchangeMismatchedSharedSecret(NamedGroup),
    /// HMAC validation failed.
    HmacFailed(CryptoError),
    /// HMAC validation returned incorrect output.
    HmacIncorrect,
}

#[derive(Debug)]
pub(crate) enum InternalError {
    Transient(TransientError),
    Fatal(Error),
}

#[derive(Debug)]
pub(crate) enum TransientError {
    ParseIncomplete,
    Parse(nom::error::ErrorKind),
    TooManyRecords,
}

impl InternalError {
    pub(crate) fn parse_incomplete() -> Self {
        Self::Transient(TransientError::ParseIncomplete)
    }

    pub(crate) fn parse(kind: nom::error::ErrorKind) -> Self {
        Self::Transient(TransientError::Parse(kind))
    }

    pub(crate) fn too_many_records() -> Self {
        Self::Transient(TransientError::TooManyRecords)
    }

    pub(crate) fn into_public_error(self) -> Option<Error> {
        match self {
            Self::Transient(err) => {
                debug!("Discarding packet: {err}");
                None
            }
            Self::Fatal(err) => Some(err),
        }
    }
}

impl From<Error> for InternalError {
    fn from(value: Error) -> Self {
        Self::Fatal(value)
    }
}

impl<'a> From<nom::Err<nom::error::Error<&'a [u8]>>> for InternalError {
    fn from(value: nom::Err<nom::error::Error<&'a [u8]>>) -> Self {
        match value {
            nom::Err::Incomplete(_) => InternalError::parse_incomplete(),
            nom::Err::Error(x) => InternalError::parse(x.code),
            nom::Err::Failure(x) => InternalError::parse(x.code),
        }
    }
}

impl From<CryptoError> for Error {
    fn from(value: CryptoError) -> Self {
        Self::CryptoError(value)
    }
}

impl From<CertificateError> for Error {
    fn from(value: CertificateError) -> Self {
        Self::CertificateError(value)
    }
}

impl From<SecurityError> for Error {
    fn from(value: SecurityError) -> Self {
        Self::SecurityError(value)
    }
}

impl From<PskError> for Error {
    fn from(value: PskError) -> Self {
        Self::PskError(value)
    }
}

impl From<ConfigError> for Error {
    fn from(value: ConfigError) -> Self {
        Self::ConfigError(value)
    }
}

impl std::error::Error for Error {}

impl fmt::Display for InternalError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            InternalError::Transient(err) => err.fmt(f),
            InternalError::Fatal(err) => err.fmt(f),
        }
    }
}

impl fmt::Display for TransientError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TransientError::ParseIncomplete => write!(f, "parse incomplete"),
            TransientError::Parse(kind) => write!(f, "parse error: {:?}", kind),
            TransientError::TooManyRecords => write!(f, "too many records in packet"),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::UnexpectedMessage(err) => write!(f, "unexpected message: {err}"),
            Error::InvalidState(err) => write!(f, "invalid state: {err}"),
            Error::CryptoError(err) => write!(f, "crypto error: {err}"),
            Error::CertificateError(err) => write!(f, "certificate error: {err}"),
            Error::SecurityError(err) => write!(f, "security error: {err}"),
            Error::PskError(err) => write!(f, "psk error: {err}"),
            Error::ReceiveQueueFull => write!(f, "receive queue full"),
            Error::TransmitQueueFull => write!(f, "transmit queue full"),
            Error::IncompleteServerHello => write!(f, "incomplete ServerHello"),
            Error::Timeout(err) => write!(f, "timeout: {err}"),
            Error::ConfigError(err) => write!(f, "config error: {err}"),
            Error::RenegotiationAttempt => write!(f, "peer attempted renegotiation"),
            Error::HandshakePending => {
                write!(f, "handshake pending: cannot send application data yet")
            }
            Error::TooManyClientHelloFragments => write!(f, "too many client hello fragments"),
            Error::ConnectionClosed => write!(f, "connection closed"),
            Error::Dtls12Fallback => write!(f, "dtls 1.2 fallback (internal)"),
        }
    }
}

impl fmt::Display for UnexpectedMessageError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnrecognizedAutoServerResponse => write!(f, "unrecognized response from server"),
            Self::ServerKeyExchangeWithoutSignature => {
                write!(f, "ServerKeyExchange without signature")
            }
            Self::PskServerKeyExchangeInEcdhePath => {
                write!(f, "PSK ServerKeyExchange in ECDHE path")
            }
            Self::EcdheServerKeyExchangeInPskPath => {
                write!(f, "ECDHE ServerKeyExchange in PSK path")
            }
            Self::PskClientKeyExchangeInEcdhePath => {
                write!(f, "PSK ClientKeyExchange in ECDHE path")
            }
            Self::EcdheClientKeyExchangeInPskPath => {
                write!(f, "ECDHE ClientKeyExchange in PSK path")
            }
            Self::CertificateRequestContextTruncated => {
                write!(f, "CertificateRequest context truncated")
            }
            Self::CertificateRequestExtensionsTruncated => {
                write!(f, "CertificateRequest extensions truncated")
            }
        }
    }
}

impl fmt::Display for InvalidStateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoCipherSuiteSelected => write!(f, "no cipher suite selected"),
            Self::NoCipherSuite => write!(f, "no cipher suite"),
            Self::NoClientRandom => write!(f, "no client random"),
            Self::NoServerRandom => write!(f, "no server random"),
            Self::NoSharedSecretForHandshakeKeyDerivation => {
                write!(f, "no shared secret for handshake key derivation")
            }
            Self::NoServerHandshakeTrafficSecret => {
                write!(f, "no server handshake traffic secret")
            }
            Self::NoServerHandshakeTrafficSecretForFinished => {
                write!(f, "no server handshake traffic secret for Finished")
            }
            Self::NoClientHandshakeTrafficSecret => {
                write!(f, "no client handshake traffic secret")
            }
            Self::NoClientHandshakeTrafficSecretForFinished => {
                write!(f, "no client handshake traffic secret for Finished")
            }
            Self::NoHandshakeSecretForApplicationKeyDerivation => {
                write!(f, "no handshake secret for application key derivation")
            }
            Self::NoActiveKeyExchange => write!(f, "no active key exchange"),
            Self::NoCurrentAppSendKeysForKeyUpdate => {
                write!(f, "no current app send keys for KeyUpdate")
            }
            Self::NoCurrentAppRecvKeysForKeyUpdate => {
                write!(f, "no current app recv keys for KeyUpdate")
            }
            Self::ExporterMasterSecretNotDerived => {
                write!(f, "exporter master secret not yet derived")
            }
            Self::ExtendedMasterSecretSessionHashMissing => {
                write!(
                    f,
                    "extended master secret negotiated but session hash not captured"
                )
            }
        }
    }
}

impl fmt::Display for CryptoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoSupportedKeyExchangeGroups => write!(f, "no supported key exchange groups"),
            Self::NoDtls12KeyExchangeGroupsConfigured => {
                write!(f, "no DTLS 1.2 key exchange groups configured")
            }
            Self::Epoch0SequenceNumberExhausted => {
                write!(f, "epoch 0 sequence number exhausted")
            }
            Self::SendSequenceNumberExhausted { epoch } => {
                write!(f, "send sequence number exhausted for epoch {epoch}")
            }
            Self::SendKeysNotAvailable { epoch } => {
                write!(f, "send keys not available for epoch {epoch}")
            }
            Self::RecvKeysNotAvailable { epoch } => {
                write!(f, "recv keys not available for epoch {epoch}")
            }
            Self::KeyExchangeGroupNotFound(group) => {
                write!(f, "key exchange group not found: {group:?}")
            }
            Self::KeyExchangeNotInitialized => write!(f, "key exchange not initialized"),
            Self::UnsupportedKeyExchangeGroup(group) => {
                write!(f, "unsupported key exchange group: {group:?}")
            }
            Self::UnsupportedEcdheNamedGroup(group) => {
                write!(f, "unsupported ECDHE named group: {group:?}")
            }
            Self::UnsupportedCipherSuite(suite) => {
                write!(f, "unsupported cipher suite: {suite:?}")
            }
            Self::UnsupportedHmacHash(hash) => {
                write!(f, "unsupported HMAC hash algorithm: {hash:?}")
            }
            Self::UnsupportedSignatureAlgorithm(sig) => {
                write!(f, "unsupported signature algorithm: {sig:?}")
            }
            Self::SignatureAlgorithmNotOfferedByClient => {
                write!(f, "signature algorithm not offered by client")
            }
            Self::SignatureAlgorithmMismatch { expected, actual } => {
                write!(
                    f,
                    "signature algorithm mismatch: {actual:?} != {expected:?}"
                )
            }
            Self::UnsupportedSignaturePair { signature, hash } => {
                write!(f, "unsupported signature algorithm: {signature:?}/{hash:?}")
            }
            Self::UnsupportedSignatureVerification {
                signature,
                hash,
                group,
            } => write!(
                f,
                "unsupported signature verification: {signature:?} + {hash:?} + {group:?}"
            ),
            Self::SignatureVerificationFailed {
                signature,
                hash,
                group,
            } => write!(
                f,
                "signature verification failed: {signature:?} + {hash:?} + {group:?}"
            ),
            Self::UnsupportedPublicKeyAlgorithm => write!(f, "unsupported public key algorithm"),
            Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"),
            Self::CertificateParseFailed => write!(f, "failed to parse certificate"),
            Self::MissingEcCurveParameter => {
                write!(f, "missing EC curve parameter in certificate")
            }
            Self::InvalidEcCurveParameter => {
                write!(f, "invalid EC curve parameter in certificate")
            }
            Self::InvalidSubjectPublicKey => {
                write!(f, "invalid EC subject_public_key bitstring")
            }
            Self::InvalidSignatureFormat => write!(f, "invalid signature format"),
            Self::InvalidPublicKey(group) => write!(f, "invalid {group:?} public key"),
            Self::InvalidPrivateKey => {
                write!(f, "failed to parse private key in any supported format")
            }
            Self::SigningKeyHashMismatch {
                key_hash,
                requested,
            } => write!(
                f,
                "signing key is locked to {key_hash:?} but {requested:?} was requested"
            ),
            Self::SigningKeyUnsupportedHash { group, hash } => {
                write!(f, "{group:?} key does not support hash algorithm {hash:?}")
            }
            Self::InvalidAesGcmKeySize { actual } => {
                write!(f, "invalid key size for AES-GCM: {actual}")
            }
            Self::InvalidChacha20Poly1305KeySize { actual } => {
                write!(f, "invalid key size for CHACHA20-POLY1305: {actual}")
            }
            Self::InvalidAes128Ccm8KeySize { actual } => {
                write!(f, "invalid key size for AES-128-CCM-8: {actual}")
            }
            Self::InvalidNonce => write!(f, "invalid nonce"),
            Self::CiphertextTooShort { minimum, actual } => {
                write!(f, "ciphertext too short: got {actual}, minimum {minimum}")
            }
            Self::HkdfOutputTooLong => write!(f, "HKDF output too long"),
            Self::HkdfLabelTooLong => write!(f, "label too long for HKDF-Expand-Label"),
            Self::HkdfContextTooLong => write!(f, "context too long for HKDF-Expand-Label"),
            Self::HkdfOutputLengthTooLarge => {
                write!(f, "output length too large for HKDF-Expand-Label")
            }
            Self::InvalidVerifyDataLength => write!(f, "invalid verify data length"),
            Self::VerifyDataTooLong => write!(f, "verify data too long"),
            Self::MasterSecretTooLong => write!(f, "master secret too long"),
            Self::KeyingMaterialTooLong => write!(f, "keying material too long"),
            Self::PreMasterSecretNotAvailable => write!(f, "pre-master secret not available"),
            Self::MasterSecretNotAvailable => write!(f, "master secret not available"),
            Self::ClientRandomNotAvailable => write!(f, "client random not available"),
            Self::ServerRandomNotAvailable => write!(f, "server random not available"),
            Self::ClientCipherNotInitialized => write!(f, "client cipher not initialized"),
            Self::ServerCipherNotInitialized => write!(f, "server cipher not initialized"),
            Self::WriteIvNotAvailable { is_client } => {
                let side = if *is_client { "client" } else { "server" };
                write!(f, "{side} write IV not available")
            }
            Self::UnsupportedDtls12RecordIvLen { len, suite } => {
                write!(f, "unsupported DTLS 1.2 record_iv_len={len} for {suite:?}")
            }
            Self::NoPrivateKeyConfigured => write!(f, "no private key configured"),
            Self::PskNotSet => write!(f, "PSK not set"),
            Self::ExporterMasterSecretNotDerived => {
                write!(f, "exporter master secret not yet derived")
            }
            Self::OperationFailed(op) => write!(f, "{op} failed"),
        }
    }
}

impl fmt::Display for CryptoOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let text = match self {
            Self::CreateCipher => "cipher creation",
            Self::Encrypt => "encryption",
            Self::Decrypt => "decryption",
            Self::Sign => "signing",
            Self::VerifySignature => "signature verification",
            Self::LoadPrivateKey => "private key loading",
            Self::StartKeyExchange => "key exchange start",
            Self::CompleteKeyExchange => "key exchange completion",
            Self::GenerateEphemeralKey => "ephemeral key generation",
            Self::ComputePublicKey => "public key computation",
            Self::FillRandom => "random generation",
            Self::ComputeHmac => "HMAC computation",
            Self::Prf => "PRF",
            Self::HkdfExtract => "HKDF extract",
            Self::HkdfExpand => "HKDF expand",
            Self::HkdfExpandLabel => "HKDF expand label",
            Self::DeriveEarlySecret => "early secret derivation",
            Self::DeriveDerivedSecret => "derived secret derivation",
            Self::DeriveHandshakeSecret => "handshake secret derivation",
            Self::DeriveTrafficSecret => "traffic secret derivation",
            Self::DeriveMasterSecret => "master secret derivation",
            Self::DeriveExporterMasterSecret => "exporter master secret derivation",
            Self::DeriveNextTrafficSecret => "next traffic secret derivation",
            Self::DeriveKey => "key derivation",
            Self::DeriveIv => "IV derivation",
            Self::DeriveSequenceNumberKey => "sequence number key derivation",
            Self::DeriveFinishedKey => "Finished key derivation",
            Self::ComputeVerifyData => "verify data computation",
            Self::VerifyData => "verify data verification",
            Self::ComputePskPreMasterSecret => "PSK pre-master secret computation",
            Self::ComputeCookie => "cookie computation",
            Self::ExtractSrtpKeyingMaterial => "SRTP keying material extraction",
            Self::EncodeKey => "key encoding",
            Self::DecodeKey => "key decoding",
        };
        write!(f, "{text}")
    }
}

impl fmt::Display for CertificateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoServerCertificateReceived => write!(f, "no server certificate received"),
            Self::NoClientCertificateForVerification => {
                write!(f, "no client certificate for verification")
            }
            Self::NoServerCertificateForVerification => {
                write!(f, "no server certificate for verification")
            }
            Self::ServerCertificateContextMustBeEmpty => {
                write!(f, "server certificate context must be empty")
            }
            Self::ClientCertificateContextMustBeEmpty => {
                write!(f, "client certificate context must be empty")
            }
            Self::UnsupportedHashAlgorithm(hash) => {
                write!(f, "unsupported hash algorithm: {hash:?}")
            }
            Self::ParseFailed => write!(f, "failed to parse certificate"),
            Self::MissingEcCurveParameter => {
                write!(f, "missing EC curve parameter in certificate")
            }
            Self::InvalidEcCurveParameter => {
                write!(f, "invalid EC curve parameter in certificate")
            }
            Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"),
            Self::InvalidSubjectPublicKey => {
                write!(f, "invalid EC subject_public_key bitstring")
            }
        }
    }
}

impl fmt::Display for SecurityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnsupportedHelloVerifyRequestVersion(version) => {
                write!(
                    f,
                    "unsupported DTLS version in HelloVerifyRequest: {version:?}"
                )
            }
            Self::UnsupportedServerVersion(version) => {
                write!(f, "unsupported DTLS version from server: {version:?}")
            }
            Self::UnsupportedClientVersion(version) => {
                write!(f, "unsupported DTLS version from client: {version:?}")
            }
            Self::UnsupportedServerCompression(compression) => {
                write!(
                    f,
                    "unsupported compression method from server: {compression:?}"
                )
            }
            Self::UnsupportedClientCompression => {
                write!(f, "client did not offer null compression")
            }
            Self::UnsupportedKeyExchangeAlgorithm => {
                write!(f, "unsupported key exchange algorithm")
            }
            Self::ServerSelectedUnknownCipherSuite => {
                write!(f, "server selected unknown cipher suite")
            }
            Self::ServerSelectedIncompatibleCipherSuite(suite) => {
                write!(f, "server selected incompatible cipher suite: {suite:?}")
            }
            Self::ServerSelectedDisallowedCipherSuite(suite) => {
                write!(f, "server selected disallowed cipher suite: {suite:?}")
            }
            Self::ServerSelectedDisallowedDtls13CipherSuite(suite) => {
                write!(f, "server selected disallowed cipher suite: {suite:?}")
            }
            Self::ExtendedMasterSecretNotNegotiated => {
                write!(f, "extended master secret not negotiated")
            }
            Self::NoMutuallyAcceptableCipherSuite => {
                write!(f, "no mutually acceptable cipher suite")
            }
            Self::ClientHelloLegacyVersionNotDtls12 => {
                write!(f, "ClientHello legacy_version must be DTLS 1.2")
            }
            Self::ServerHelloLegacyVersionNotDtls12 => {
                write!(f, "ServerHello legacy_version must be DTLS 1.2")
            }
            Self::ClientHelloMissingDtls13SupportedVersions => {
                write!(f, "ClientHello missing DTLS 1.3 supported_versions")
            }
            Self::ClientHelloMustOfferNullCompression => {
                write!(f, "ClientHello must offer null compression")
            }
            Self::InvalidCookieInClientHello => write!(f, "invalid cookie in ClientHello"),
            Self::InvalidLegacyCookieInClientHello => {
                write!(f, "ClientHello legacy_cookie must be empty")
            }
            Self::CannotSendSecondHelloRetryRequest => {
                write!(f, "cannot send second HelloRetryRequest")
            }
            Self::UnexpectedSecondHelloRetryRequest => {
                write!(f, "received second HelloRetryRequest")
            }
            Self::NoCommonCipherSuite => write!(f, "no common cipher suite found"),
            Self::NoCommonKeyExchangeGroup => write!(f, "no common key exchange group"),
            Self::HrrSelectedDisallowedCipherSuite => {
                write!(f, "HRR selected disallowed cipher suite")
            }
            Self::HrrDidNotSelectDtls13 => write!(f, "HRR did not select DTLS 1.3"),
            Self::ServerHelloCompressionMustBeNull => {
                write!(f, "ServerHello compression must be null")
            }
            Self::ServerDidNotNegotiateDtls13 => {
                write!(f, "server did not negotiate DTLS 1.3")
            }
            Self::ServerMissingKeyShare => write!(f, "server missing key_share"),
            Self::ServerKeyShareGroupMismatch { expected, actual } => {
                write!(
                    f,
                    "server key_share group mismatch: expected {expected:?}, actual {actual:?}"
                )
            }
            Self::SignatureTooLarge => write!(f, "signature too large"),
            Self::SignatureSchemeNotOffered(scheme) => {
                write!(f, "signature scheme {scheme:?} was not offered")
            }
            Self::SignatureAlgorithmMismatch { expected, actual } => {
                write!(
                    f,
                    "signature algorithm mismatch: expected {expected:?}, got {actual:?}"
                )
            }
            Self::UnsupportedSignatureScheme(scheme) => {
                write!(f, "unsupported signature scheme: {scheme:?}")
            }
            Self::SignatureSchemeCertificateCurveMismatch {
                scheme,
                expected,
                actual,
            } => write!(
                f,
                "signature scheme {scheme:?} requires {expected:?} but certificate uses {actual:?}"
            ),
            Self::ServerFinishedVerificationFailed => {
                write!(f, "server Finished verification failed")
            }
            Self::ClientFinishedVerificationFailed => {
                write!(f, "client Finished verification failed")
            }
            Self::FatalAlert { description } => {
                write!(f, "received fatal alert: description={description}")
            }
        }
    }
}

impl fmt::Display for PskError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoPskResolverConfigured => write!(f, "no PSK resolver configured"),
            Self::NoPskIdentityConfigured => write!(f, "no PSK identity configured"),
            Self::ResolverReturnedNoKey => write!(f, "PSK resolver returned no key"),
        }
    }
}

impl fmt::Display for TimeoutError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::HybridClientHello => write!(f, "hybrid ClientHello"),
            Self::Connect => write!(f, "connect"),
            Self::Handshake => write!(f, "handshake"),
        }
    }
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MtuTooSmall { mtu, minimum } => {
                write!(f, "MTU {mtu} is too small (minimum {minimum})")
            }
            Self::AeadEncryptionLimitTooSmall => {
                write!(f, "aead_encryption_limit must be at least 1")
            }
            Self::NoCipherSuitesAfterFiltering => write!(
                f,
                concat!(
                    "no cipher suites remain after filtering; at least one DTLS 1.2 or ",
                    "DTLS 1.3 cipher suite must be available"
                )
            ),
            Self::PskConfiguredWithoutPskCipherSuite => write!(
                f,
                "PSK is configured but no PSK cipher suite remains after filtering DTLS 1.2 suites"
            ),
            Self::NoDtls12KeyExchangeGroupsAfterFiltering => write!(
                f,
                concat!(
                    "DTLS 1.2 cipher suites are enabled but no compatible key exchange ",
                    "groups remain after filtering"
                )
            ),
            Self::NoDtls13KeyExchangeGroupsAfterFiltering => write!(
                f,
                "DTLS 1.3 cipher suites are enabled but no key exchange groups remain after filtering"
            ),
            Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"),
        }
    }
}

impl fmt::Display for CryptoProviderValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NoCipherSuites => {
                write!(f, "CryptoProvider has no cipher suites supported by dimpl")
            }
            Self::EcdhCipherSuitesWithoutKeyExchangeGroups => write!(
                f,
                "CryptoProvider has ECDH cipher suites but no supported key exchange groups"
            ),
            Self::NoDtls13CipherSuites => {
                write!(f, "CryptoProvider has no DTLS 1.3 cipher suites")
            }
            Self::MissingHashTestVector(hash) => {
                write!(f, "no expected hash data for hash algorithm: {hash:?}")
            }
            Self::HashProviderIncorrect(hash) => {
                write!(f, "hash provider {hash:?} produced incorrect result")
            }
            Self::PrfFailed { hash, source } => write!(f, "PRF failed for {hash:?}: {source}"),
            Self::MissingPrfTestVector(hash) => {
                write!(f, "no expected PRF data for hash algorithm: {hash:?}")
            }
            Self::PrfIncorrect(hash) => write!(f, "PRF {hash:?} produced incorrect result"),
            Self::NoSignatureValidationVector { hash, signature } => {
                write!(f, "no validation test vectors for {hash:?} + {signature:?}")
            }
            Self::SignatureVerificationFailed {
                hash,
                signature,
                source,
            } => write!(
                f,
                "signature verification failed for {hash:?} + {signature:?}: {source}"
            ),
            Self::HkdfFailed { suite, source } => {
                write!(f, "HKDF failed for DTLS 1.3 suite {suite:?}: {source}")
            }
            Self::HkdfEmptyOutput(suite) => {
                write!(f, "HKDF returned empty output for {suite:?}")
            }
            Self::NoAeadTestVector(suite) => {
                write!(f, "no AEAD test vector for DTLS 1.3 suite {suite:?}")
            }
            Self::AeadCreateFailed { suite, source } => {
                write!(f, "failed to create cipher for {suite:?}: {source}")
            }
            Self::AeadEncryptFailed { suite, source } => {
                write!(f, "AEAD encrypt failed for {suite:?}: {source}")
            }
            Self::AeadEncryptWrongOutput(suite) => {
                write!(f, "AEAD encrypt produced wrong output for {suite:?}")
            }
            Self::AeadDecryptFailed { suite, source } => {
                write!(f, "AEAD decrypt failed for {suite:?}: {source}")
            }
            Self::AeadDecryptWrongOutput(suite) => {
                write!(f, "AEAD decrypt produced wrong output for {suite:?}")
            }
            Self::NoRecordNumberEncryptionTestVector(suite) => {
                write!(f, "no encrypt_sn test vector for DTLS 1.3 suite {suite:?}")
            }
            Self::RecordNumberEncryptionWrongMask(suite) => {
                write!(f, "encrypt_sn produced wrong mask for {suite:?}")
            }
            Self::KeyExchangeStartFailed { group, source } => {
                write!(f, "key exchange start failed for {group:?}: {source}")
            }
            Self::KeyExchangeCompleteFailed { group, source } => {
                write!(f, "key exchange complete failed for {group:?}: {source}")
            }
            Self::KeyExchangeMismatchedSharedSecret(group) => {
                write!(f, "key exchange produced different secrets for {group:?}")
            }
            Self::HmacFailed(source) => write!(f, "HMAC provider failed: {source}"),
            Self::HmacIncorrect => {
                write!(f, "HMAC provider produced incorrect result for HMAC-SHA256")
            }
        }
    }
}