1use crate::algorithm::{
3 AeadAlgorithm, Algorithm, KdfAlgorithm, KeyAgreementAlgorithm, SignatureAlgorithm, TlsVersion,
4};
5use crate::capability::Approval;
6use crate::peer_certificate::PeerCertificateViolation;
7use crate::profile::{Options, Profile};
8use std::fmt;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum Family {
14 Version,
16 CipherSuite,
18 KxGroup,
20 SignatureScheme,
22 KeyAlgorithm,
24 Mac,
26 Kdf,
28 KeyAgreement,
30 Aead,
32 Hash,
34 Signature,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum CsrError {
42 InvalidName,
44 InvalidParams,
46 Signing,
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum PeerVerifierIdentity {
53 Owned {
55 rule: Option<crate::PeerCertificateRuleId>,
57 handshake_schemes: u64,
59 },
60 Opaque,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66#[non_exhaustive]
67pub enum TlsError {
68 ProtocolVersions,
70 PrivateKey,
72 DefaultProviderInstalled,
74 KeyMismatch,
76 StrictBuilderRequired {
78 entry_point: &'static str,
80 },
81 IncompatiblePeerVerifier {
83 expected: PeerVerifierIdentity,
85 actual: PeerVerifierIdentity,
87 },
88 PeerCertificate {
90 profile: Profile,
92 violation: PeerCertificateViolation,
94 },
95}
96
97impl fmt::Display for TlsError {
98 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99 match self {
100 Self::ProtocolVersions => f.write_str("the provider refused the protocol versions"),
101 Self::PrivateKey => f.write_str("the private key was refused"),
102 Self::DefaultProviderInstalled => {
103 f.write_str("a process-default provider is already installed")
104 }
105 Self::KeyMismatch => {
106 f.write_str("the certificate chain is empty or does not carry the key")
107 }
108 Self::IncompatiblePeerVerifier { expected, actual } => {
109 write!(
110 f,
111 "the peer verifier {actual:?} is incompatible with {expected:?}"
112 )
113 }
114 Self::StrictBuilderRequired { entry_point } => {
115 write!(f, "the peer certificate rule requires tls::{entry_point}")
116 }
117 Self::PeerCertificate { profile, violation } => {
118 write!(f, "the {profile} peer certificate was refused: {violation}")
119 }
120 }
121 }
122}
123
124impl std::error::Error for TlsError {
125 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
126 match self {
127 Self::PeerCertificate { violation, .. } => Some(violation),
128 Self::IncompatiblePeerVerifier { .. }
129 | Self::StrictBuilderRequired { .. }
130 | Self::ProtocolVersions
131 | Self::PrivateKey
132 | Self::DefaultProviderInstalled
133 | Self::KeyMismatch => None,
134 }
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140#[non_exhaustive]
141pub enum CryptoError {
142 Unavailable(Algorithm),
144 PolicyEmpty(Family),
146 PolicyDuplicate(Algorithm),
148 PolicyDrift,
150 PolicyVersionUnusable {
152 version: TlsVersion,
154 family: Family,
156 },
157 NotFips,
159 SelfTest,
161 SelfTestUnavailable,
163 KeyGeneration(Algorithm),
165 Verify,
167 Sign,
169 Csr(CsrError),
171 Tls(TlsError),
173 Random,
175 AeadKey,
177 AeadSeal,
179 AeadOpen,
181 SealPlaintext,
183 SealDomainEmpty,
186 SealBlob,
188 SealVersion,
190 SealEphemeralKey,
192 SealPublicKey,
194 SealPrivateKey,
196 SealOpen,
198 Primitive,
200 #[non_exhaustive]
202 EmptyProfile {
203 profile: Profile,
205 options: Options,
207 category: Family,
209 },
210 SignaturePrivateKey {
213 algorithm: SignatureAlgorithm,
215 },
216 SignaturePublicKey {
219 algorithm: SignatureAlgorithm,
221 },
222 KeyNotInProfile {
224 profile: Profile,
226 algorithm: SignatureAlgorithm,
228 },
229 NotApproved {
231 algorithm: Algorithm,
233 approval: Approval,
235 },
236 NotInProfile {
238 profile: Profile,
240 algorithm: Algorithm,
242 },
243 MacKeyLength {
245 profile: Profile,
247 bytes: usize,
249 min_bits: usize,
251 max_bits: usize,
253 },
254 MacVerify,
256 KdfOutputLength {
258 algorithm: KdfAlgorithm,
260 bytes: usize,
262 max_bytes: usize,
264 },
265 KdfSecretEmpty,
267 KdfInfoEmpty {
269 profile: Profile,
271 },
272 KdfInfoMayBeEmpty {
276 profile: Profile,
278 },
279 KdfSpecMismatch {
281 algorithm: KdfAlgorithm,
283 },
284 KeyAgreementPeerKey {
286 algorithm: KeyAgreementAlgorithm,
288 },
289 KeyAgreementPrivateKey {
291 algorithm: KeyAgreementAlgorithm,
293 },
294 AeadKeyLength {
296 algorithm: AeadAlgorithm,
298 bytes: usize,
300 },
301 AeadPlaintextLength {
303 algorithm: AeadAlgorithm,
305 bytes: usize,
307 },
308 AeadLimit {
310 algorithm: AeadAlgorithm,
312 },
313 FamilyNotAdmitted(Family),
316}
317
318impl fmt::Display for CryptoError {
319 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 match self {
321 CryptoError::Unavailable(a) => {
322 write!(f, "{a:?} is not available on this backend's module")
323 }
324 CryptoError::PolicyEmpty(fam) => write!(f, "the TLS policy names no {fam:?}"),
325 CryptoError::PolicyDuplicate(a) => write!(f, "the TLS policy names {a:?} twice"),
326 CryptoError::PolicyVersionUnusable { version, family } => write!(
327 f,
328 "the TLS policy lists {version:?} but names no {family:?} usable with it"
329 ),
330 CryptoError::PolicyDrift => {
331 f.write_str("the provider does not carry exactly the policy's algorithms")
332 }
333 CryptoError::NotFips => {
334 f.write_str("the AWS-LC FIPS module is not active, or the provider is not FIPS")
335 }
336 CryptoError::SelfTest => f.write_str("the module's on-demand self-test failed"),
337 CryptoError::SelfTestUnavailable => {
338 f.write_str("this backend does not expose the module's on-demand self-test")
339 }
340 CryptoError::KeyGeneration(a) => write!(f, "key generation for {a:?} failed"),
341 CryptoError::Verify => f.write_str("the signature does not verify"),
342 CryptoError::Sign => f.write_str("signing failed"),
343 CryptoError::Csr(e) => write!(f, "the certificate signing request failed: {e:?}"),
344 CryptoError::Tls(e) => write!(f, "the TLS configuration was refused: {e:?}"),
345 CryptoError::Random => f.write_str("the random generator failed"),
346 CryptoError::AeadKey => f.write_str("the AEAD key was refused"),
347 CryptoError::AeadSeal => f.write_str("AEAD sealing failed"),
348 CryptoError::AeadOpen => f.write_str("the AEAD ciphertext does not authenticate"),
349 CryptoError::SealPlaintext => f.write_str("the sealed plaintext is empty"),
350 CryptoError::SealDomainEmpty => f.write_str("the sealed-box domain is empty"),
351 CryptoError::SealBlob => f.write_str("the sealed blob is too short"),
352 CryptoError::SealVersion => f.write_str("the sealed blob has an unknown version"),
353 CryptoError::SealEphemeralKey => {
354 f.write_str("the sealed blob's ephemeral key is not an uncompressed P-384 point")
355 }
356 CryptoError::SealPublicKey => {
357 f.write_str("the sealing public key is not a canonical P-384 SubjectPublicKeyInfo")
358 }
359 CryptoError::SealPrivateKey => {
360 f.write_str("the sealing private key is not a P-384 PKCS#8 key")
361 }
362 CryptoError::SealOpen => {
363 f.write_str("the sealed blob does not open under this key, domain and AAD")
364 }
365 CryptoError::Primitive => f.write_str("a cryptographic primitive failed"),
366 CryptoError::EmptyProfile {
367 profile,
368 options,
369 category,
370 } => {
371 write!(
372 f,
373 "the {profile} profile, with {options}, names no {category:?}"
374 )
375 }
376 CryptoError::SignaturePrivateKey { algorithm } => {
377 write!(f, "the {algorithm} private key was refused")
378 }
379 CryptoError::SignaturePublicKey { algorithm } => {
380 write!(f, "the public key is not a raw {algorithm} public key")
381 }
382 CryptoError::KeyNotInProfile { profile, algorithm } => {
383 write!(f, "the {profile} profile does not admit {algorithm} keys")
384 }
385 CryptoError::NotApproved {
386 algorithm,
387 approval,
388 } => {
389 write!(
390 f,
391 "{algorithm:?} is not approved by the running module: {approval:?}"
392 )
393 }
394 CryptoError::NotInProfile { profile, algorithm } => {
395 write!(f, "the {profile} profile does not admit {algorithm:?}")
396 }
397 CryptoError::MacKeyLength {
398 profile,
399 bytes,
400 min_bits,
401 max_bits,
402 } => write!(
403 f,
404 "an HMAC key of {bytes} bytes is outside the {profile} profile's {min_bits}-{max_bits} bit range"
405 ),
406 CryptoError::MacVerify => f.write_str("the MAC did not verify"),
407 CryptoError::KdfOutputLength {
408 algorithm,
409 bytes,
410 max_bytes,
411 } => write!(
412 f,
413 "a KDF output of {bytes} bytes ({algorithm:?}) is outside 1-{max_bytes} bytes"
414 ),
415 CryptoError::KdfSecretEmpty => f.write_str("the KDF secret is empty"),
416 CryptoError::KdfInfoEmpty { profile } => {
417 write!(f, "the {profile} profile refuses an empty KDF info")
418 }
419 CryptoError::KdfInfoMayBeEmpty { profile } => write!(
420 f,
421 "the {profile} profile admits an empty KDF info, which the module does not approve"
422 ),
423 CryptoError::KdfSpecMismatch { algorithm } => {
424 write!(f, "{algorithm:?} does not match its KDF specification")
425 }
426 CryptoError::KeyAgreementPeerKey { algorithm } => {
427 write!(f, "the peer public key is not a valid {algorithm} key")
428 }
429 CryptoError::KeyAgreementPrivateKey { algorithm } => {
430 write!(f, "the {algorithm} private key was refused")
431 }
432 CryptoError::AeadKeyLength { algorithm, bytes } => write!(
433 f,
434 "the {algorithm} key must be {} bytes, not {bytes}",
435 algorithm.key_len()
436 ),
437 CryptoError::AeadPlaintextLength { algorithm, bytes } => write!(
438 f,
439 "a plaintext of {bytes} bytes exceeds {algorithm}'s maximum of {} bytes",
440 algorithm.max_plaintext_len()
441 ),
442 CryptoError::AeadLimit { algorithm } => {
443 write!(
444 f,
445 "the {algorithm} key has sealed 2^32 times; use a new key"
446 )
447 }
448 CryptoError::FamilyNotAdmitted(family) => write!(
449 f,
450 "assert_admitted_approved does not check the {family:?} family; assert_module_approves checks the TLS families"
451 ),
452 }
453 }
454}
455
456impl std::error::Error for CryptoError {}
457
458#[cfg(test)]
459mod tests {
460 use super::*;
461 use crate::algorithm::{
462 AeadAlgorithm, Algorithm, KdfAlgorithm, KeyAgreementAlgorithm, KxGroup, MacAlgorithm,
463 SignatureAlgorithm, TlsSignatureScheme,
464 };
465 use crate::capability::Approval;
466 use crate::profile::{Options, Profile};
467
468 #[test]
469 fn display_texts_are_pinned() {
470 assert_eq!(
471 CryptoError::Random.to_string(),
472 "the random generator failed"
473 );
474 assert_eq!(
475 CryptoError::NotFips.to_string(),
476 "the AWS-LC FIPS module is not active, or the provider is not FIPS"
477 );
478 assert_eq!(
479 CryptoError::SelfTest.to_string(),
480 "the module's on-demand self-test failed"
481 );
482 assert_eq!(
483 CryptoError::SelfTestUnavailable.to_string(),
484 "this backend does not expose the module's on-demand self-test"
485 );
486 assert_eq!(
487 CryptoError::Unavailable(Algorithm::Signature(SignatureAlgorithm::MlDsa87)).to_string(),
488 "Signature(MlDsa87) is not available on this backend's module"
489 );
490 assert_eq!(
491 CryptoError::PolicyEmpty(Family::KxGroup).to_string(),
492 "the TLS policy names no KxGroup"
493 );
494 assert_eq!(
495 [
496 Family::Mac,
497 Family::Kdf,
498 Family::KeyAgreement,
499 Family::Aead,
500 Family::Hash,
501 Family::Signature
502 ]
503 .map(|f| format!("{f:?}")),
504 ["Mac", "Kdf", "KeyAgreement", "Aead", "Hash", "Signature"]
505 );
506 assert_eq!(
507 CryptoError::PolicyVersionUnusable {
508 version: TlsVersion::Tls12,
509 family: Family::KxGroup
510 }
511 .to_string(),
512 "the TLS policy lists Tls12 but names no KxGroup usable with it"
513 );
514 assert_eq!(
515 CryptoError::PolicyDuplicate(Algorithm::Scheme(TlsSignatureScheme::Ed25519))
516 .to_string(),
517 "the TLS policy names Scheme(Ed25519) twice"
518 );
519 assert_eq!(
520 CryptoError::Csr(CsrError::InvalidName).to_string(),
521 "the certificate signing request failed: InvalidName"
522 );
523 assert_eq!(
524 CryptoError::Tls(TlsError::PrivateKey).to_string(),
525 "the TLS configuration was refused: PrivateKey"
526 );
527 }
528
529 #[test]
530 fn profile_display_texts_are_pinned() {
531 let pq = Options {
532 pq_key_exchange_required: true,
533 peer_certificates_match_profile: false,
534 cnsa1_unclassified_nss: false,
535 };
536 let table: [(CryptoError, &str); 20] = [
537 (
538 CryptoError::EmptyProfile {
539 profile: Profile::Cnsa1,
540 options: pq,
541 category: Family::KxGroup,
542 },
543 "the cnsa1 profile, with post-quantum key exchange required, names no KxGroup",
544 ),
545 (
546 CryptoError::EmptyProfile {
547 profile: Profile::Cnsa2,
548 options: Options::default(),
549 category: Family::KeyAlgorithm,
550 },
551 "the cnsa2 profile, with no options, names no KeyAlgorithm",
552 ),
553 (
554 CryptoError::KeyNotInProfile {
555 profile: Profile::Bsi,
556 algorithm: SignatureAlgorithm::Rsa3072Sha384,
557 },
558 "the bsi profile does not admit rsa3072-sha384 keys",
559 ),
560 (
561 CryptoError::SignaturePrivateKey {
562 algorithm: SignatureAlgorithm::Ed25519,
563 },
564 "the ed25519 private key was refused",
565 ),
566 (
567 CryptoError::SignaturePublicKey {
568 algorithm: SignatureAlgorithm::MlDsa87,
569 },
570 "the public key is not a raw ml-dsa-87 public key",
571 ),
572 (
573 CryptoError::NotApproved {
574 algorithm: Algorithm::Kx(KxGroup::X25519),
575 approval: Approval::Unverified,
576 },
577 "Kx(X25519) is not approved by the running module: Unverified",
578 ),
579 (
580 CryptoError::NotApproved {
581 algorithm: Algorithm::Signature(SignatureAlgorithm::MlDsa87),
582 approval: Approval::AlgorithmTested { cavp: "A7855 (x)" },
583 },
584 "Signature(MlDsa87) is not approved by the running module: AlgorithmTested { cavp: \"A7855 (x)\" }",
585 ),
586 (
587 CryptoError::NotInProfile {
588 profile: Profile::Cnsa2,
589 algorithm: Algorithm::Mac(MacAlgorithm::HmacSha256),
590 },
591 "the cnsa2 profile does not admit Mac(HmacSha256)",
592 ),
593 (
594 CryptoError::MacKeyLength {
595 profile: Profile::Bsi,
596 bytes: 15,
597 min_bits: 128,
598 max_bits: 524_288,
599 },
600 "an HMAC key of 15 bytes is outside the bsi profile's 128-524288 bit range",
601 ),
602 (CryptoError::MacVerify, "the MAC did not verify"),
603 (
604 CryptoError::KdfOutputLength {
605 algorithm: KdfAlgorithm::HkdfSha256,
606 bytes: 8161,
607 max_bytes: 8160,
608 },
609 "a KDF output of 8161 bytes (HkdfSha256) is outside 1-8160 bytes",
610 ),
611 (CryptoError::KdfSecretEmpty, "the KDF secret is empty"),
612 (
613 CryptoError::KdfInfoEmpty {
614 profile: Profile::Fips1403,
615 },
616 "the fips1403 profile refuses an empty KDF info",
617 ),
618 (
619 CryptoError::KdfInfoMayBeEmpty {
620 profile: Profile::Unrestricted,
621 },
622 "the unrestricted profile admits an empty KDF info, which the module does not approve",
623 ),
624 (
625 CryptoError::KdfSpecMismatch {
626 algorithm: KdfAlgorithm::OneStepSha256,
627 },
628 "OneStepSha256 does not match its KDF specification",
629 ),
630 (
631 CryptoError::KeyAgreementPeerKey {
632 algorithm: KeyAgreementAlgorithm::EcdhP384,
633 },
634 "the peer public key is not a valid ecdh-p384 key",
635 ),
636 (
637 CryptoError::KeyAgreementPrivateKey {
638 algorithm: KeyAgreementAlgorithm::X25519,
639 },
640 "the x25519 private key was refused",
641 ),
642 (
643 CryptoError::AeadKeyLength {
644 algorithm: AeadAlgorithm::Aes128Gcm,
645 bytes: 32,
646 },
647 "the aes-128-gcm key must be 16 bytes, not 32",
648 ),
649 (
650 CryptoError::AeadLimit {
651 algorithm: AeadAlgorithm::Aes256Gcm,
652 },
653 "the aes-256-gcm key has sealed 2^32 times; use a new key",
654 ),
655 (
656 CryptoError::FamilyNotAdmitted(Family::CipherSuite),
657 "assert_admitted_approved does not check the CipherSuite family; assert_module_approves checks the TLS families",
658 ),
659 ];
660 for (e, text) in table {
661 assert_eq!(e.to_string(), text);
662 }
663 }
664
665 #[test]
666 #[cfg(target_pointer_width = "64")]
667 fn the_aead_plaintext_length_text_is_pinned() {
668 assert_eq!(
669 CryptoError::AeadPlaintextLength {
670 algorithm: AeadAlgorithm::Chacha20Poly1305,
671 bytes: 274_877_906_880,
672 }
673 .to_string(),
674 "a plaintext of 274877906880 bytes exceeds chacha20-poly1305's maximum of 274877906879 bytes"
675 );
676 }
677
678 #[test]
679 fn every_other_display_text_is_pinned() {
680 let table: [(CryptoError, &str); 16] = [
681 (
682 CryptoError::PolicyDrift,
683 "the provider does not carry exactly the policy's algorithms",
684 ),
685 (
686 CryptoError::KeyGeneration(Algorithm::Signature(SignatureAlgorithm::Ed25519)),
687 "key generation for Signature(Ed25519) failed",
688 ),
689 (CryptoError::Verify, "the signature does not verify"),
690 (CryptoError::Sign, "signing failed"),
691 (CryptoError::AeadKey, "the AEAD key was refused"),
692 (CryptoError::AeadSeal, "AEAD sealing failed"),
693 (
694 CryptoError::AeadOpen,
695 "the AEAD ciphertext does not authenticate",
696 ),
697 (CryptoError::SealPlaintext, "the sealed plaintext is empty"),
698 (
699 CryptoError::SealDomainEmpty,
700 "the sealed-box domain is empty",
701 ),
702 (CryptoError::SealBlob, "the sealed blob is too short"),
703 (
704 CryptoError::SealVersion,
705 "the sealed blob has an unknown version",
706 ),
707 (
708 CryptoError::SealEphemeralKey,
709 "the sealed blob's ephemeral key is not an uncompressed P-384 point",
710 ),
711 (
712 CryptoError::SealPublicKey,
713 "the sealing public key is not a canonical P-384 SubjectPublicKeyInfo",
714 ),
715 (
716 CryptoError::SealPrivateKey,
717 "the sealing private key is not a P-384 PKCS#8 key",
718 ),
719 (
720 CryptoError::SealOpen,
721 "the sealed blob does not open under this key, domain and AAD",
722 ),
723 (CryptoError::Primitive, "a cryptographic primitive failed"),
724 ];
725 for (e, text) in table {
726 assert_eq!(e.to_string(), text);
727 }
728 }
729}