Skip to main content

rtci_crypto/providers/
aws_lc_rs.rs

1use std::sync::Arc;
2
3use aws_lc_rs::rand::SystemRandom;
4use aws_lc_rs::signature::{self, KeyPair};
5use aws_lc_rs::{aead, agreement, digest, hmac};
6
7use crate::common;
8use crate::{
9    ActiveKeyExchange, AeadAlgorithm, AeadCipher, BlockCipherAlgorithm, CbcAlgorithm, CbcCipher,
10    CryptoAlgorithm, CryptoError, HEADER_MASK_LEN, HEADER_MASK_SAMPLE_LEN, HashAlgorithm,
11    HeaderMask, HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, Mac, PublicKey,
12    PublicKeyEncoding, RTCCrypto, RTCCryptoProvider, RTCRandom, SecretVec, SignatureScheme,
13    SigningKey, StreamCipher, StreamCipherAlgorithm, constant_time_eq,
14};
15
16/// The built-in AWS-LC-RS provider bundle.
17#[derive(Default)]
18pub struct AwsLcRsProvider {
19    crypto: AwsLcRsCrypto,
20    random: AwsLcRsRandom,
21}
22
23impl AwsLcRsProvider {
24    /// Creates an AWS-LC-RS provider.
25    #[must_use]
26    pub const fn new() -> Self {
27        Self {
28            crypto: AwsLcRsCrypto,
29            random: AwsLcRsRandom,
30        }
31    }
32}
33
34impl RTCCryptoProvider for AwsLcRsProvider {
35    fn name(&self) -> &'static str {
36        "aws-lc-rs"
37    }
38
39    fn crypto(&self) -> &dyn RTCCrypto {
40        &self.crypto
41    }
42
43    fn random(&self) -> &dyn RTCRandom {
44        &self.random
45    }
46}
47
48/// AWS-LC-RS-backed operations, with RustCrypto fallbacks for primitives that are not exposed by
49/// its stable high-level API: MD5, AES block/CTR/CBC, and AES-CCM.
50#[derive(Default)]
51pub struct AwsLcRsCrypto;
52
53/// AWS-LC-RS's operating-system-backed secure random source.
54#[derive(Default)]
55pub struct AwsLcRsRandom;
56
57impl RTCRandom for AwsLcRsRandom {
58    fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError> {
59        common::fill_random(output)
60    }
61
62    fn fill_secret(&self, output: &mut [u8]) -> Result<(), CryptoError> {
63        use aws_lc_rs::rand::SecureRandom;
64        SystemRandom::new()
65            .fill(output)
66            .map_err(|_| CryptoError::RandomnessFailed)
67    }
68}
69
70impl RTCCrypto for AwsLcRsCrypto {
71    fn supports(&self, algorithm: CryptoAlgorithm) -> bool {
72        matches!(
73            algorithm,
74            CryptoAlgorithm::Hash(
75                HashAlgorithm::Md5
76                    | HashAlgorithm::Sha256
77                    | HashAlgorithm::Sha1
78                    | HashAlgorithm::Sha224
79                    | HashAlgorithm::Sha384
80                    | HashAlgorithm::Sha512
81            ) | CryptoAlgorithm::Hmac(
82                HmacAlgorithm::Sha1
83                    | HmacAlgorithm::Sha256
84                    | HmacAlgorithm::Sha384
85                    | HmacAlgorithm::Sha512
86            ) | CryptoAlgorithm::HeaderMask(
87                HeaderMaskAlgorithm::Aes128
88                    | HeaderMaskAlgorithm::Aes256
89                    | HeaderMaskAlgorithm::ChaCha20
90            ) | CryptoAlgorithm::Aead(
91                AeadAlgorithm::Aes128Gcm
92                    | AeadAlgorithm::Aes256Gcm
93                    | AeadAlgorithm::Aes128Ccm
94                    | AeadAlgorithm::Aes128Ccm8
95                    | AeadAlgorithm::ChaCha20Poly1305,
96            ) | CryptoAlgorithm::StreamCipher(
97                StreamCipherAlgorithm::Aes128Ctr
98                    | StreamCipherAlgorithm::Aes256Ctr
99                    | StreamCipherAlgorithm::Aes192Ctr,
100            ) | CryptoAlgorithm::BlockCipher(
101                BlockCipherAlgorithm::Aes128
102                    | BlockCipherAlgorithm::Aes256
103                    | BlockCipherAlgorithm::Aes192,
104            ) | CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc)
105                | CryptoAlgorithm::KeyExchange(
106                    KeyExchangeAlgorithm::P256
107                        | KeyExchangeAlgorithm::P384
108                        | KeyExchangeAlgorithm::X25519
109                        | KeyExchangeAlgorithm::X25519MlKem768,
110                )
111                | CryptoAlgorithm::Signature(
112                    SignatureScheme::Ed25519
113                        | SignatureScheme::EcdsaP256Sha256
114                        | SignatureScheme::EcdsaP384Sha256
115                        | SignatureScheme::EcdsaP384Sha384
116                        | SignatureScheme::RsaPkcs1Sha1
117                        | SignatureScheme::RsaPkcs1Sha256
118                        | SignatureScheme::RsaPkcs1Sha384
119                        | SignatureScheme::RsaPkcs1Sha512
120                        | SignatureScheme::RsaPssSha256
121                        | SignatureScheme::RsaPssSha384
122                        | SignatureScheme::RsaPssSha512,
123                )
124                | CryptoAlgorithm::SigningKeyGeneration(
125                    SignatureScheme::Ed25519
126                        | SignatureScheme::EcdsaP256Sha256
127                        | SignatureScheme::RsaPkcs1Sha256,
128                )
129                | CryptoAlgorithm::SigningKeyImport(
130                    SignatureScheme::Ed25519
131                        | SignatureScheme::EcdsaP256Sha256
132                        | SignatureScheme::RsaPkcs1Sha256,
133                )
134        )
135    }
136
137    fn hash(&self, algorithm: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
138        match algorithm {
139            HashAlgorithm::Md5 => Ok(common::md5(data)),
140            HashAlgorithm::Sha256 => Ok(digest::digest(&digest::SHA256, data).as_ref().to_vec()),
141            HashAlgorithm::Sha1 => Ok(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data)
142                .as_ref()
143                .to_vec()),
144            HashAlgorithm::Sha224 => Ok(digest::digest(&digest::SHA224, data).as_ref().to_vec()),
145            HashAlgorithm::Sha384 => Ok(digest::digest(&digest::SHA384, data).as_ref().to_vec()),
146            HashAlgorithm::Sha512 => Ok(digest::digest(&digest::SHA512, data).as_ref().to_vec()),
147        }
148    }
149
150    fn new_hmac(&self, algorithm: HmacAlgorithm, key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
151        Ok(Box::new(AwsLcRsHmac {
152            key: hmac::Key::new(hmac_algorithm(algorithm), key),
153            output_len: algorithm.output_len(),
154        }))
155    }
156
157    fn block_encrypt(
158        &self,
159        algorithm: BlockCipherAlgorithm,
160        key: &[u8],
161        block: &mut [u8],
162    ) -> Result<(), CryptoError> {
163        common::block_encrypt(algorithm, key, block)
164    }
165
166    fn new_stream_cipher(
167        &self,
168        algorithm: StreamCipherAlgorithm,
169        key: &[u8],
170    ) -> Result<Box<dyn StreamCipher>, CryptoError> {
171        common::new_stream_cipher(algorithm, key)
172    }
173
174    fn new_aead(
175        &self,
176        algorithm: AeadAlgorithm,
177        key: &[u8],
178    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
179        match algorithm {
180            AeadAlgorithm::Aes128Ccm | AeadAlgorithm::Aes128Ccm8 => common::new_ccm(algorithm, key),
181            AeadAlgorithm::Aes128Gcm => AwsLcRsAead::create(&aead::AES_128_GCM, key),
182            AeadAlgorithm::Aes256Gcm => AwsLcRsAead::create(&aead::AES_256_GCM, key),
183            AeadAlgorithm::ChaCha20Poly1305 => AwsLcRsAead::create(&aead::CHACHA20_POLY1305, key),
184        }
185    }
186
187    fn new_header_mask(
188        &self,
189        algorithm: HeaderMaskAlgorithm,
190        key: &[u8],
191    ) -> Result<Box<dyn HeaderMask>, CryptoError> {
192        common::check_key_len(algorithm.key_len(), key.len())?;
193        let backend_algorithm = match algorithm {
194            HeaderMaskAlgorithm::Aes128 => &aead::quic::AES_128,
195            HeaderMaskAlgorithm::Aes256 => &aead::quic::AES_256,
196            HeaderMaskAlgorithm::ChaCha20 => &aead::quic::CHACHA20,
197        };
198        let key = aead::quic::HeaderProtectionKey::new(backend_algorithm, key)
199            .map_err(|_| CryptoError::InvalidPrivateKey)?;
200        Ok(Box::new(AwsLcRsHeaderMask { key }))
201    }
202
203    fn new_cbc(
204        &self,
205        algorithm: CbcAlgorithm,
206        key: &[u8],
207    ) -> Result<Box<dyn CbcCipher>, CryptoError> {
208        common::new_cbc(algorithm, key)
209    }
210
211    fn start_key_exchange(
212        &self,
213        algorithm: KeyExchangeAlgorithm,
214    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
215        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
216            return HybridKeyExchange::start();
217        }
218        AwsLcRsKeyExchange::start(algorithm)
219    }
220
221    fn key_exchange_respond(
222        &self,
223        algorithm: KeyExchangeAlgorithm,
224        peer_share: &[u8],
225    ) -> Result<(Vec<u8>, SecretVec), CryptoError> {
226        if algorithm == KeyExchangeAlgorithm::X25519MlKem768 {
227            return HybridKeyExchange::respond(peer_share);
228        }
229        let exchange = self.start_key_exchange(algorithm)?;
230        let share = exchange.public_key().to_vec();
231        let secret = exchange.complete(peer_share)?;
232        Ok((share, secret))
233    }
234
235    fn generate_signing_key(
236        &self,
237        scheme: SignatureScheme,
238    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
239        AwsLcRsSigningKey::generate(scheme)
240    }
241
242    fn import_signing_key(
243        &self,
244        scheme: SignatureScheme,
245        pkcs8_der: &[u8],
246    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
247        AwsLcRsSigningKey::import(scheme, pkcs8_der)
248    }
249
250    fn verify_signature(
251        &self,
252        scheme: SignatureScheme,
253        public_key: PublicKey<'_>,
254        message: &[u8],
255        signature: &[u8],
256    ) -> Result<(), CryptoError> {
257        verify_public_key_encoding(scheme, public_key.encoding)?;
258        signature::UnparsedPublicKey::new(verification_algorithm(scheme), public_key.bytes)
259            .verify(message, signature)
260            .map_err(|_| CryptoError::InvalidSignature)
261    }
262}
263
264/// A keyed HMAC holding an `aws_lc_rs::hmac::Key`.
265///
266/// `Key::new` performs the ipad/opad derivation; `Context::with_key` only clones the resulting
267/// state. Keeping the key here is what moves that derivation off the per-packet path.
268struct AwsLcRsHmac {
269    key: hmac::Key,
270    output_len: usize,
271}
272
273impl Mac for AwsLcRsHmac {
274    fn output_len(&self) -> usize {
275        self.output_len
276    }
277
278    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
279        common::check_tag_len(self.output_len, output.len())?;
280        // AWS-LC computes the MAC on a copy of the keyed context (both padded-key states) in its
281        // own stack frames: overwritten after the call (`set_record_stack_erasure`).
282        crate::secret::erased_record_call::<{ crate::secret::record_depth::AWS_LC_HMAC }, _>(
283            || {
284                let mut context = hmac::Context::with_key(&self.key);
285                for part in input {
286                    context.update(part);
287                }
288                output.copy_from_slice(context.sign().as_ref());
289            },
290        );
291        Ok(())
292    }
293
294    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
295        common::check_tag_len(self.output_len, expected.len())?;
296        let mut actual = vec![0; self.output_len];
297        self.sign(input, &mut actual)?;
298        if constant_time_eq(&actual, expected) {
299            Ok(())
300        } else {
301            Err(CryptoError::AuthenticationFailed)
302        }
303    }
304}
305
306fn hmac_algorithm(algorithm: HmacAlgorithm) -> hmac::Algorithm {
307    match algorithm {
308        HmacAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
309        HmacAlgorithm::Sha256 => hmac::HMAC_SHA256,
310        HmacAlgorithm::Sha512 => hmac::HMAC_SHA512,
311        HmacAlgorithm::Sha384 => hmac::HMAC_SHA384,
312    }
313}
314
315/// A record-number mask generator on the backend's QUIC header-protection key, which is the
316/// computation RFC 9147 section 4.2.3 defines (AES-ECB of the sample, or the ChaCha20 block
317/// function keyed by it).
318struct AwsLcRsHeaderMask {
319    key: aead::quic::HeaderProtectionKey,
320}
321
322impl HeaderMask for AwsLcRsHeaderMask {
323    fn mask(
324        &mut self,
325        sample: &[u8; HEADER_MASK_SAMPLE_LEN],
326    ) -> Result<[u8; HEADER_MASK_LEN], CryptoError> {
327        // The DTLS 1.3 record-number mask, once per record: AES-ECB or a ChaCha20 block keyed
328        // by the record-number key in AWS-LC's own frames, overwritten after the call
329        // (`set_record_stack_erasure`).
330        let key = &self.key;
331        crate::secret::erased_record_call::<{ crate::secret::record_depth::AWS_LC_HEADER_MASK }, _>(
332            || {
333                key.new_mask(sample)
334                    .map_err(|_| CryptoError::Provider("header mask generation failed".into()))
335            },
336        )
337    }
338}
339
340struct AwsLcRsAead {
341    key: aead::LessSafeKey,
342}
343
344impl AwsLcRsAead {
345    fn create(
346        algorithm: &'static aead::Algorithm,
347        key: &[u8],
348    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
349        common::check_key_len(algorithm.key_len(), key.len())?;
350        let key = aead::UnboundKey::new(algorithm, key)
351            .map(aead::LessSafeKey::new)
352            .map_err(|_| CryptoError::InvalidPrivateKey)?;
353        Ok(Box::new(Self { key }))
354    }
355}
356
357impl AeadCipher for AwsLcRsAead {
358    fn tag_len(&self) -> usize {
359        16
360    }
361
362    fn seal_in_place(
363        &mut self,
364        nonce: &[u8],
365        aad: &[u8],
366        plaintext_and_ciphertext: &mut [u8],
367        tag_out: &mut [u8],
368    ) -> Result<(), CryptoError> {
369        common::check_nonce_len(12, nonce.len())?;
370        common::check_tag_len(self.tag_len(), tag_out.len())?;
371        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
372            CryptoError::InvalidNonceLength {
373                expected: 12,
374                actual: nonce.len(),
375            }
376        })?;
377        // AWS-LC's AES-GCM leaves a GHASH table entry in its own stack frames: overwritten
378        // after the call (`set_record_stack_erasure`).
379        let key = &self.key;
380        crate::secret::erased_record_call::<{ crate::secret::record_depth::AWS_LC_AEAD }, _>(|| {
381            let tag = key
382                .seal_in_place_separate_tag(nonce, aead::Aad::from(aad), plaintext_and_ciphertext)
383                .map_err(|_| CryptoError::AuthenticationFailed)?;
384            tag_out.copy_from_slice(tag.as_ref());
385            Ok(())
386        })
387    }
388
389    fn open_in_place(
390        &mut self,
391        nonce: &[u8],
392        aad: &[u8],
393        ciphertext_and_plaintext: &mut [u8],
394        tag: &[u8],
395    ) -> Result<(), CryptoError> {
396        common::check_nonce_len(12, nonce.len())?;
397        common::check_tag_len(self.tag_len(), tag.len())?;
398        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
399            CryptoError::InvalidNonceLength {
400                expected: 12,
401                actual: nonce.len(),
402            }
403        })?;
404        let key = &self.key;
405        crate::secret::erased_record_call::<{ crate::secret::record_depth::AWS_LC_AEAD }, _>(|| {
406            key.open_in_place_separate_tag(
407                nonce,
408                aead::Aad::from(aad),
409                tag,
410                ciphertext_and_plaintext,
411            )
412            .map(|_| ())
413            .map_err(|_| CryptoError::AuthenticationFailed)
414        })
415    }
416}
417
418/// The lengths of X25519MLKEM768 (draft-ietf-tls-ecdhe-mlkem section 4.2).
419const ML_KEM_768_ENCAPSULATION_KEY_LEN: usize = 1184;
420const ML_KEM_768_CIPHERTEXT_LEN: usize = 1088;
421const X25519_LEN: usize = 32;
422
423/// The initiator's half of X25519MLKEM768: an ML-KEM-768 decapsulation key and an X25519
424/// private key. Its share is the encapsulation key followed by the X25519 public key.
425struct HybridKeyExchange {
426    decapsulation_key: aws_lc_rs::kem::DecapsulationKey,
427    x25519: agreement::PrivateKey,
428    share: Vec<u8>,
429}
430
431impl HybridKeyExchange {
432    fn failure(what: &'static str) -> CryptoError {
433        CryptoError::Provider(what.into())
434    }
435
436    fn start() -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
437        let decapsulation_key =
438            aws_lc_rs::kem::DecapsulationKey::generate(&aws_lc_rs::kem::ML_KEM_768)
439                .map_err(|_| CryptoError::RandomnessFailed)?;
440        let encapsulation_key = decapsulation_key
441            .encapsulation_key()
442            .and_then(|key| key.key_bytes())
443            .map_err(|_| Self::failure("ML-KEM key generation failed"))?;
444        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
445            .map_err(|_| CryptoError::RandomnessFailed)?;
446        let x25519_public = x25519
447            .compute_public_key()
448            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
449        let mut share = encapsulation_key.as_ref().to_vec();
450        share.extend_from_slice(x25519_public.as_ref());
451        Ok(Box::new(Self {
452            decapsulation_key,
453            x25519,
454            share,
455        }))
456    }
457
458    /// The responder's half: encapsulates to the initiator's ML-KEM key and agrees with its
459    /// X25519 key. The share is the ciphertext followed by an X25519 public key, the secret
460    /// the ML-KEM shared secret followed by the X25519 one.
461    fn respond(peer_share: &[u8]) -> Result<(Vec<u8>, SecretVec), CryptoError> {
462        if peer_share.len() != ML_KEM_768_ENCAPSULATION_KEY_LEN + X25519_LEN {
463            return Err(CryptoError::InvalidPublicKey);
464        }
465        let (encapsulation_key, peer_x25519) =
466            peer_share.split_at(ML_KEM_768_ENCAPSULATION_KEY_LEN);
467        let encapsulation_key =
468            aws_lc_rs::kem::EncapsulationKey::new(&aws_lc_rs::kem::ML_KEM_768, encapsulation_key)
469                .map_err(|_| CryptoError::InvalidPublicKey)?;
470        let (ciphertext, kem_secret) = encapsulation_key
471            .encapsulate()
472            .map_err(|_| CryptoError::InvalidPublicKey)?;
473        let x25519 = agreement::PrivateKey::generate(&agreement::X25519)
474            .map_err(|_| CryptoError::RandomnessFailed)?;
475        let x25519_public = x25519
476            .compute_public_key()
477            .map_err(|_| Self::failure("key exchange public-key generation failed"))?;
478        let mut secret = kem_secret.as_ref().to_vec();
479        agreement::agree(
480            &x25519,
481            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
482            CryptoError::InvalidPublicKey,
483            |x25519_secret| {
484                secret.extend_from_slice(x25519_secret);
485                Ok(())
486            },
487        )?;
488        let mut share = ciphertext.as_ref().to_vec();
489        share.extend_from_slice(x25519_public.as_ref());
490        Ok((share, SecretVec::new(secret)))
491    }
492}
493
494impl ActiveKeyExchange for HybridKeyExchange {
495    fn algorithm(&self) -> KeyExchangeAlgorithm {
496        KeyExchangeAlgorithm::X25519MlKem768
497    }
498
499    fn public_key(&self) -> &[u8] {
500        &self.share
501    }
502
503    fn complete(self: Box<Self>, peer_share: &[u8]) -> Result<SecretVec, CryptoError> {
504        if peer_share.len() != ML_KEM_768_CIPHERTEXT_LEN + X25519_LEN {
505            return Err(CryptoError::InvalidPublicKey);
506        }
507        let (ciphertext, peer_x25519) = peer_share.split_at(ML_KEM_768_CIPHERTEXT_LEN);
508        let kem_secret = self
509            .decapsulation_key
510            .decapsulate(ciphertext.into())
511            .map_err(|_| CryptoError::InvalidPublicKey)?;
512        let mut secret = kem_secret.as_ref().to_vec();
513        agreement::agree(
514            &self.x25519,
515            agreement::UnparsedPublicKey::new(&agreement::X25519, peer_x25519),
516            CryptoError::InvalidPublicKey,
517            |x25519_secret| {
518                secret.extend_from_slice(x25519_secret);
519                Ok(())
520            },
521        )?;
522        Ok(SecretVec::new(secret))
523    }
524}
525
526struct AwsLcRsKeyExchange {
527    algorithm: KeyExchangeAlgorithm,
528    backend_algorithm: &'static agreement::Algorithm,
529    private_key: agreement::PrivateKey,
530    public_key: Vec<u8>,
531}
532
533impl AwsLcRsKeyExchange {
534    fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
535        let backend_algorithm = agreement_algorithm(algorithm);
536        let private_key = agreement::PrivateKey::generate(backend_algorithm)
537            .map_err(|_| CryptoError::RandomnessFailed)?;
538        let public_key = private_key
539            .compute_public_key()
540            .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
541            .as_ref()
542            .to_vec();
543        Ok(Box::new(Self {
544            algorithm,
545            backend_algorithm,
546            private_key,
547            public_key,
548        }))
549    }
550}
551
552impl ActiveKeyExchange for AwsLcRsKeyExchange {
553    fn algorithm(&self) -> KeyExchangeAlgorithm {
554        self.algorithm
555    }
556
557    fn public_key(&self) -> &[u8] {
558        &self.public_key
559    }
560
561    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
562        check_wire_share(self.algorithm, peer_public_key)?;
563        let peer = agreement::UnparsedPublicKey::new(self.backend_algorithm, peer_public_key);
564        agreement::agree(
565            &self.private_key,
566            peer,
567            CryptoError::InvalidPublicKey,
568            |secret| Ok(SecretVec::new(secret.to_vec())),
569        )
570    }
571}
572
573/// Takes only the wire form of a key share: the uncompressed point for P-256 and P-384 (RFC
574/// 8446 section 4.2.8.2, `legacy_form = 4`; RFC 8422 section 5.4.1) and the 32-byte
575/// u-coordinate for X25519, which is all ring takes. aws-lc-rs also parses a
576/// SubjectPublicKeyInfo and a compressed or hybrid point, so a peer could send those
577/// (Wycheproof `ecdh_secp256r1_ecpoint_test.json` tcId 2).
578fn check_wire_share(algorithm: KeyExchangeAlgorithm, share: &[u8]) -> Result<(), CryptoError> {
579    let wire = match algorithm {
580        KeyExchangeAlgorithm::P256 => share.len() == 65 && share[0] == 0x04,
581        KeyExchangeAlgorithm::P384 => share.len() == 97 && share[0] == 0x04,
582        KeyExchangeAlgorithm::X25519 => share.len() == 32,
583        // Its own type (`HybridKeyExchange`) splits the share at fixed lengths.
584        KeyExchangeAlgorithm::X25519MlKem768 => true,
585    };
586    if wire {
587        Ok(())
588    } else {
589        Err(CryptoError::InvalidPublicKey)
590    }
591}
592
593enum AwsLcRsSigningKeyKind {
594    Ed25519(signature::Ed25519KeyPair),
595    EcdsaP256(signature::EcdsaKeyPair),
596    Rsa(signature::RsaKeyPair),
597}
598
599struct AwsLcRsSigningKey {
600    scheme: SignatureScheme,
601    kind: AwsLcRsSigningKeyKind,
602    public_key: Vec<u8>,
603    public_key_encoding: PublicKeyEncoding,
604    pkcs8_der: SecretVec,
605}
606
607impl AwsLcRsSigningKey {
608    fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
609        let rng = SystemRandom::new();
610        let pkcs8 = match scheme {
611            SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
612            SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
613                &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
614                &rng,
615            ),
616            // W3C webrtc-pc 4.9 generateCertificate: RSASSA-PKCS1-v1_5 with a 2048-bit
617            // modulus, public exponent 65537 (AWS-LC's key generation default), SHA-256.
618            SignatureScheme::RsaPkcs1Sha256 => {
619                use aws_lc_rs::encoding::AsDer;
620                let key = aws_lc_rs::rsa::KeyPair::generate(aws_lc_rs::rsa::KeySize::Rsa2048)
621                    .map_err(|_| CryptoError::RandomnessFailed)?;
622                let pkcs8 = key.as_der().map_err(|_| CryptoError::RandomnessFailed)?;
623                return Self::import(scheme, pkcs8.as_ref());
624            }
625            _ => {
626                return Err(CryptoError::UnsupportedAlgorithm(
627                    CryptoAlgorithm::SigningKeyGeneration(scheme),
628                ));
629            }
630        }
631        .map_err(|_| CryptoError::RandomnessFailed)?;
632        Self::import(scheme, pkcs8.as_ref())
633    }
634
635    fn import(
636        scheme: SignatureScheme,
637        pkcs8_der: &[u8],
638    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
639        let (kind, public_key, public_key_encoding) = match scheme {
640            SignatureScheme::Ed25519 => {
641                let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
642                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
643                let public = key.public_key().as_ref().to_vec();
644                (
645                    AwsLcRsSigningKeyKind::Ed25519(key),
646                    public,
647                    PublicKeyEncoding::Ed25519Raw,
648                )
649            }
650            SignatureScheme::EcdsaP256Sha256 => {
651                let key = signature::EcdsaKeyPair::from_pkcs8(
652                    &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
653                    pkcs8_der,
654                )
655                .map_err(|_| CryptoError::InvalidPrivateKey)?;
656                let public = key.public_key().as_ref().to_vec();
657                (
658                    AwsLcRsSigningKeyKind::EcdsaP256(key),
659                    public,
660                    PublicKeyEncoding::EcUncompressedPoint,
661                )
662            }
663            SignatureScheme::RsaPkcs1Sha256 => {
664                let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
665                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
666                let public = key.public_key().as_ref().to_vec();
667                (
668                    AwsLcRsSigningKeyKind::Rsa(key),
669                    public,
670                    PublicKeyEncoding::RsaPkcs1Der,
671                )
672            }
673            _ => {
674                return Err(CryptoError::UnsupportedAlgorithm(
675                    CryptoAlgorithm::SigningKeyImport(scheme),
676                ));
677            }
678        };
679        Ok(Arc::new(Self {
680            scheme,
681            kind,
682            public_key,
683            public_key_encoding,
684            pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
685        }))
686    }
687}
688
689impl SigningKey for AwsLcRsSigningKey {
690    fn supports(&self, scheme: SignatureScheme) -> bool {
691        // An RSA key with the rsaEncryption OID signs PKCS#1 v1.5 and RSASSA-PSS alike
692        // (RFC 8446 section 4.2.3, the rsa_pss_rsae schemes).
693        self.scheme == scheme
694            || (matches!(self.kind, AwsLcRsSigningKeyKind::Rsa(_))
695                && matches!(
696                    scheme,
697                    SignatureScheme::RsaPssSha256
698                        | SignatureScheme::RsaPssSha384
699                        | SignatureScheme::RsaPssSha512
700                ))
701    }
702
703    fn public_key(&self) -> PublicKey<'_> {
704        PublicKey {
705            encoding: self.public_key_encoding,
706            bytes: &self.public_key,
707        }
708    }
709
710    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
711        if !self.supports(scheme) {
712            return Err(CryptoError::UnsupportedAlgorithm(
713                CryptoAlgorithm::Signature(scheme),
714            ));
715        }
716        match &self.kind {
717            AwsLcRsSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
718            AwsLcRsSigningKeyKind::EcdsaP256(key) => key
719                .sign(&SystemRandom::new(), message)
720                .map(|signature| signature.as_ref().to_vec())
721                .map_err(|_| CryptoError::Provider("signature generation failed".into())),
722            AwsLcRsSigningKeyKind::Rsa(key) => {
723                let encoding: &'static dyn signature::RsaEncoding = match scheme {
724                    SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
725                    SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
726                    SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
727                    _ => &signature::RSA_PKCS1_SHA256,
728                };
729                let mut signature = vec![0; key.public_modulus_len()];
730                key.sign(encoding, &SystemRandom::new(), message, &mut signature)
731                    .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
732                Ok(signature)
733            }
734        }
735    }
736
737    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
738        Ok(Some(self.pkcs8_der.clone()))
739    }
740}
741
742fn agreement_algorithm(algorithm: KeyExchangeAlgorithm) -> &'static agreement::Algorithm {
743    match algorithm {
744        KeyExchangeAlgorithm::P256 => &agreement::ECDH_P256,
745        KeyExchangeAlgorithm::P384 => &agreement::ECDH_P384,
746        // The hybrid has its own type (`HybridKeyExchange`); its Diffie-Hellman half is
747        // X25519.
748        KeyExchangeAlgorithm::X25519 | KeyExchangeAlgorithm::X25519MlKem768 => &agreement::X25519,
749    }
750}
751
752fn verification_algorithm(
753    scheme: SignatureScheme,
754) -> &'static dyn signature::VerificationAlgorithm {
755    match scheme {
756        SignatureScheme::Ed25519 => &signature::ED25519,
757        SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
758        SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
759        SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
760        SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
761        SignatureScheme::RsaPkcs1Sha256 => {
762            &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
763        }
764        SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
765        SignatureScheme::RsaPkcs1Sha512 => {
766            &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
767        }
768        SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
769        SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
770        SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
771    }
772}
773
774fn verify_public_key_encoding(
775    scheme: SignatureScheme,
776    encoding: PublicKeyEncoding,
777) -> Result<(), CryptoError> {
778    let valid = matches!(
779        (scheme, encoding),
780        (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
781            | (
782                SignatureScheme::EcdsaP256Sha256
783                    | SignatureScheme::EcdsaP384Sha256
784                    | SignatureScheme::EcdsaP384Sha384,
785                PublicKeyEncoding::EcUncompressedPoint
786            )
787            | (
788                SignatureScheme::RsaPkcs1Sha1
789                    | SignatureScheme::RsaPkcs1Sha256
790                    | SignatureScheme::RsaPkcs1Sha384
791                    | SignatureScheme::RsaPkcs1Sha512
792                    | SignatureScheme::RsaPssSha256
793                    | SignatureScheme::RsaPssSha384
794                    | SignatureScheme::RsaPssSha512,
795                PublicKeyEncoding::RsaPkcs1Der
796            )
797    );
798    if valid {
799        Ok(())
800    } else {
801        Err(CryptoError::InvalidPublicKey)
802    }
803}