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 KeyGeneration(Algorithm),
161 Verify,
163 Sign,
165 Csr(CsrError),
167 Tls(TlsError),
169 Random,
171 AeadKey,
173 AeadSeal,
175 AeadOpen,
177 SealPlaintext,
179 SealDomainEmpty,
182 SealBlob,
184 SealVersion,
186 SealEphemeralKey,
188 SealPublicKey,
190 SealPrivateKey,
192 SealOpen,
194 Primitive,
196 #[non_exhaustive]
198 EmptyProfile {
199 profile: Profile,
201 options: Options,
203 category: Family,
205 },
206 SignaturePrivateKey {
209 algorithm: SignatureAlgorithm,
211 },
212 SignaturePublicKey {
215 algorithm: SignatureAlgorithm,
217 },
218 KeyNotInProfile {
220 profile: Profile,
222 algorithm: SignatureAlgorithm,
224 },
225 NotApproved {
227 algorithm: Algorithm,
229 approval: Approval,
231 },
232 NotInProfile {
234 profile: Profile,
236 algorithm: Algorithm,
238 },
239 MacKeyLength {
241 profile: Profile,
243 bytes: usize,
245 min_bits: usize,
247 max_bits: usize,
249 },
250 MacVerify,
252 KdfOutputLength {
254 algorithm: KdfAlgorithm,
256 bytes: usize,
258 max_bytes: usize,
260 },
261 KdfSecretEmpty,
263 KdfInfoEmpty {
265 profile: Profile,
267 },
268 KdfInfoMayBeEmpty {
272 profile: Profile,
274 },
275 KdfSpecMismatch {
277 algorithm: KdfAlgorithm,
279 },
280 KeyAgreementPeerKey {
282 algorithm: KeyAgreementAlgorithm,
284 },
285 KeyAgreementPrivateKey {
287 algorithm: KeyAgreementAlgorithm,
289 },
290 AeadKeyLength {
292 algorithm: AeadAlgorithm,
294 bytes: usize,
296 },
297 AeadPlaintextLength {
299 algorithm: AeadAlgorithm,
301 bytes: usize,
303 },
304 AeadLimit {
306 algorithm: AeadAlgorithm,
308 },
309 FamilyNotAdmitted(Family),
312}
313
314impl fmt::Display for CryptoError {
315 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
316 match self {
317 CryptoError::Unavailable(a) => {
318 write!(f, "{a:?} is not available on this backend's module")
319 }
320 CryptoError::PolicyEmpty(fam) => write!(f, "the TLS policy names no {fam:?}"),
321 CryptoError::PolicyDuplicate(a) => write!(f, "the TLS policy names {a:?} twice"),
322 CryptoError::PolicyVersionUnusable { version, family } => write!(
323 f,
324 "the TLS policy lists {version:?} but names no {family:?} usable with it"
325 ),
326 CryptoError::PolicyDrift => {
327 f.write_str("the provider does not carry exactly the policy's algorithms")
328 }
329 CryptoError::NotFips => {
330 f.write_str("the AWS-LC FIPS module is not active, or the provider is not FIPS")
331 }
332 CryptoError::KeyGeneration(a) => write!(f, "key generation for {a:?} failed"),
333 CryptoError::Verify => f.write_str("the signature does not verify"),
334 CryptoError::Sign => f.write_str("signing failed"),
335 CryptoError::Csr(e) => write!(f, "the certificate signing request failed: {e:?}"),
336 CryptoError::Tls(e) => write!(f, "the TLS configuration was refused: {e:?}"),
337 CryptoError::Random => f.write_str("the random generator failed"),
338 CryptoError::AeadKey => f.write_str("the AEAD key was refused"),
339 CryptoError::AeadSeal => f.write_str("AEAD sealing failed"),
340 CryptoError::AeadOpen => f.write_str("the AEAD ciphertext does not authenticate"),
341 CryptoError::SealPlaintext => f.write_str("the sealed plaintext is empty"),
342 CryptoError::SealDomainEmpty => f.write_str("the sealed-box domain is empty"),
343 CryptoError::SealBlob => f.write_str("the sealed blob is too short"),
344 CryptoError::SealVersion => f.write_str("the sealed blob has an unknown version"),
345 CryptoError::SealEphemeralKey => {
346 f.write_str("the sealed blob's ephemeral key is not an uncompressed P-384 point")
347 }
348 CryptoError::SealPublicKey => {
349 f.write_str("the sealing public key is not a canonical P-384 SubjectPublicKeyInfo")
350 }
351 CryptoError::SealPrivateKey => {
352 f.write_str("the sealing private key is not a P-384 PKCS#8 key")
353 }
354 CryptoError::SealOpen => {
355 f.write_str("the sealed blob does not open under this key, domain and AAD")
356 }
357 CryptoError::Primitive => f.write_str("a cryptographic primitive failed"),
358 CryptoError::EmptyProfile {
359 profile,
360 options,
361 category,
362 } => {
363 write!(
364 f,
365 "the {profile} profile, with {options}, names no {category:?}"
366 )
367 }
368 CryptoError::SignaturePrivateKey { algorithm } => {
369 write!(f, "the {algorithm} private key was refused")
370 }
371 CryptoError::SignaturePublicKey { algorithm } => {
372 write!(f, "the public key is not a raw {algorithm} public key")
373 }
374 CryptoError::KeyNotInProfile { profile, algorithm } => {
375 write!(f, "the {profile} profile does not admit {algorithm} keys")
376 }
377 CryptoError::NotApproved {
378 algorithm,
379 approval,
380 } => {
381 write!(
382 f,
383 "{algorithm:?} is not approved by the running module: {approval:?}"
384 )
385 }
386 CryptoError::NotInProfile { profile, algorithm } => {
387 write!(f, "the {profile} profile does not admit {algorithm:?}")
388 }
389 CryptoError::MacKeyLength {
390 profile,
391 bytes,
392 min_bits,
393 max_bits,
394 } => write!(
395 f,
396 "an HMAC key of {bytes} bytes is outside the {profile} profile's {min_bits}-{max_bits} bit range"
397 ),
398 CryptoError::MacVerify => f.write_str("the MAC did not verify"),
399 CryptoError::KdfOutputLength {
400 algorithm,
401 bytes,
402 max_bytes,
403 } => write!(
404 f,
405 "a KDF output of {bytes} bytes ({algorithm:?}) is outside 1-{max_bytes} bytes"
406 ),
407 CryptoError::KdfSecretEmpty => f.write_str("the KDF secret is empty"),
408 CryptoError::KdfInfoEmpty { profile } => {
409 write!(f, "the {profile} profile refuses an empty KDF info")
410 }
411 CryptoError::KdfInfoMayBeEmpty { profile } => write!(
412 f,
413 "the {profile} profile admits an empty KDF info, which the module does not approve"
414 ),
415 CryptoError::KdfSpecMismatch { algorithm } => {
416 write!(f, "{algorithm:?} does not match its KDF specification")
417 }
418 CryptoError::KeyAgreementPeerKey { algorithm } => {
419 write!(f, "the peer public key is not a valid {algorithm} key")
420 }
421 CryptoError::KeyAgreementPrivateKey { algorithm } => {
422 write!(f, "the {algorithm} private key was refused")
423 }
424 CryptoError::AeadKeyLength { algorithm, bytes } => write!(
425 f,
426 "the {algorithm} key must be {} bytes, not {bytes}",
427 algorithm.key_len()
428 ),
429 CryptoError::AeadPlaintextLength { algorithm, bytes } => write!(
430 f,
431 "a plaintext of {bytes} bytes exceeds {algorithm}'s maximum of {} bytes",
432 algorithm.max_plaintext_len()
433 ),
434 CryptoError::AeadLimit { algorithm } => {
435 write!(
436 f,
437 "the {algorithm} key has sealed 2^32 times; use a new key"
438 )
439 }
440 CryptoError::FamilyNotAdmitted(family) => write!(
441 f,
442 "assert_admitted_approved does not check the {family:?} family; assert_module_approves checks the TLS families"
443 ),
444 }
445 }
446}
447
448impl std::error::Error for CryptoError {}
449
450#[cfg(test)]
451mod tests {
452 use super::*;
453 use crate::algorithm::{
454 AeadAlgorithm, Algorithm, KdfAlgorithm, KeyAgreementAlgorithm, KxGroup, MacAlgorithm,
455 SignatureAlgorithm, TlsSignatureScheme,
456 };
457 use crate::capability::Approval;
458 use crate::profile::{Options, Profile};
459
460 #[test]
461 fn display_texts_are_pinned() {
462 assert_eq!(
463 CryptoError::Random.to_string(),
464 "the random generator failed"
465 );
466 assert_eq!(
467 CryptoError::NotFips.to_string(),
468 "the AWS-LC FIPS module is not active, or the provider is not FIPS"
469 );
470 assert_eq!(
471 CryptoError::Unavailable(Algorithm::Signature(SignatureAlgorithm::MlDsa87)).to_string(),
472 "Signature(MlDsa87) is not available on this backend's module"
473 );
474 assert_eq!(
475 CryptoError::PolicyEmpty(Family::KxGroup).to_string(),
476 "the TLS policy names no KxGroup"
477 );
478 assert_eq!(
479 [
480 Family::Mac,
481 Family::Kdf,
482 Family::KeyAgreement,
483 Family::Aead,
484 Family::Hash,
485 Family::Signature
486 ]
487 .map(|f| format!("{f:?}")),
488 ["Mac", "Kdf", "KeyAgreement", "Aead", "Hash", "Signature"]
489 );
490 assert_eq!(
491 CryptoError::PolicyVersionUnusable {
492 version: TlsVersion::Tls12,
493 family: Family::KxGroup
494 }
495 .to_string(),
496 "the TLS policy lists Tls12 but names no KxGroup usable with it"
497 );
498 assert_eq!(
499 CryptoError::PolicyDuplicate(Algorithm::Scheme(TlsSignatureScheme::Ed25519))
500 .to_string(),
501 "the TLS policy names Scheme(Ed25519) twice"
502 );
503 assert_eq!(
504 CryptoError::Csr(CsrError::InvalidName).to_string(),
505 "the certificate signing request failed: InvalidName"
506 );
507 assert_eq!(
508 CryptoError::Tls(TlsError::PrivateKey).to_string(),
509 "the TLS configuration was refused: PrivateKey"
510 );
511 }
512
513 #[test]
514 fn profile_display_texts_are_pinned() {
515 let pq = Options {
516 pq_key_exchange_required: true,
517 peer_certificates_match_profile: false,
518 cnsa1_unclassified_nss: false,
519 };
520 let table: [(CryptoError, &str); 20] = [
521 (
522 CryptoError::EmptyProfile {
523 profile: Profile::Cnsa1,
524 options: pq,
525 category: Family::KxGroup,
526 },
527 "the cnsa1 profile, with post-quantum key exchange required, names no KxGroup",
528 ),
529 (
530 CryptoError::EmptyProfile {
531 profile: Profile::Cnsa2,
532 options: Options::default(),
533 category: Family::KeyAlgorithm,
534 },
535 "the cnsa2 profile, with no options, names no KeyAlgorithm",
536 ),
537 (
538 CryptoError::KeyNotInProfile {
539 profile: Profile::Bsi,
540 algorithm: SignatureAlgorithm::Rsa3072Sha384,
541 },
542 "the bsi profile does not admit rsa3072-sha384 keys",
543 ),
544 (
545 CryptoError::SignaturePrivateKey {
546 algorithm: SignatureAlgorithm::Ed25519,
547 },
548 "the ed25519 private key was refused",
549 ),
550 (
551 CryptoError::SignaturePublicKey {
552 algorithm: SignatureAlgorithm::MlDsa87,
553 },
554 "the public key is not a raw ml-dsa-87 public key",
555 ),
556 (
557 CryptoError::NotApproved {
558 algorithm: Algorithm::Kx(KxGroup::X25519),
559 approval: Approval::Unverified,
560 },
561 "Kx(X25519) is not approved by the running module: Unverified",
562 ),
563 (
564 CryptoError::NotApproved {
565 algorithm: Algorithm::Signature(SignatureAlgorithm::MlDsa87),
566 approval: Approval::AlgorithmTested { cavp: "A7855 (x)" },
567 },
568 "Signature(MlDsa87) is not approved by the running module: AlgorithmTested { cavp: \"A7855 (x)\" }",
569 ),
570 (
571 CryptoError::NotInProfile {
572 profile: Profile::Cnsa2,
573 algorithm: Algorithm::Mac(MacAlgorithm::HmacSha256),
574 },
575 "the cnsa2 profile does not admit Mac(HmacSha256)",
576 ),
577 (
578 CryptoError::MacKeyLength {
579 profile: Profile::Bsi,
580 bytes: 15,
581 min_bits: 128,
582 max_bits: 524_288,
583 },
584 "an HMAC key of 15 bytes is outside the bsi profile's 128-524288 bit range",
585 ),
586 (CryptoError::MacVerify, "the MAC did not verify"),
587 (
588 CryptoError::KdfOutputLength {
589 algorithm: KdfAlgorithm::HkdfSha256,
590 bytes: 8161,
591 max_bytes: 8160,
592 },
593 "a KDF output of 8161 bytes (HkdfSha256) is outside 1-8160 bytes",
594 ),
595 (CryptoError::KdfSecretEmpty, "the KDF secret is empty"),
596 (
597 CryptoError::KdfInfoEmpty {
598 profile: Profile::Fips1403,
599 },
600 "the fips1403 profile refuses an empty KDF info",
601 ),
602 (
603 CryptoError::KdfInfoMayBeEmpty {
604 profile: Profile::Unrestricted,
605 },
606 "the unrestricted profile admits an empty KDF info, which the module does not approve",
607 ),
608 (
609 CryptoError::KdfSpecMismatch {
610 algorithm: KdfAlgorithm::OneStepSha256,
611 },
612 "OneStepSha256 does not match its KDF specification",
613 ),
614 (
615 CryptoError::KeyAgreementPeerKey {
616 algorithm: KeyAgreementAlgorithm::EcdhP384,
617 },
618 "the peer public key is not a valid ecdh-p384 key",
619 ),
620 (
621 CryptoError::KeyAgreementPrivateKey {
622 algorithm: KeyAgreementAlgorithm::X25519,
623 },
624 "the x25519 private key was refused",
625 ),
626 (
627 CryptoError::AeadKeyLength {
628 algorithm: AeadAlgorithm::Aes128Gcm,
629 bytes: 32,
630 },
631 "the aes-128-gcm key must be 16 bytes, not 32",
632 ),
633 (
634 CryptoError::AeadLimit {
635 algorithm: AeadAlgorithm::Aes256Gcm,
636 },
637 "the aes-256-gcm key has sealed 2^32 times; use a new key",
638 ),
639 (
640 CryptoError::FamilyNotAdmitted(Family::CipherSuite),
641 "assert_admitted_approved does not check the CipherSuite family; assert_module_approves checks the TLS families",
642 ),
643 ];
644 for (e, text) in table {
645 assert_eq!(e.to_string(), text);
646 }
647 }
648
649 #[test]
650 #[cfg(target_pointer_width = "64")]
651 fn the_aead_plaintext_length_text_is_pinned() {
652 assert_eq!(
653 CryptoError::AeadPlaintextLength {
654 algorithm: AeadAlgorithm::Chacha20Poly1305,
655 bytes: 274_877_906_880,
656 }
657 .to_string(),
658 "a plaintext of 274877906880 bytes exceeds chacha20-poly1305's maximum of 274877906879 bytes"
659 );
660 }
661
662 #[test]
663 fn every_other_display_text_is_pinned() {
664 let table: [(CryptoError, &str); 16] = [
665 (
666 CryptoError::PolicyDrift,
667 "the provider does not carry exactly the policy's algorithms",
668 ),
669 (
670 CryptoError::KeyGeneration(Algorithm::Signature(SignatureAlgorithm::Ed25519)),
671 "key generation for Signature(Ed25519) failed",
672 ),
673 (CryptoError::Verify, "the signature does not verify"),
674 (CryptoError::Sign, "signing failed"),
675 (CryptoError::AeadKey, "the AEAD key was refused"),
676 (CryptoError::AeadSeal, "AEAD sealing failed"),
677 (
678 CryptoError::AeadOpen,
679 "the AEAD ciphertext does not authenticate",
680 ),
681 (CryptoError::SealPlaintext, "the sealed plaintext is empty"),
682 (
683 CryptoError::SealDomainEmpty,
684 "the sealed-box domain is empty",
685 ),
686 (CryptoError::SealBlob, "the sealed blob is too short"),
687 (
688 CryptoError::SealVersion,
689 "the sealed blob has an unknown version",
690 ),
691 (
692 CryptoError::SealEphemeralKey,
693 "the sealed blob's ephemeral key is not an uncompressed P-384 point",
694 ),
695 (
696 CryptoError::SealPublicKey,
697 "the sealing public key is not a canonical P-384 SubjectPublicKeyInfo",
698 ),
699 (
700 CryptoError::SealPrivateKey,
701 "the sealing private key is not a P-384 PKCS#8 key",
702 ),
703 (
704 CryptoError::SealOpen,
705 "the sealed blob does not open under this key, domain and AAD",
706 ),
707 (CryptoError::Primitive, "a cryptographic primitive failed"),
708 ];
709 for (e, text) in table {
710 assert_eq!(e.to_string(), text);
711 }
712 }
713}