Skip to main content

dimpl/
error.rs

1//! Public error type returned by the high-level DTLS API.
2
3use std::fmt;
4
5use crate::dtls12::message::Dtls12CipherSuite;
6use crate::types::CompressionMethod;
7use crate::types::Dtls13CipherSuite;
8use crate::types::HashAlgorithm;
9use crate::types::NamedGroup;
10use crate::types::ProtocolVersion;
11use crate::types::SignatureAlgorithm;
12use crate::types::SignatureScheme;
13
14pub(crate) fn bounded_error_len(len: usize) -> u16 {
15    len.min(u16::MAX as usize) as u16
16}
17
18#[derive(Debug, Clone, PartialEq, Eq)]
19#[non_exhaustive]
20/// Errors returned by DTLS processing functions.
21pub enum Error {
22    /// Unexpected DTLS message.
23    UnexpectedMessage(UnexpectedMessageError),
24    /// Local state was missing data required for the requested operation.
25    InvalidState(InvalidStateError),
26    /// Cryptographic operation failed.
27    CryptoError(CryptoError),
28    /// Certificate validation failed.
29    CertificateError(CertificateError),
30    /// Security policy violation.
31    SecurityError(SecurityError),
32    /// PSK (Pre-Shared Key) error.
33    PskError(PskError),
34    /// Incoming queue exceeded capacity.
35    ReceiveQueueFull,
36    /// Outgoing queue exceeded capacity.
37    TransmitQueueFull,
38    /// Missing fields when parsing ServerHello.
39    IncompleteServerHello,
40    /// Something timed out.
41    Timeout(TimeoutError),
42    /// Configuration error (e.g., invalid crypto provider).
43    ConfigError(ConfigError),
44    /// Peer attempted renegotiation (not supported).
45    RenegotiationAttempt,
46    /// Application data cannot be sent because the handshake is not yet complete.
47    ///
48    /// For auto-sense instances this means the version has not yet been
49    /// resolved.  Callers should buffer the data and retry once the
50    /// handshake advances.
51    HandshakePending,
52    /// The connection has been closed (close_notify sent or received).
53    ConnectionClosed,
54    /// If we are in auto-sense mode for a server and we received too
55    /// many client hello fragments that haven't made a packet.
56    TooManyClientHelloFragments,
57    /// The DTLS 1.3 server received a ClientHello that does not offer
58    /// DTLS 1.3 in `supported_versions`. In auto-sense mode the caller
59    /// should fall back to a DTLS 1.2 server and replay the buffered
60    /// packets.
61    ///
62    /// This value should never be seen outside dimpl. It's an internal
63    /// value to communicate from dtls13/server.rs to lib.rs.
64    #[doc(hidden)]
65    Dtls12Fallback,
66}
67
68/// Fine-grained reason for an [`Error::UnexpectedMessage`].
69#[derive(Debug, Clone, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum UnexpectedMessageError {
72    /// Auto-detection received a server response that was neither DTLS 1.2 nor DTLS 1.3.
73    UnrecognizedAutoServerResponse,
74    /// A DTLS 1.2 `ServerKeyExchange` omitted its required signature.
75    ServerKeyExchangeWithoutSignature,
76    /// A PSK `ServerKeyExchange` was received while processing an ECDHE suite.
77    PskServerKeyExchangeInEcdhePath,
78    /// An ECDHE `ServerKeyExchange` was received while processing a PSK suite.
79    EcdheServerKeyExchangeInPskPath,
80    /// A PSK `ClientKeyExchange` was received while processing an ECDHE suite.
81    PskClientKeyExchangeInEcdhePath,
82    /// An ECDHE `ClientKeyExchange` was received while processing a PSK suite.
83    EcdheClientKeyExchangeInPskPath,
84    /// A DTLS 1.3 `CertificateRequest` context was shorter than declared.
85    CertificateRequestContextTruncated,
86    /// A DTLS 1.3 `CertificateRequest` extension block was shorter than declared.
87    CertificateRequestExtensionsTruncated,
88}
89
90/// Fine-grained reason for an [`Error::InvalidState`].
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum InvalidStateError {
94    /// No cipher suite has been selected for the connection.
95    NoCipherSuiteSelected,
96    /// A cipher suite was required but not available.
97    NoCipherSuite,
98    /// The client random was required but not available.
99    NoClientRandom,
100    /// The server random was required but not available.
101    NoServerRandom,
102    /// The handshake key schedule was used before a shared secret existed.
103    NoSharedSecretForHandshakeKeyDerivation,
104    /// The server handshake traffic secret was required but not available.
105    NoServerHandshakeTrafficSecret,
106    /// The server handshake traffic secret was required to verify or create `Finished`.
107    NoServerHandshakeTrafficSecretForFinished,
108    /// The client handshake traffic secret was required but not available.
109    NoClientHandshakeTrafficSecret,
110    /// The client handshake traffic secret was required to verify or create `Finished`.
111    NoClientHandshakeTrafficSecretForFinished,
112    /// Application traffic keys were requested before the handshake secret existed.
113    NoHandshakeSecretForApplicationKeyDerivation,
114    /// A key exchange was required but no exchange was active.
115    NoActiveKeyExchange,
116    /// A DTLS 1.3 key update was requested before current send keys existed.
117    NoCurrentAppSendKeysForKeyUpdate,
118    /// A DTLS 1.3 peer key update was processed before current receive keys existed.
119    NoCurrentAppRecvKeysForKeyUpdate,
120    /// Exported keying material was requested before the exporter secret was derived.
121    ExporterMasterSecretNotDerived,
122    /// Extended master secret was negotiated, but the session hash was not captured.
123    ExtendedMasterSecretSessionHashMissing,
124}
125
126/// Fine-grained reason for an [`Error::CryptoError`].
127#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum CryptoError {
130    /// No supported key exchange group is available.
131    NoSupportedKeyExchangeGroups,
132    /// DTLS 1.2 needs a key exchange group but none is configured.
133    NoDtls12KeyExchangeGroupsConfigured,
134    /// The epoch 0 sequence number space has been exhausted.
135    Epoch0SequenceNumberExhausted,
136    /// The send sequence number space for an epoch has been exhausted.
137    SendSequenceNumberExhausted {
138        /// The epoch whose send sequence number was exhausted.
139        epoch: u16,
140    },
141    /// Send keys are not available for an epoch.
142    SendKeysNotAvailable {
143        /// The epoch whose send keys are unavailable.
144        epoch: u16,
145    },
146    /// Receive keys are not available for an epoch.
147    RecvKeysNotAvailable {
148        /// The epoch whose receive keys are unavailable.
149        epoch: u16,
150    },
151    /// No provider key exchange group matches the negotiated group.
152    KeyExchangeGroupNotFound(NamedGroup),
153    /// A key exchange operation was requested before initialization.
154    KeyExchangeNotInitialized,
155    /// The requested key exchange group is unsupported.
156    UnsupportedKeyExchangeGroup(NamedGroup),
157    /// The requested ECDHE group is unsupported.
158    UnsupportedEcdheNamedGroup(NamedGroup),
159    /// The requested DTLS 1.2 cipher suite is unsupported.
160    UnsupportedCipherSuite(Dtls12CipherSuite),
161    /// The requested HMAC hash algorithm is unsupported.
162    UnsupportedHmacHash(HashAlgorithm),
163    /// The requested signature algorithm is unsupported.
164    UnsupportedSignatureAlgorithm(SignatureAlgorithm),
165    /// No locally supported signature algorithm was offered by the peer.
166    SignatureAlgorithmNotOfferedByClient,
167    /// The signature algorithm did not match the expected algorithm.
168    SignatureAlgorithmMismatch {
169        /// The signature algorithm expected for this operation.
170        expected: SignatureAlgorithm,
171        /// The signature algorithm actually present.
172        actual: SignatureAlgorithm,
173    },
174    /// The signature and hash algorithm pair is unsupported.
175    UnsupportedSignaturePair {
176        /// The requested signature algorithm.
177        signature: SignatureAlgorithm,
178        /// The requested hash algorithm.
179        hash: HashAlgorithm,
180    },
181    /// The signature, hash, and key group combination is unsupported for verification.
182    UnsupportedSignatureVerification {
183        /// The requested signature algorithm.
184        signature: SignatureAlgorithm,
185        /// The requested hash algorithm.
186        hash: HashAlgorithm,
187        /// The public key group used for verification.
188        group: NamedGroup,
189    },
190    /// Signature verification failed for a supported signature/hash/group combination.
191    SignatureVerificationFailed {
192        /// The requested signature algorithm.
193        signature: SignatureAlgorithm,
194        /// The requested hash algorithm.
195        hash: HashAlgorithm,
196        /// The public key group used for verification.
197        group: NamedGroup,
198    },
199    /// The public key algorithm is unsupported.
200    UnsupportedPublicKeyAlgorithm,
201    /// A certificate or key references an unsupported EC curve.
202    UnsupportedEcCurve,
203    /// Certificate parsing failed during a crypto operation.
204    CertificateParseFailed,
205    /// A certificate omitted its required EC curve parameter.
206    MissingEcCurveParameter,
207    /// A certificate had an invalid EC curve parameter.
208    InvalidEcCurveParameter,
209    /// A certificate had an invalid subject public key.
210    InvalidSubjectPublicKey,
211    /// A signature was not encoded in the expected format.
212    InvalidSignatureFormat,
213    /// A public key could not be parsed for the given group.
214    InvalidPublicKey(NamedGroup),
215    /// A private key could not be parsed in any supported format.
216    InvalidPrivateKey,
217    /// A signing key was used with a hash other than the one it is bound to.
218    SigningKeyHashMismatch {
219        /// The hash algorithm bound to the signing key.
220        key_hash: HashAlgorithm,
221        /// The hash algorithm requested by the caller.
222        requested: HashAlgorithm,
223    },
224    /// A signing key group does not support the requested hash algorithm.
225    SigningKeyUnsupportedHash {
226        /// The key group used for signing.
227        group: NamedGroup,
228        /// The requested hash algorithm.
229        hash: HashAlgorithm,
230    },
231    /// An AES-GCM key had the wrong length.
232    InvalidAesGcmKeySize {
233        /// The actual key length in bytes.
234        ///
235        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
236        actual: u16,
237    },
238    /// A ChaCha20-Poly1305 key had the wrong length.
239    InvalidChacha20Poly1305KeySize {
240        /// The actual key length in bytes.
241        ///
242        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
243        actual: u16,
244    },
245    /// An AES-128-CCM-8 key had the wrong length.
246    InvalidAes128Ccm8KeySize {
247        /// The actual key length in bytes.
248        ///
249        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
250        actual: u16,
251    },
252    /// A nonce was invalid for the selected cipher.
253    InvalidNonce,
254    /// A ciphertext was shorter than the selected AEAD permits.
255    CiphertextTooShort {
256        /// The minimum accepted ciphertext length in bytes.
257        minimum: u8,
258        /// The actual ciphertext length in bytes.
259        actual: u8,
260    },
261    /// The requested HKDF output length is too large.
262    HkdfOutputTooLong,
263    /// The HKDF label is too long to encode.
264    HkdfLabelTooLong,
265    /// The HKDF context is too long to encode.
266    HkdfContextTooLong,
267    /// The HKDF-Expand-Label output length is too large to encode.
268    HkdfOutputLengthTooLarge,
269    /// The `Finished` verify-data length was invalid.
270    InvalidVerifyDataLength,
271    /// The `Finished` verify-data is too long to encode.
272    VerifyDataTooLong,
273    /// The TLS 1.2 master secret is too long to encode.
274    MasterSecretTooLong,
275    /// The requested exported keying material is too long.
276    KeyingMaterialTooLong,
277    /// The TLS 1.2 pre-master secret is not available.
278    PreMasterSecretNotAvailable,
279    /// The TLS 1.2 master secret is not available.
280    MasterSecretNotAvailable,
281    /// The client random is not available.
282    ClientRandomNotAvailable,
283    /// The server random is not available.
284    ServerRandomNotAvailable,
285    /// The client cipher has not been initialized.
286    ClientCipherNotInitialized,
287    /// The server cipher has not been initialized.
288    ServerCipherNotInitialized,
289    /// A write IV is not available for the requested side.
290    WriteIvNotAvailable {
291        /// Whether the missing write IV is for the client side.
292        is_client: bool,
293    },
294    /// The DTLS 1.2 record IV length is unsupported for the selected suite.
295    UnsupportedDtls12RecordIvLen {
296        /// The unsupported record IV length.
297        ///
298        /// Values greater than `u16::MAX` are reported as `u16::MAX`.
299        len: u16,
300        /// The selected DTLS 1.2 cipher suite.
301        suite: Dtls12CipherSuite,
302    },
303    /// No private key is configured.
304    NoPrivateKeyConfigured,
305    /// A PSK operation was requested before a PSK was set.
306    PskNotSet,
307    /// The exporter master secret is not available.
308    ExporterMasterSecretNotDerived,
309    /// A provider operation failed without a more specific reason.
310    OperationFailed(CryptoOperation),
311}
312
313/// A cryptographic operation that can fail.
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315#[non_exhaustive]
316pub enum CryptoOperation {
317    /// Create an AEAD cipher instance.
318    CreateCipher,
319    /// Encrypt plaintext.
320    Encrypt,
321    /// Decrypt ciphertext.
322    Decrypt,
323    /// Sign a transcript or payload.
324    Sign,
325    /// Verify a signature.
326    VerifySignature,
327    /// Load a private key.
328    LoadPrivateKey,
329    /// Start a key exchange.
330    StartKeyExchange,
331    /// Complete a key exchange.
332    CompleteKeyExchange,
333    /// Generate an ephemeral key.
334    GenerateEphemeralKey,
335    /// Compute a public key.
336    ComputePublicKey,
337    /// Fill a buffer with random bytes.
338    FillRandom,
339    /// Compute an HMAC.
340    ComputeHmac,
341    /// Run the TLS 1.2 PRF.
342    Prf,
343    /// Run HKDF-Extract.
344    HkdfExtract,
345    /// Run HKDF-Expand.
346    HkdfExpand,
347    /// Run TLS HKDF-Expand-Label.
348    HkdfExpandLabel,
349    /// Derive a DTLS 1.3 early secret.
350    DeriveEarlySecret,
351    /// Derive a DTLS 1.3 derived secret.
352    DeriveDerivedSecret,
353    /// Derive a DTLS 1.3 handshake secret.
354    DeriveHandshakeSecret,
355    /// Derive a DTLS 1.3 traffic secret.
356    DeriveTrafficSecret,
357    /// Derive a DTLS 1.3 master secret.
358    DeriveMasterSecret,
359    /// Derive a DTLS 1.3 exporter master secret.
360    DeriveExporterMasterSecret,
361    /// Derive a DTLS 1.3 next-generation traffic secret.
362    DeriveNextTrafficSecret,
363    /// Derive an AEAD key.
364    DeriveKey,
365    /// Derive an AEAD IV.
366    DeriveIv,
367    /// Derive a record sequence-number encryption key.
368    DeriveSequenceNumberKey,
369    /// Derive a Finished-message key.
370    DeriveFinishedKey,
371    /// Compute Finished verify data.
372    ComputeVerifyData,
373    /// Verify Finished verify data.
374    VerifyData,
375    /// Compute a PSK pre-master secret.
376    ComputePskPreMasterSecret,
377    /// Compute a DTLS cookie.
378    ComputeCookie,
379    /// Extract SRTP keying material.
380    ExtractSrtpKeyingMaterial,
381    /// Encode a key.
382    EncodeKey,
383    /// Decode a key.
384    DecodeKey,
385}
386
387/// Fine-grained reason for an [`Error::CertificateError`].
388#[derive(Debug, Clone, PartialEq, Eq)]
389#[non_exhaustive]
390pub enum CertificateError {
391    /// The peer did not send a server certificate.
392    NoServerCertificateReceived,
393    /// Client certificate verification was requested with no client certificate.
394    NoClientCertificateForVerification,
395    /// Server certificate verification was requested with no server certificate.
396    NoServerCertificateForVerification,
397    /// A DTLS 1.3 server certificate carried a non-empty context.
398    ServerCertificateContextMustBeEmpty,
399    /// A DTLS 1.3 client certificate carried a non-empty context.
400    ClientCertificateContextMustBeEmpty,
401    /// The certificate operation needs an unsupported hash algorithm.
402    UnsupportedHashAlgorithm(HashAlgorithm),
403    /// Certificate parsing failed.
404    ParseFailed,
405    /// A certificate omitted its EC curve parameter.
406    MissingEcCurveParameter,
407    /// A certificate had an invalid EC curve parameter.
408    InvalidEcCurveParameter,
409    /// A certificate references an unsupported EC curve.
410    UnsupportedEcCurve,
411    /// A certificate had an invalid subject public key.
412    InvalidSubjectPublicKey,
413}
414
415/// Fine-grained reason for an [`Error::SecurityError`].
416#[derive(Debug, Clone, PartialEq, Eq)]
417#[non_exhaustive]
418pub enum SecurityError {
419    /// `HelloVerifyRequest` used an unsupported protocol version.
420    UnsupportedHelloVerifyRequestVersion(ProtocolVersion),
421    /// A server selected an unsupported protocol version.
422    UnsupportedServerVersion(ProtocolVersion),
423    /// A client offered an unsupported protocol version.
424    UnsupportedClientVersion(ProtocolVersion),
425    /// A server selected an unsupported DTLS 1.2 compression method.
426    UnsupportedServerCompression(CompressionMethod),
427    /// A client did not offer null compression.
428    UnsupportedClientCompression,
429    /// The selected key exchange algorithm is unsupported.
430    UnsupportedKeyExchangeAlgorithm,
431    /// The server selected a cipher suite that was not offered or recognized.
432    ServerSelectedUnknownCipherSuite,
433    /// The server selected a DTLS 1.2 cipher suite incompatible with local mode.
434    ServerSelectedIncompatibleCipherSuite(Dtls12CipherSuite),
435    /// The server selected a DTLS 1.2 cipher suite disallowed by configuration.
436    ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite),
437    /// The server selected a DTLS 1.3 cipher suite disallowed by configuration.
438    ServerSelectedDisallowedDtls13CipherSuite(Dtls13CipherSuite),
439    /// DTLS 1.2 extended master secret was required but not negotiated.
440    ExtendedMasterSecretNotNegotiated,
441    /// No mutually acceptable cipher suite was found.
442    NoMutuallyAcceptableCipherSuite,
443    /// A DTLS 1.3 ClientHello did not use the required DTLS 1.2 legacy version.
444    ClientHelloLegacyVersionNotDtls12,
445    /// A DTLS 1.3 ServerHello did not use the required DTLS 1.2 legacy version.
446    ServerHelloLegacyVersionNotDtls12,
447    /// A DTLS 1.3 ClientHello did not contain a recognized DTLS 1.3 version.
448    ClientHelloMissingDtls13SupportedVersions,
449    /// A ClientHello did not offer null compression.
450    ClientHelloMustOfferNullCompression,
451    /// The ClientHello cookie did not match the expected cookie.
452    InvalidCookieInClientHello,
453    /// A DTLS 1.3 ClientHello carried a non-empty legacy_cookie field.
454    InvalidLegacyCookieInClientHello,
455    /// The server attempted to send a second HelloRetryRequest.
456    CannotSendSecondHelloRetryRequest,
457    /// The client received a second HelloRetryRequest.
458    UnexpectedSecondHelloRetryRequest,
459    /// No common DTLS 1.3 cipher suite was found.
460    NoCommonCipherSuite,
461    /// No common DTLS 1.3 key exchange group was found.
462    NoCommonKeyExchangeGroup,
463    /// A HelloRetryRequest selected a disallowed cipher suite.
464    HrrSelectedDisallowedCipherSuite,
465    /// A HelloRetryRequest did not select DTLS 1.3.
466    HrrDidNotSelectDtls13,
467    /// A ServerHello selected a non-null compression method.
468    ServerHelloCompressionMustBeNull,
469    /// A server did not negotiate DTLS 1.3.
470    ServerDidNotNegotiateDtls13,
471    /// A DTLS 1.3 server did not send a key share.
472    ServerMissingKeyShare,
473    /// The server key share group did not match the expected group.
474    ServerKeyShareGroupMismatch {
475        /// The expected key exchange group.
476        expected: NamedGroup,
477        /// The key exchange group in the server key share.
478        actual: NamedGroup,
479    },
480    /// A signature was too large to encode.
481    SignatureTooLarge,
482    /// A signature scheme was used even though the peer did not offer it.
483    SignatureSchemeNotOffered(SignatureScheme),
484    /// A signature algorithm did not match the expected algorithm.
485    SignatureAlgorithmMismatch {
486        /// The expected signature algorithm.
487        expected: SignatureAlgorithm,
488        /// The actual signature algorithm.
489        actual: SignatureAlgorithm,
490    },
491    /// The signature scheme is unsupported.
492    UnsupportedSignatureScheme(SignatureScheme),
493    /// The signature scheme and certificate curve are incompatible.
494    SignatureSchemeCertificateCurveMismatch {
495        /// The signature scheme used for the operation.
496        scheme: SignatureScheme,
497        /// The certificate curve required by the signature scheme.
498        expected: NamedGroup,
499        /// The actual certificate curve.
500        actual: NamedGroup,
501    },
502    /// Server Finished verification failed.
503    ServerFinishedVerificationFailed,
504    /// Client Finished verification failed.
505    ClientFinishedVerificationFailed,
506    /// A fatal DTLS alert was received.
507    FatalAlert {
508        /// The DTLS alert description.
509        description: u8,
510    },
511}
512
513/// Fine-grained reason for an [`Error::PskError`].
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515#[non_exhaustive]
516pub enum PskError {
517    /// No PSK resolver is configured.
518    NoPskResolverConfigured,
519    /// No PSK identity is configured.
520    NoPskIdentityConfigured,
521    /// The configured PSK resolver did not return a key.
522    ResolverReturnedNoKey,
523}
524
525/// Fine-grained reason for an [`Error::Timeout`].
526#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527#[non_exhaustive]
528pub enum TimeoutError {
529    /// Timeout while waiting for an auto client hybrid ClientHello to resolve.
530    HybridClientHello,
531    /// Timeout while connecting.
532    Connect,
533    /// Timeout while handshaking.
534    Handshake,
535}
536
537/// Fine-grained reason for an [`Error::ConfigError`].
538#[derive(Debug, Clone, PartialEq, Eq)]
539#[non_exhaustive]
540pub enum ConfigError {
541    /// The configured MTU is smaller than dimpl permits.
542    MtuTooSmall {
543        /// The configured MTU.
544        mtu: u16,
545        /// The minimum accepted MTU.
546        minimum: u16,
547    },
548    /// The configured AEAD encryption limit is too small.
549    AeadEncryptionLimitTooSmall,
550    /// Cipher-suite filtering removed every available suite.
551    NoCipherSuitesAfterFiltering,
552    /// A PSK resolver is configured but no PSK cipher suite remains enabled.
553    PskConfiguredWithoutPskCipherSuite,
554    /// DTLS 1.2 suites are enabled but no compatible key exchange group remains enabled.
555    NoDtls12KeyExchangeGroupsAfterFiltering,
556    /// DTLS 1.3 suites are enabled but no key exchange group remains enabled.
557    NoDtls13KeyExchangeGroupsAfterFiltering,
558    /// Crypto provider validation failed.
559    CryptoProvider(CryptoProviderValidationError),
560}
561
562/// Fine-grained reason for crypto provider validation failure.
563#[derive(Debug, Clone, PartialEq, Eq)]
564#[non_exhaustive]
565pub enum CryptoProviderValidationError {
566    /// The provider has no cipher suites supported by dimpl.
567    NoCipherSuites,
568    /// The provider has ECDH cipher suites but no key exchange groups.
569    EcdhCipherSuitesWithoutKeyExchangeGroups,
570    /// The provider has no DTLS 1.3 cipher suites.
571    NoDtls13CipherSuites,
572    /// No hash test vector exists for the hash algorithm.
573    MissingHashTestVector(HashAlgorithm),
574    /// The provider hash implementation returned an unexpected value.
575    HashProviderIncorrect(HashAlgorithm),
576    /// The provider PRF operation failed.
577    PrfFailed {
578        /// The hash algorithm used by the PRF.
579        hash: HashAlgorithm,
580        /// The underlying crypto failure.
581        source: CryptoError,
582    },
583    /// No PRF test vector exists for the hash algorithm.
584    MissingPrfTestVector(HashAlgorithm),
585    /// The provider PRF returned incorrect output.
586    PrfIncorrect(HashAlgorithm),
587    /// No signature-validation vector exists for the algorithm pair.
588    NoSignatureValidationVector {
589        /// The hash algorithm used by the vector.
590        hash: HashAlgorithm,
591        /// The signature algorithm used by the vector.
592        signature: SignatureAlgorithm,
593    },
594    /// Provider signature verification failed.
595    SignatureVerificationFailed {
596        /// The hash algorithm used for verification.
597        hash: HashAlgorithm,
598        /// The signature algorithm used for verification.
599        signature: SignatureAlgorithm,
600        /// The underlying crypto failure.
601        source: CryptoError,
602    },
603    /// Provider HKDF validation failed.
604    HkdfFailed {
605        /// The DTLS 1.3 cipher suite under validation.
606        suite: Dtls13CipherSuite,
607        /// The underlying crypto failure.
608        source: CryptoError,
609    },
610    /// Provider HKDF returned empty output.
611    HkdfEmptyOutput(Dtls13CipherSuite),
612    /// No AEAD test vector exists for the suite.
613    NoAeadTestVector(Dtls13CipherSuite),
614    /// Creating the AEAD cipher failed.
615    AeadCreateFailed {
616        /// The DTLS 1.3 cipher suite under validation.
617        suite: Dtls13CipherSuite,
618        /// The underlying crypto failure.
619        source: CryptoError,
620    },
621    /// AEAD encryption failed.
622    AeadEncryptFailed {
623        /// The DTLS 1.3 cipher suite under validation.
624        suite: Dtls13CipherSuite,
625        /// The underlying crypto failure.
626        source: CryptoError,
627    },
628    /// AEAD encryption returned the wrong output.
629    AeadEncryptWrongOutput(Dtls13CipherSuite),
630    /// AEAD decryption failed.
631    AeadDecryptFailed {
632        /// The DTLS 1.3 cipher suite under validation.
633        suite: Dtls13CipherSuite,
634        /// The underlying crypto failure.
635        source: CryptoError,
636    },
637    /// AEAD decryption returned the wrong output.
638    AeadDecryptWrongOutput(Dtls13CipherSuite),
639    /// No record-number-encryption vector exists for the suite.
640    NoRecordNumberEncryptionTestVector(Dtls13CipherSuite),
641    /// Record-number encryption returned the wrong mask.
642    RecordNumberEncryptionWrongMask(Dtls13CipherSuite),
643    /// Starting key exchange failed.
644    KeyExchangeStartFailed {
645        /// The key exchange group under validation.
646        group: NamedGroup,
647        /// The underlying crypto failure.
648        source: CryptoError,
649    },
650    /// Completing key exchange failed.
651    KeyExchangeCompleteFailed {
652        /// The key exchange group under validation.
653        group: NamedGroup,
654        /// The underlying crypto failure.
655        source: CryptoError,
656    },
657    /// Two sides of a validation key exchange produced different shared secrets.
658    KeyExchangeMismatchedSharedSecret(NamedGroup),
659    /// HMAC validation failed.
660    HmacFailed(CryptoError),
661    /// HMAC validation returned incorrect output.
662    HmacIncorrect,
663}
664
665#[derive(Debug)]
666pub(crate) enum InternalError {
667    Transient(TransientError),
668    Fatal(Error),
669}
670
671#[derive(Debug)]
672pub(crate) enum TransientError {
673    ParseIncomplete,
674    Parse(nom::error::ErrorKind),
675    TooManyRecords,
676}
677
678impl InternalError {
679    pub(crate) fn parse_incomplete() -> Self {
680        Self::Transient(TransientError::ParseIncomplete)
681    }
682
683    pub(crate) fn parse(kind: nom::error::ErrorKind) -> Self {
684        Self::Transient(TransientError::Parse(kind))
685    }
686
687    pub(crate) fn too_many_records() -> Self {
688        Self::Transient(TransientError::TooManyRecords)
689    }
690
691    pub(crate) fn into_public_error(self) -> Option<Error> {
692        match self {
693            Self::Transient(err) => {
694                debug!("Discarding packet: {err}");
695                None
696            }
697            Self::Fatal(err) => Some(err),
698        }
699    }
700}
701
702impl From<Error> for InternalError {
703    fn from(value: Error) -> Self {
704        Self::Fatal(value)
705    }
706}
707
708impl<'a> From<nom::Err<nom::error::Error<&'a [u8]>>> for InternalError {
709    fn from(value: nom::Err<nom::error::Error<&'a [u8]>>) -> Self {
710        match value {
711            nom::Err::Incomplete(_) => InternalError::parse_incomplete(),
712            nom::Err::Error(x) => InternalError::parse(x.code),
713            nom::Err::Failure(x) => InternalError::parse(x.code),
714        }
715    }
716}
717
718impl From<CryptoError> for Error {
719    fn from(value: CryptoError) -> Self {
720        Self::CryptoError(value)
721    }
722}
723
724impl From<CertificateError> for Error {
725    fn from(value: CertificateError) -> Self {
726        Self::CertificateError(value)
727    }
728}
729
730impl From<SecurityError> for Error {
731    fn from(value: SecurityError) -> Self {
732        Self::SecurityError(value)
733    }
734}
735
736impl From<PskError> for Error {
737    fn from(value: PskError) -> Self {
738        Self::PskError(value)
739    }
740}
741
742impl From<ConfigError> for Error {
743    fn from(value: ConfigError) -> Self {
744        Self::ConfigError(value)
745    }
746}
747
748impl std::error::Error for Error {}
749
750impl fmt::Display for InternalError {
751    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
752        match self {
753            InternalError::Transient(err) => err.fmt(f),
754            InternalError::Fatal(err) => err.fmt(f),
755        }
756    }
757}
758
759impl fmt::Display for TransientError {
760    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
761        match self {
762            TransientError::ParseIncomplete => write!(f, "parse incomplete"),
763            TransientError::Parse(kind) => write!(f, "parse error: {:?}", kind),
764            TransientError::TooManyRecords => write!(f, "too many records in packet"),
765        }
766    }
767}
768
769impl fmt::Display for Error {
770    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771        match self {
772            Error::UnexpectedMessage(err) => write!(f, "unexpected message: {err}"),
773            Error::InvalidState(err) => write!(f, "invalid state: {err}"),
774            Error::CryptoError(err) => write!(f, "crypto error: {err}"),
775            Error::CertificateError(err) => write!(f, "certificate error: {err}"),
776            Error::SecurityError(err) => write!(f, "security error: {err}"),
777            Error::PskError(err) => write!(f, "psk error: {err}"),
778            Error::ReceiveQueueFull => write!(f, "receive queue full"),
779            Error::TransmitQueueFull => write!(f, "transmit queue full"),
780            Error::IncompleteServerHello => write!(f, "incomplete ServerHello"),
781            Error::Timeout(err) => write!(f, "timeout: {err}"),
782            Error::ConfigError(err) => write!(f, "config error: {err}"),
783            Error::RenegotiationAttempt => write!(f, "peer attempted renegotiation"),
784            Error::HandshakePending => {
785                write!(f, "handshake pending: cannot send application data yet")
786            }
787            Error::TooManyClientHelloFragments => write!(f, "too many client hello fragments"),
788            Error::ConnectionClosed => write!(f, "connection closed"),
789            Error::Dtls12Fallback => write!(f, "dtls 1.2 fallback (internal)"),
790        }
791    }
792}
793
794impl fmt::Display for UnexpectedMessageError {
795    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
796        match self {
797            Self::UnrecognizedAutoServerResponse => write!(f, "unrecognized response from server"),
798            Self::ServerKeyExchangeWithoutSignature => {
799                write!(f, "ServerKeyExchange without signature")
800            }
801            Self::PskServerKeyExchangeInEcdhePath => {
802                write!(f, "PSK ServerKeyExchange in ECDHE path")
803            }
804            Self::EcdheServerKeyExchangeInPskPath => {
805                write!(f, "ECDHE ServerKeyExchange in PSK path")
806            }
807            Self::PskClientKeyExchangeInEcdhePath => {
808                write!(f, "PSK ClientKeyExchange in ECDHE path")
809            }
810            Self::EcdheClientKeyExchangeInPskPath => {
811                write!(f, "ECDHE ClientKeyExchange in PSK path")
812            }
813            Self::CertificateRequestContextTruncated => {
814                write!(f, "CertificateRequest context truncated")
815            }
816            Self::CertificateRequestExtensionsTruncated => {
817                write!(f, "CertificateRequest extensions truncated")
818            }
819        }
820    }
821}
822
823impl fmt::Display for InvalidStateError {
824    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
825        match self {
826            Self::NoCipherSuiteSelected => write!(f, "no cipher suite selected"),
827            Self::NoCipherSuite => write!(f, "no cipher suite"),
828            Self::NoClientRandom => write!(f, "no client random"),
829            Self::NoServerRandom => write!(f, "no server random"),
830            Self::NoSharedSecretForHandshakeKeyDerivation => {
831                write!(f, "no shared secret for handshake key derivation")
832            }
833            Self::NoServerHandshakeTrafficSecret => {
834                write!(f, "no server handshake traffic secret")
835            }
836            Self::NoServerHandshakeTrafficSecretForFinished => {
837                write!(f, "no server handshake traffic secret for Finished")
838            }
839            Self::NoClientHandshakeTrafficSecret => {
840                write!(f, "no client handshake traffic secret")
841            }
842            Self::NoClientHandshakeTrafficSecretForFinished => {
843                write!(f, "no client handshake traffic secret for Finished")
844            }
845            Self::NoHandshakeSecretForApplicationKeyDerivation => {
846                write!(f, "no handshake secret for application key derivation")
847            }
848            Self::NoActiveKeyExchange => write!(f, "no active key exchange"),
849            Self::NoCurrentAppSendKeysForKeyUpdate => {
850                write!(f, "no current app send keys for KeyUpdate")
851            }
852            Self::NoCurrentAppRecvKeysForKeyUpdate => {
853                write!(f, "no current app recv keys for KeyUpdate")
854            }
855            Self::ExporterMasterSecretNotDerived => {
856                write!(f, "exporter master secret not yet derived")
857            }
858            Self::ExtendedMasterSecretSessionHashMissing => {
859                write!(
860                    f,
861                    "extended master secret negotiated but session hash not captured"
862                )
863            }
864        }
865    }
866}
867
868impl fmt::Display for CryptoError {
869    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
870        match self {
871            Self::NoSupportedKeyExchangeGroups => write!(f, "no supported key exchange groups"),
872            Self::NoDtls12KeyExchangeGroupsConfigured => {
873                write!(f, "no DTLS 1.2 key exchange groups configured")
874            }
875            Self::Epoch0SequenceNumberExhausted => {
876                write!(f, "epoch 0 sequence number exhausted")
877            }
878            Self::SendSequenceNumberExhausted { epoch } => {
879                write!(f, "send sequence number exhausted for epoch {epoch}")
880            }
881            Self::SendKeysNotAvailable { epoch } => {
882                write!(f, "send keys not available for epoch {epoch}")
883            }
884            Self::RecvKeysNotAvailable { epoch } => {
885                write!(f, "recv keys not available for epoch {epoch}")
886            }
887            Self::KeyExchangeGroupNotFound(group) => {
888                write!(f, "key exchange group not found: {group:?}")
889            }
890            Self::KeyExchangeNotInitialized => write!(f, "key exchange not initialized"),
891            Self::UnsupportedKeyExchangeGroup(group) => {
892                write!(f, "unsupported key exchange group: {group:?}")
893            }
894            Self::UnsupportedEcdheNamedGroup(group) => {
895                write!(f, "unsupported ECDHE named group: {group:?}")
896            }
897            Self::UnsupportedCipherSuite(suite) => {
898                write!(f, "unsupported cipher suite: {suite:?}")
899            }
900            Self::UnsupportedHmacHash(hash) => {
901                write!(f, "unsupported HMAC hash algorithm: {hash:?}")
902            }
903            Self::UnsupportedSignatureAlgorithm(sig) => {
904                write!(f, "unsupported signature algorithm: {sig:?}")
905            }
906            Self::SignatureAlgorithmNotOfferedByClient => {
907                write!(f, "signature algorithm not offered by client")
908            }
909            Self::SignatureAlgorithmMismatch { expected, actual } => {
910                write!(
911                    f,
912                    "signature algorithm mismatch: {actual:?} != {expected:?}"
913                )
914            }
915            Self::UnsupportedSignaturePair { signature, hash } => {
916                write!(f, "unsupported signature algorithm: {signature:?}/{hash:?}")
917            }
918            Self::UnsupportedSignatureVerification {
919                signature,
920                hash,
921                group,
922            } => write!(
923                f,
924                "unsupported signature verification: {signature:?} + {hash:?} + {group:?}"
925            ),
926            Self::SignatureVerificationFailed {
927                signature,
928                hash,
929                group,
930            } => write!(
931                f,
932                "signature verification failed: {signature:?} + {hash:?} + {group:?}"
933            ),
934            Self::UnsupportedPublicKeyAlgorithm => write!(f, "unsupported public key algorithm"),
935            Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"),
936            Self::CertificateParseFailed => write!(f, "failed to parse certificate"),
937            Self::MissingEcCurveParameter => {
938                write!(f, "missing EC curve parameter in certificate")
939            }
940            Self::InvalidEcCurveParameter => {
941                write!(f, "invalid EC curve parameter in certificate")
942            }
943            Self::InvalidSubjectPublicKey => {
944                write!(f, "invalid EC subject_public_key bitstring")
945            }
946            Self::InvalidSignatureFormat => write!(f, "invalid signature format"),
947            Self::InvalidPublicKey(group) => write!(f, "invalid {group:?} public key"),
948            Self::InvalidPrivateKey => {
949                write!(f, "failed to parse private key in any supported format")
950            }
951            Self::SigningKeyHashMismatch {
952                key_hash,
953                requested,
954            } => write!(
955                f,
956                "signing key is locked to {key_hash:?} but {requested:?} was requested"
957            ),
958            Self::SigningKeyUnsupportedHash { group, hash } => {
959                write!(f, "{group:?} key does not support hash algorithm {hash:?}")
960            }
961            Self::InvalidAesGcmKeySize { actual } => {
962                write!(f, "invalid key size for AES-GCM: {actual}")
963            }
964            Self::InvalidChacha20Poly1305KeySize { actual } => {
965                write!(f, "invalid key size for CHACHA20-POLY1305: {actual}")
966            }
967            Self::InvalidAes128Ccm8KeySize { actual } => {
968                write!(f, "invalid key size for AES-128-CCM-8: {actual}")
969            }
970            Self::InvalidNonce => write!(f, "invalid nonce"),
971            Self::CiphertextTooShort { minimum, actual } => {
972                write!(f, "ciphertext too short: got {actual}, minimum {minimum}")
973            }
974            Self::HkdfOutputTooLong => write!(f, "HKDF output too long"),
975            Self::HkdfLabelTooLong => write!(f, "label too long for HKDF-Expand-Label"),
976            Self::HkdfContextTooLong => write!(f, "context too long for HKDF-Expand-Label"),
977            Self::HkdfOutputLengthTooLarge => {
978                write!(f, "output length too large for HKDF-Expand-Label")
979            }
980            Self::InvalidVerifyDataLength => write!(f, "invalid verify data length"),
981            Self::VerifyDataTooLong => write!(f, "verify data too long"),
982            Self::MasterSecretTooLong => write!(f, "master secret too long"),
983            Self::KeyingMaterialTooLong => write!(f, "keying material too long"),
984            Self::PreMasterSecretNotAvailable => write!(f, "pre-master secret not available"),
985            Self::MasterSecretNotAvailable => write!(f, "master secret not available"),
986            Self::ClientRandomNotAvailable => write!(f, "client random not available"),
987            Self::ServerRandomNotAvailable => write!(f, "server random not available"),
988            Self::ClientCipherNotInitialized => write!(f, "client cipher not initialized"),
989            Self::ServerCipherNotInitialized => write!(f, "server cipher not initialized"),
990            Self::WriteIvNotAvailable { is_client } => {
991                let side = if *is_client { "client" } else { "server" };
992                write!(f, "{side} write IV not available")
993            }
994            Self::UnsupportedDtls12RecordIvLen { len, suite } => {
995                write!(f, "unsupported DTLS 1.2 record_iv_len={len} for {suite:?}")
996            }
997            Self::NoPrivateKeyConfigured => write!(f, "no private key configured"),
998            Self::PskNotSet => write!(f, "PSK not set"),
999            Self::ExporterMasterSecretNotDerived => {
1000                write!(f, "exporter master secret not yet derived")
1001            }
1002            Self::OperationFailed(op) => write!(f, "{op} failed"),
1003        }
1004    }
1005}
1006
1007impl fmt::Display for CryptoOperation {
1008    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1009        let text = match self {
1010            Self::CreateCipher => "cipher creation",
1011            Self::Encrypt => "encryption",
1012            Self::Decrypt => "decryption",
1013            Self::Sign => "signing",
1014            Self::VerifySignature => "signature verification",
1015            Self::LoadPrivateKey => "private key loading",
1016            Self::StartKeyExchange => "key exchange start",
1017            Self::CompleteKeyExchange => "key exchange completion",
1018            Self::GenerateEphemeralKey => "ephemeral key generation",
1019            Self::ComputePublicKey => "public key computation",
1020            Self::FillRandom => "random generation",
1021            Self::ComputeHmac => "HMAC computation",
1022            Self::Prf => "PRF",
1023            Self::HkdfExtract => "HKDF extract",
1024            Self::HkdfExpand => "HKDF expand",
1025            Self::HkdfExpandLabel => "HKDF expand label",
1026            Self::DeriveEarlySecret => "early secret derivation",
1027            Self::DeriveDerivedSecret => "derived secret derivation",
1028            Self::DeriveHandshakeSecret => "handshake secret derivation",
1029            Self::DeriveTrafficSecret => "traffic secret derivation",
1030            Self::DeriveMasterSecret => "master secret derivation",
1031            Self::DeriveExporterMasterSecret => "exporter master secret derivation",
1032            Self::DeriveNextTrafficSecret => "next traffic secret derivation",
1033            Self::DeriveKey => "key derivation",
1034            Self::DeriveIv => "IV derivation",
1035            Self::DeriveSequenceNumberKey => "sequence number key derivation",
1036            Self::DeriveFinishedKey => "Finished key derivation",
1037            Self::ComputeVerifyData => "verify data computation",
1038            Self::VerifyData => "verify data verification",
1039            Self::ComputePskPreMasterSecret => "PSK pre-master secret computation",
1040            Self::ComputeCookie => "cookie computation",
1041            Self::ExtractSrtpKeyingMaterial => "SRTP keying material extraction",
1042            Self::EncodeKey => "key encoding",
1043            Self::DecodeKey => "key decoding",
1044        };
1045        write!(f, "{text}")
1046    }
1047}
1048
1049impl fmt::Display for CertificateError {
1050    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1051        match self {
1052            Self::NoServerCertificateReceived => write!(f, "no server certificate received"),
1053            Self::NoClientCertificateForVerification => {
1054                write!(f, "no client certificate for verification")
1055            }
1056            Self::NoServerCertificateForVerification => {
1057                write!(f, "no server certificate for verification")
1058            }
1059            Self::ServerCertificateContextMustBeEmpty => {
1060                write!(f, "server certificate context must be empty")
1061            }
1062            Self::ClientCertificateContextMustBeEmpty => {
1063                write!(f, "client certificate context must be empty")
1064            }
1065            Self::UnsupportedHashAlgorithm(hash) => {
1066                write!(f, "unsupported hash algorithm: {hash:?}")
1067            }
1068            Self::ParseFailed => write!(f, "failed to parse certificate"),
1069            Self::MissingEcCurveParameter => {
1070                write!(f, "missing EC curve parameter in certificate")
1071            }
1072            Self::InvalidEcCurveParameter => {
1073                write!(f, "invalid EC curve parameter in certificate")
1074            }
1075            Self::UnsupportedEcCurve => write!(f, "unsupported EC curve"),
1076            Self::InvalidSubjectPublicKey => {
1077                write!(f, "invalid EC subject_public_key bitstring")
1078            }
1079        }
1080    }
1081}
1082
1083impl fmt::Display for SecurityError {
1084    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1085        match self {
1086            Self::UnsupportedHelloVerifyRequestVersion(version) => {
1087                write!(
1088                    f,
1089                    "unsupported DTLS version in HelloVerifyRequest: {version:?}"
1090                )
1091            }
1092            Self::UnsupportedServerVersion(version) => {
1093                write!(f, "unsupported DTLS version from server: {version:?}")
1094            }
1095            Self::UnsupportedClientVersion(version) => {
1096                write!(f, "unsupported DTLS version from client: {version:?}")
1097            }
1098            Self::UnsupportedServerCompression(compression) => {
1099                write!(
1100                    f,
1101                    "unsupported compression method from server: {compression:?}"
1102                )
1103            }
1104            Self::UnsupportedClientCompression => {
1105                write!(f, "client did not offer null compression")
1106            }
1107            Self::UnsupportedKeyExchangeAlgorithm => {
1108                write!(f, "unsupported key exchange algorithm")
1109            }
1110            Self::ServerSelectedUnknownCipherSuite => {
1111                write!(f, "server selected unknown cipher suite")
1112            }
1113            Self::ServerSelectedIncompatibleCipherSuite(suite) => {
1114                write!(f, "server selected incompatible cipher suite: {suite:?}")
1115            }
1116            Self::ServerSelectedDisallowedCipherSuite(suite) => {
1117                write!(f, "server selected disallowed cipher suite: {suite:?}")
1118            }
1119            Self::ServerSelectedDisallowedDtls13CipherSuite(suite) => {
1120                write!(f, "server selected disallowed cipher suite: {suite:?}")
1121            }
1122            Self::ExtendedMasterSecretNotNegotiated => {
1123                write!(f, "extended master secret not negotiated")
1124            }
1125            Self::NoMutuallyAcceptableCipherSuite => {
1126                write!(f, "no mutually acceptable cipher suite")
1127            }
1128            Self::ClientHelloLegacyVersionNotDtls12 => {
1129                write!(f, "ClientHello legacy_version must be DTLS 1.2")
1130            }
1131            Self::ServerHelloLegacyVersionNotDtls12 => {
1132                write!(f, "ServerHello legacy_version must be DTLS 1.2")
1133            }
1134            Self::ClientHelloMissingDtls13SupportedVersions => {
1135                write!(f, "ClientHello missing DTLS 1.3 supported_versions")
1136            }
1137            Self::ClientHelloMustOfferNullCompression => {
1138                write!(f, "ClientHello must offer null compression")
1139            }
1140            Self::InvalidCookieInClientHello => write!(f, "invalid cookie in ClientHello"),
1141            Self::InvalidLegacyCookieInClientHello => {
1142                write!(f, "ClientHello legacy_cookie must be empty")
1143            }
1144            Self::CannotSendSecondHelloRetryRequest => {
1145                write!(f, "cannot send second HelloRetryRequest")
1146            }
1147            Self::UnexpectedSecondHelloRetryRequest => {
1148                write!(f, "received second HelloRetryRequest")
1149            }
1150            Self::NoCommonCipherSuite => write!(f, "no common cipher suite found"),
1151            Self::NoCommonKeyExchangeGroup => write!(f, "no common key exchange group"),
1152            Self::HrrSelectedDisallowedCipherSuite => {
1153                write!(f, "HRR selected disallowed cipher suite")
1154            }
1155            Self::HrrDidNotSelectDtls13 => write!(f, "HRR did not select DTLS 1.3"),
1156            Self::ServerHelloCompressionMustBeNull => {
1157                write!(f, "ServerHello compression must be null")
1158            }
1159            Self::ServerDidNotNegotiateDtls13 => {
1160                write!(f, "server did not negotiate DTLS 1.3")
1161            }
1162            Self::ServerMissingKeyShare => write!(f, "server missing key_share"),
1163            Self::ServerKeyShareGroupMismatch { expected, actual } => {
1164                write!(
1165                    f,
1166                    "server key_share group mismatch: expected {expected:?}, actual {actual:?}"
1167                )
1168            }
1169            Self::SignatureTooLarge => write!(f, "signature too large"),
1170            Self::SignatureSchemeNotOffered(scheme) => {
1171                write!(f, "signature scheme {scheme:?} was not offered")
1172            }
1173            Self::SignatureAlgorithmMismatch { expected, actual } => {
1174                write!(
1175                    f,
1176                    "signature algorithm mismatch: expected {expected:?}, got {actual:?}"
1177                )
1178            }
1179            Self::UnsupportedSignatureScheme(scheme) => {
1180                write!(f, "unsupported signature scheme: {scheme:?}")
1181            }
1182            Self::SignatureSchemeCertificateCurveMismatch {
1183                scheme,
1184                expected,
1185                actual,
1186            } => write!(
1187                f,
1188                "signature scheme {scheme:?} requires {expected:?} but certificate uses {actual:?}"
1189            ),
1190            Self::ServerFinishedVerificationFailed => {
1191                write!(f, "server Finished verification failed")
1192            }
1193            Self::ClientFinishedVerificationFailed => {
1194                write!(f, "client Finished verification failed")
1195            }
1196            Self::FatalAlert { description } => {
1197                write!(f, "received fatal alert: description={description}")
1198            }
1199        }
1200    }
1201}
1202
1203impl fmt::Display for PskError {
1204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1205        match self {
1206            Self::NoPskResolverConfigured => write!(f, "no PSK resolver configured"),
1207            Self::NoPskIdentityConfigured => write!(f, "no PSK identity configured"),
1208            Self::ResolverReturnedNoKey => write!(f, "PSK resolver returned no key"),
1209        }
1210    }
1211}
1212
1213impl fmt::Display for TimeoutError {
1214    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1215        match self {
1216            Self::HybridClientHello => write!(f, "hybrid ClientHello"),
1217            Self::Connect => write!(f, "connect"),
1218            Self::Handshake => write!(f, "handshake"),
1219        }
1220    }
1221}
1222
1223impl fmt::Display for ConfigError {
1224    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1225        match self {
1226            Self::MtuTooSmall { mtu, minimum } => {
1227                write!(f, "MTU {mtu} is too small (minimum {minimum})")
1228            }
1229            Self::AeadEncryptionLimitTooSmall => {
1230                write!(f, "aead_encryption_limit must be at least 1")
1231            }
1232            Self::NoCipherSuitesAfterFiltering => write!(
1233                f,
1234                concat!(
1235                    "no cipher suites remain after filtering; at least one DTLS 1.2 or ",
1236                    "DTLS 1.3 cipher suite must be available"
1237                )
1238            ),
1239            Self::PskConfiguredWithoutPskCipherSuite => write!(
1240                f,
1241                "PSK is configured but no PSK cipher suite remains after filtering DTLS 1.2 suites"
1242            ),
1243            Self::NoDtls12KeyExchangeGroupsAfterFiltering => write!(
1244                f,
1245                concat!(
1246                    "DTLS 1.2 cipher suites are enabled but no compatible key exchange ",
1247                    "groups remain after filtering"
1248                )
1249            ),
1250            Self::NoDtls13KeyExchangeGroupsAfterFiltering => write!(
1251                f,
1252                "DTLS 1.3 cipher suites are enabled but no key exchange groups remain after filtering"
1253            ),
1254            Self::CryptoProvider(err) => write!(f, "crypto provider validation failed: {err}"),
1255        }
1256    }
1257}
1258
1259impl fmt::Display for CryptoProviderValidationError {
1260    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1261        match self {
1262            Self::NoCipherSuites => {
1263                write!(f, "CryptoProvider has no cipher suites supported by dimpl")
1264            }
1265            Self::EcdhCipherSuitesWithoutKeyExchangeGroups => write!(
1266                f,
1267                "CryptoProvider has ECDH cipher suites but no supported key exchange groups"
1268            ),
1269            Self::NoDtls13CipherSuites => {
1270                write!(f, "CryptoProvider has no DTLS 1.3 cipher suites")
1271            }
1272            Self::MissingHashTestVector(hash) => {
1273                write!(f, "no expected hash data for hash algorithm: {hash:?}")
1274            }
1275            Self::HashProviderIncorrect(hash) => {
1276                write!(f, "hash provider {hash:?} produced incorrect result")
1277            }
1278            Self::PrfFailed { hash, source } => write!(f, "PRF failed for {hash:?}: {source}"),
1279            Self::MissingPrfTestVector(hash) => {
1280                write!(f, "no expected PRF data for hash algorithm: {hash:?}")
1281            }
1282            Self::PrfIncorrect(hash) => write!(f, "PRF {hash:?} produced incorrect result"),
1283            Self::NoSignatureValidationVector { hash, signature } => {
1284                write!(f, "no validation test vectors for {hash:?} + {signature:?}")
1285            }
1286            Self::SignatureVerificationFailed {
1287                hash,
1288                signature,
1289                source,
1290            } => write!(
1291                f,
1292                "signature verification failed for {hash:?} + {signature:?}: {source}"
1293            ),
1294            Self::HkdfFailed { suite, source } => {
1295                write!(f, "HKDF failed for DTLS 1.3 suite {suite:?}: {source}")
1296            }
1297            Self::HkdfEmptyOutput(suite) => {
1298                write!(f, "HKDF returned empty output for {suite:?}")
1299            }
1300            Self::NoAeadTestVector(suite) => {
1301                write!(f, "no AEAD test vector for DTLS 1.3 suite {suite:?}")
1302            }
1303            Self::AeadCreateFailed { suite, source } => {
1304                write!(f, "failed to create cipher for {suite:?}: {source}")
1305            }
1306            Self::AeadEncryptFailed { suite, source } => {
1307                write!(f, "AEAD encrypt failed for {suite:?}: {source}")
1308            }
1309            Self::AeadEncryptWrongOutput(suite) => {
1310                write!(f, "AEAD encrypt produced wrong output for {suite:?}")
1311            }
1312            Self::AeadDecryptFailed { suite, source } => {
1313                write!(f, "AEAD decrypt failed for {suite:?}: {source}")
1314            }
1315            Self::AeadDecryptWrongOutput(suite) => {
1316                write!(f, "AEAD decrypt produced wrong output for {suite:?}")
1317            }
1318            Self::NoRecordNumberEncryptionTestVector(suite) => {
1319                write!(f, "no encrypt_sn test vector for DTLS 1.3 suite {suite:?}")
1320            }
1321            Self::RecordNumberEncryptionWrongMask(suite) => {
1322                write!(f, "encrypt_sn produced wrong mask for {suite:?}")
1323            }
1324            Self::KeyExchangeStartFailed { group, source } => {
1325                write!(f, "key exchange start failed for {group:?}: {source}")
1326            }
1327            Self::KeyExchangeCompleteFailed { group, source } => {
1328                write!(f, "key exchange complete failed for {group:?}: {source}")
1329            }
1330            Self::KeyExchangeMismatchedSharedSecret(group) => {
1331                write!(f, "key exchange produced different secrets for {group:?}")
1332            }
1333            Self::HmacFailed(source) => write!(f, "HMAC provider failed: {source}"),
1334            Self::HmacIncorrect => {
1335                write!(f, "HMAC provider produced incorrect result for HMAC-SHA256")
1336            }
1337        }
1338    }
1339}