1use 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]
20pub enum Error {
22 UnexpectedMessage(UnexpectedMessageError),
24 InvalidState(InvalidStateError),
26 CryptoError(CryptoError),
28 CertificateError(CertificateError),
30 SecurityError(SecurityError),
32 PskError(PskError),
34 ReceiveQueueFull,
36 TransmitQueueFull,
38 IncompleteServerHello,
40 Timeout(TimeoutError),
42 ConfigError(ConfigError),
44 RenegotiationAttempt,
46 HandshakePending,
52 ConnectionClosed,
54 TooManyClientHelloFragments,
57 #[doc(hidden)]
65 Dtls12Fallback,
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
70#[non_exhaustive]
71pub enum UnexpectedMessageError {
72 UnrecognizedAutoServerResponse,
74 ServerKeyExchangeWithoutSignature,
76 PskServerKeyExchangeInEcdhePath,
78 EcdheServerKeyExchangeInPskPath,
80 PskClientKeyExchangeInEcdhePath,
82 EcdheClientKeyExchangeInPskPath,
84 CertificateRequestContextTruncated,
86 CertificateRequestExtensionsTruncated,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92#[non_exhaustive]
93pub enum InvalidStateError {
94 NoCipherSuiteSelected,
96 NoCipherSuite,
98 NoClientRandom,
100 NoServerRandom,
102 NoSharedSecretForHandshakeKeyDerivation,
104 NoServerHandshakeTrafficSecret,
106 NoServerHandshakeTrafficSecretForFinished,
108 NoClientHandshakeTrafficSecret,
110 NoClientHandshakeTrafficSecretForFinished,
112 NoHandshakeSecretForApplicationKeyDerivation,
114 NoActiveKeyExchange,
116 NoCurrentAppSendKeysForKeyUpdate,
118 NoCurrentAppRecvKeysForKeyUpdate,
120 ExporterMasterSecretNotDerived,
122 ExtendedMasterSecretSessionHashMissing,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum CryptoError {
130 NoSupportedKeyExchangeGroups,
132 NoDtls12KeyExchangeGroupsConfigured,
134 Epoch0SequenceNumberExhausted,
136 SendSequenceNumberExhausted {
138 epoch: u16,
140 },
141 SendKeysNotAvailable {
143 epoch: u16,
145 },
146 RecvKeysNotAvailable {
148 epoch: u16,
150 },
151 KeyExchangeGroupNotFound(NamedGroup),
153 KeyExchangeNotInitialized,
155 UnsupportedKeyExchangeGroup(NamedGroup),
157 UnsupportedEcdheNamedGroup(NamedGroup),
159 UnsupportedCipherSuite(Dtls12CipherSuite),
161 UnsupportedHmacHash(HashAlgorithm),
163 UnsupportedSignatureAlgorithm(SignatureAlgorithm),
165 SignatureAlgorithmNotOfferedByClient,
167 SignatureAlgorithmMismatch {
169 expected: SignatureAlgorithm,
171 actual: SignatureAlgorithm,
173 },
174 UnsupportedSignaturePair {
176 signature: SignatureAlgorithm,
178 hash: HashAlgorithm,
180 },
181 UnsupportedSignatureVerification {
183 signature: SignatureAlgorithm,
185 hash: HashAlgorithm,
187 group: NamedGroup,
189 },
190 SignatureVerificationFailed {
192 signature: SignatureAlgorithm,
194 hash: HashAlgorithm,
196 group: NamedGroup,
198 },
199 UnsupportedPublicKeyAlgorithm,
201 UnsupportedEcCurve,
203 CertificateParseFailed,
205 MissingEcCurveParameter,
207 InvalidEcCurveParameter,
209 InvalidSubjectPublicKey,
211 InvalidSignatureFormat,
213 InvalidPublicKey(NamedGroup),
215 InvalidPrivateKey,
217 SigningKeyHashMismatch {
219 key_hash: HashAlgorithm,
221 requested: HashAlgorithm,
223 },
224 SigningKeyUnsupportedHash {
226 group: NamedGroup,
228 hash: HashAlgorithm,
230 },
231 InvalidAesGcmKeySize {
233 actual: u16,
237 },
238 InvalidChacha20Poly1305KeySize {
240 actual: u16,
244 },
245 InvalidAes128Ccm8KeySize {
247 actual: u16,
251 },
252 InvalidNonce,
254 CiphertextTooShort {
256 minimum: u8,
258 actual: u8,
260 },
261 HkdfOutputTooLong,
263 HkdfLabelTooLong,
265 HkdfContextTooLong,
267 HkdfOutputLengthTooLarge,
269 InvalidVerifyDataLength,
271 VerifyDataTooLong,
273 MasterSecretTooLong,
275 KeyingMaterialTooLong,
277 PreMasterSecretNotAvailable,
279 MasterSecretNotAvailable,
281 ClientRandomNotAvailable,
283 ServerRandomNotAvailable,
285 ClientCipherNotInitialized,
287 ServerCipherNotInitialized,
289 WriteIvNotAvailable {
291 is_client: bool,
293 },
294 UnsupportedDtls12RecordIvLen {
296 len: u16,
300 suite: Dtls12CipherSuite,
302 },
303 NoPrivateKeyConfigured,
305 PskNotSet,
307 ExporterMasterSecretNotDerived,
309 OperationFailed(CryptoOperation),
311}
312
313#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315#[non_exhaustive]
316pub enum CryptoOperation {
317 CreateCipher,
319 Encrypt,
321 Decrypt,
323 Sign,
325 VerifySignature,
327 LoadPrivateKey,
329 StartKeyExchange,
331 CompleteKeyExchange,
333 GenerateEphemeralKey,
335 ComputePublicKey,
337 FillRandom,
339 ComputeHmac,
341 Prf,
343 HkdfExtract,
345 HkdfExpand,
347 HkdfExpandLabel,
349 DeriveEarlySecret,
351 DeriveDerivedSecret,
353 DeriveHandshakeSecret,
355 DeriveTrafficSecret,
357 DeriveMasterSecret,
359 DeriveExporterMasterSecret,
361 DeriveNextTrafficSecret,
363 DeriveKey,
365 DeriveIv,
367 DeriveSequenceNumberKey,
369 DeriveFinishedKey,
371 ComputeVerifyData,
373 VerifyData,
375 ComputePskPreMasterSecret,
377 ComputeCookie,
379 ExtractSrtpKeyingMaterial,
381 EncodeKey,
383 DecodeKey,
385}
386
387#[derive(Debug, Clone, PartialEq, Eq)]
389#[non_exhaustive]
390pub enum CertificateError {
391 NoServerCertificateReceived,
393 NoClientCertificateForVerification,
395 NoServerCertificateForVerification,
397 ServerCertificateContextMustBeEmpty,
399 ClientCertificateContextMustBeEmpty,
401 UnsupportedHashAlgorithm(HashAlgorithm),
403 ParseFailed,
405 MissingEcCurveParameter,
407 InvalidEcCurveParameter,
409 UnsupportedEcCurve,
411 InvalidSubjectPublicKey,
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
417#[non_exhaustive]
418pub enum SecurityError {
419 UnsupportedHelloVerifyRequestVersion(ProtocolVersion),
421 UnsupportedServerVersion(ProtocolVersion),
423 UnsupportedClientVersion(ProtocolVersion),
425 UnsupportedServerCompression(CompressionMethod),
427 UnsupportedClientCompression,
429 UnsupportedKeyExchangeAlgorithm,
431 ServerSelectedUnknownCipherSuite,
433 ServerSelectedIncompatibleCipherSuite(Dtls12CipherSuite),
435 ServerSelectedDisallowedCipherSuite(Dtls12CipherSuite),
437 ServerSelectedDisallowedDtls13CipherSuite(Dtls13CipherSuite),
439 ExtendedMasterSecretNotNegotiated,
441 NoMutuallyAcceptableCipherSuite,
443 ClientHelloLegacyVersionNotDtls12,
445 ServerHelloLegacyVersionNotDtls12,
447 ClientHelloMissingDtls13SupportedVersions,
449 ClientHelloMustOfferNullCompression,
451 InvalidCookieInClientHello,
453 InvalidLegacyCookieInClientHello,
455 CannotSendSecondHelloRetryRequest,
457 UnexpectedSecondHelloRetryRequest,
459 NoCommonCipherSuite,
461 NoCommonKeyExchangeGroup,
463 HrrSelectedDisallowedCipherSuite,
465 HrrDidNotSelectDtls13,
467 ServerHelloCompressionMustBeNull,
469 ServerDidNotNegotiateDtls13,
471 ServerMissingKeyShare,
473 ServerKeyShareGroupMismatch {
475 expected: NamedGroup,
477 actual: NamedGroup,
479 },
480 SignatureTooLarge,
482 SignatureSchemeNotOffered(SignatureScheme),
484 SignatureAlgorithmMismatch {
486 expected: SignatureAlgorithm,
488 actual: SignatureAlgorithm,
490 },
491 UnsupportedSignatureScheme(SignatureScheme),
493 SignatureSchemeCertificateCurveMismatch {
495 scheme: SignatureScheme,
497 expected: NamedGroup,
499 actual: NamedGroup,
501 },
502 ServerFinishedVerificationFailed,
504 ClientFinishedVerificationFailed,
506 FatalAlert {
508 description: u8,
510 },
511}
512
513#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515#[non_exhaustive]
516pub enum PskError {
517 NoPskResolverConfigured,
519 NoPskIdentityConfigured,
521 ResolverReturnedNoKey,
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527#[non_exhaustive]
528pub enum TimeoutError {
529 HybridClientHello,
531 Connect,
533 Handshake,
535}
536
537#[derive(Debug, Clone, PartialEq, Eq)]
539#[non_exhaustive]
540pub enum ConfigError {
541 MtuTooSmall {
543 mtu: u16,
545 minimum: u16,
547 },
548 AeadEncryptionLimitTooSmall,
550 NoCipherSuitesAfterFiltering,
552 PskConfiguredWithoutPskCipherSuite,
554 NoDtls12KeyExchangeGroupsAfterFiltering,
556 NoDtls13KeyExchangeGroupsAfterFiltering,
558 CryptoProvider(CryptoProviderValidationError),
560}
561
562#[derive(Debug, Clone, PartialEq, Eq)]
564#[non_exhaustive]
565pub enum CryptoProviderValidationError {
566 NoCipherSuites,
568 EcdhCipherSuitesWithoutKeyExchangeGroups,
570 NoDtls13CipherSuites,
572 MissingHashTestVector(HashAlgorithm),
574 HashProviderIncorrect(HashAlgorithm),
576 PrfFailed {
578 hash: HashAlgorithm,
580 source: CryptoError,
582 },
583 MissingPrfTestVector(HashAlgorithm),
585 PrfIncorrect(HashAlgorithm),
587 NoSignatureValidationVector {
589 hash: HashAlgorithm,
591 signature: SignatureAlgorithm,
593 },
594 SignatureVerificationFailed {
596 hash: HashAlgorithm,
598 signature: SignatureAlgorithm,
600 source: CryptoError,
602 },
603 HkdfFailed {
605 suite: Dtls13CipherSuite,
607 source: CryptoError,
609 },
610 HkdfEmptyOutput(Dtls13CipherSuite),
612 NoAeadTestVector(Dtls13CipherSuite),
614 AeadCreateFailed {
616 suite: Dtls13CipherSuite,
618 source: CryptoError,
620 },
621 AeadEncryptFailed {
623 suite: Dtls13CipherSuite,
625 source: CryptoError,
627 },
628 AeadEncryptWrongOutput(Dtls13CipherSuite),
630 AeadDecryptFailed {
632 suite: Dtls13CipherSuite,
634 source: CryptoError,
636 },
637 AeadDecryptWrongOutput(Dtls13CipherSuite),
639 NoRecordNumberEncryptionTestVector(Dtls13CipherSuite),
641 RecordNumberEncryptionWrongMask(Dtls13CipherSuite),
643 KeyExchangeStartFailed {
645 group: NamedGroup,
647 source: CryptoError,
649 },
650 KeyExchangeCompleteFailed {
652 group: NamedGroup,
654 source: CryptoError,
656 },
657 KeyExchangeMismatchedSharedSecret(NamedGroup),
659 HmacFailed(CryptoError),
661 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}