Skip to main content

rtci_crypto/providers/
ring.rs

1use crate::common;
2use crate::common::check_tag_len;
3use crate::{
4    ActiveKeyExchange, AeadAlgorithm, AeadCipher, BlockCipherAlgorithm, CbcAlgorithm, CbcCipher,
5    CryptoAlgorithm, CryptoError, HEADER_MASK_LEN, HEADER_MASK_SAMPLE_LEN, HashAlgorithm,
6    HeaderMask, HeaderMaskAlgorithm, HmacAlgorithm, KeyExchangeAlgorithm, Mac, PublicKey,
7    PublicKeyEncoding, RTCCrypto, RTCCryptoProvider, RTCRandom, SecretVec, SignatureScheme,
8    SigningKey, StreamCipher, StreamCipherAlgorithm, constant_time_eq,
9};
10use ::hmac::Mac as RustCryptoMac;
11use ring::aead;
12use ring::agreement;
13use ring::digest;
14use ring::hmac;
15use ring::rand::SystemRandom;
16use ring::signature::{self, KeyPair};
17use sha1::Sha1;
18use std::mem::MaybeUninit;
19use std::sync::Arc;
20use std::sync::atomic::{Ordering, compiler_fence};
21
22/// The built-in Ring provider bundle.
23#[derive(Default)]
24pub struct RingProvider {
25    crypto: RingCrypto,
26    random: RingRandom,
27}
28
29impl RingProvider {
30    /// Creates a Ring provider.
31    #[must_use]
32    pub const fn new() -> Self {
33        Self {
34            crypto: RingCrypto,
35            random: RingRandom,
36        }
37    }
38}
39
40impl RTCCryptoProvider for RingProvider {
41    fn name(&self) -> &'static str {
42        "ring"
43    }
44
45    fn crypto(&self) -> &dyn RTCCrypto {
46        &self.crypto
47    }
48
49    fn random(&self) -> &dyn RTCRandom {
50        &self.random
51    }
52}
53
54/// Ring-backed cryptographic operations, with documented RustCrypto fallbacks for primitives Ring
55/// does not expose (MD5, AES block/CTR/CBC, and AES-CCM).
56#[derive(Default)]
57pub struct RingCrypto;
58
59/// Ring's operating-system-backed secure random source.
60#[derive(Default)]
61pub struct RingRandom;
62
63impl RTCRandom for RingRandom {
64    fn fill(&self, output: &mut [u8]) -> Result<(), CryptoError> {
65        common::fill_random(output)
66    }
67
68    fn fill_secret(&self, output: &mut [u8]) -> Result<(), CryptoError> {
69        use ring::rand::SecureRandom;
70        SystemRandom::new()
71            .fill(output)
72            .map_err(|_| CryptoError::RandomnessFailed)
73    }
74}
75
76impl RTCCrypto for RingCrypto {
77    fn supports(&self, algorithm: CryptoAlgorithm) -> bool {
78        matches!(
79            algorithm,
80            CryptoAlgorithm::Hash(
81                HashAlgorithm::Md5
82                    | HashAlgorithm::Sha256
83                    | HashAlgorithm::Sha1
84                    | HashAlgorithm::Sha224
85                    | HashAlgorithm::Sha384
86                    | HashAlgorithm::Sha512
87            ) | CryptoAlgorithm::Hmac(
88                HmacAlgorithm::Sha1
89                    | HmacAlgorithm::Sha256
90                    | HmacAlgorithm::Sha384
91                    | HmacAlgorithm::Sha512
92            ) | CryptoAlgorithm::HeaderMask(
93                HeaderMaskAlgorithm::Aes128
94                    | HeaderMaskAlgorithm::Aes256
95                    | HeaderMaskAlgorithm::ChaCha20
96            ) | CryptoAlgorithm::Aead(
97                AeadAlgorithm::Aes128Gcm
98                    | AeadAlgorithm::Aes256Gcm
99                    | AeadAlgorithm::Aes128Ccm
100                    | AeadAlgorithm::Aes128Ccm8
101                    | AeadAlgorithm::ChaCha20Poly1305,
102            ) | CryptoAlgorithm::StreamCipher(
103                StreamCipherAlgorithm::Aes128Ctr
104                    | StreamCipherAlgorithm::Aes256Ctr
105                    | StreamCipherAlgorithm::Aes192Ctr,
106            ) | CryptoAlgorithm::BlockCipher(
107                BlockCipherAlgorithm::Aes128
108                    | BlockCipherAlgorithm::Aes256
109                    | BlockCipherAlgorithm::Aes192,
110            ) | CryptoAlgorithm::Cbc(CbcAlgorithm::Aes256Cbc)
111                | CryptoAlgorithm::KeyExchange(
112                    KeyExchangeAlgorithm::P256
113                        | KeyExchangeAlgorithm::P384
114                        | KeyExchangeAlgorithm::X25519,
115                )
116                | CryptoAlgorithm::Signature(
117                    SignatureScheme::Ed25519
118                        | SignatureScheme::EcdsaP256Sha256
119                        | SignatureScheme::EcdsaP384Sha256
120                        | SignatureScheme::EcdsaP384Sha384
121                        | SignatureScheme::RsaPkcs1Sha1
122                        | SignatureScheme::RsaPkcs1Sha256
123                        | SignatureScheme::RsaPkcs1Sha384
124                        | SignatureScheme::RsaPkcs1Sha512
125                        | SignatureScheme::RsaPssSha256
126                        | SignatureScheme::RsaPssSha384
127                        | SignatureScheme::RsaPssSha512,
128                )
129                | CryptoAlgorithm::SigningKeyGeneration(
130                    SignatureScheme::Ed25519 | SignatureScheme::EcdsaP256Sha256,
131                )
132                | CryptoAlgorithm::SigningKeyImport(
133                    SignatureScheme::Ed25519
134                        | SignatureScheme::EcdsaP256Sha256
135                        | SignatureScheme::RsaPkcs1Sha256,
136                )
137        )
138    }
139
140    fn hash(&self, algorithm: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
141        match algorithm {
142            HashAlgorithm::Md5 => Ok(common::md5(data)),
143            HashAlgorithm::Sha256 => Ok(digest::digest(&digest::SHA256, data).as_ref().to_vec()),
144            HashAlgorithm::Sha1 => Ok(digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, data)
145                .as_ref()
146                .to_vec()),
147            // ring has no SHA-224.
148            HashAlgorithm::Sha224 => Ok(common::sha224(data)),
149            HashAlgorithm::Sha384 => Ok(digest::digest(&digest::SHA384, data).as_ref().to_vec()),
150            HashAlgorithm::Sha512 => Ok(digest::digest(&digest::SHA512, data).as_ref().to_vec()),
151        }
152    }
153
154    fn new_hmac(&self, algorithm: HmacAlgorithm, key: &[u8]) -> Result<Box<dyn Mac>, CryptoError> {
155        match algorithm {
156            // ring's SHA-1 is a software implementation and measures 3.3x slower than
157            // RustCrypto's; see common::RustCryptoHmacSha1. SHA-256 stays on ring, which uses
158            // the hardware instructions.
159            HmacAlgorithm::Sha1 => Ok(Box::new(RustCryptoHmacSha1::new(key))),
160            HmacAlgorithm::Sha256 | HmacAlgorithm::Sha384 | HmacAlgorithm::Sha512 => {
161                Ok(Box::new(RingHmac {
162                    key: ErasedOnDrop::new(hmac::Key::new(hmac_algorithm(algorithm), key)),
163                    output_len: algorithm.output_len(),
164                }))
165            }
166        }
167    }
168
169    fn block_encrypt(
170        &self,
171        algorithm: BlockCipherAlgorithm,
172        key: &[u8],
173        block: &mut [u8],
174    ) -> Result<(), CryptoError> {
175        common::block_encrypt(algorithm, key, block)
176    }
177
178    fn new_stream_cipher(
179        &self,
180        algorithm: StreamCipherAlgorithm,
181        key: &[u8],
182    ) -> Result<Box<dyn StreamCipher>, CryptoError> {
183        common::new_stream_cipher(algorithm, key)
184    }
185
186    fn new_aead(
187        &self,
188        algorithm: AeadAlgorithm,
189        key: &[u8],
190    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
191        match algorithm {
192            AeadAlgorithm::Aes128Ccm | AeadAlgorithm::Aes128Ccm8 => common::new_ccm(algorithm, key),
193            AeadAlgorithm::Aes128Gcm => RingAead::create(&aead::AES_128_GCM, key),
194            AeadAlgorithm::Aes256Gcm => RingAead::create(&aead::AES_256_GCM, key),
195            AeadAlgorithm::ChaCha20Poly1305 => RingAead::create(&aead::CHACHA20_POLY1305, key),
196        }
197    }
198
199    fn new_header_mask(
200        &self,
201        algorithm: HeaderMaskAlgorithm,
202        key: &[u8],
203    ) -> Result<Box<dyn HeaderMask>, CryptoError> {
204        common::check_key_len(algorithm.key_len(), key.len())?;
205        let backend_algorithm = match algorithm {
206            HeaderMaskAlgorithm::Aes128 => &aead::quic::AES_128,
207            HeaderMaskAlgorithm::Aes256 => &aead::quic::AES_256,
208            HeaderMaskAlgorithm::ChaCha20 => &aead::quic::CHACHA20,
209        };
210        let key = aead::quic::HeaderProtectionKey::new(backend_algorithm, key)
211            .map_err(|_| CryptoError::InvalidPrivateKey)?;
212        Ok(Box::new(RingHeaderMask {
213            key: ErasedOnDrop::new(key),
214        }))
215    }
216
217    fn new_cbc(
218        &self,
219        algorithm: CbcAlgorithm,
220        key: &[u8],
221    ) -> Result<Box<dyn CbcCipher>, CryptoError> {
222        common::new_cbc(algorithm, key)
223    }
224
225    fn start_key_exchange(
226        &self,
227        algorithm: KeyExchangeAlgorithm,
228    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
229        RingKeyExchange::start(algorithm)
230    }
231
232    fn generate_signing_key(
233        &self,
234        scheme: SignatureScheme,
235    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
236        RingSigningKey::generate(scheme)
237    }
238
239    fn import_signing_key(
240        &self,
241        scheme: SignatureScheme,
242        pkcs8_der: &[u8],
243    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
244        RingSigningKey::import(scheme, pkcs8_der)
245    }
246
247    fn verify_signature(
248        &self,
249        scheme: SignatureScheme,
250        public_key: PublicKey<'_>,
251        message: &[u8],
252        signature: &[u8],
253    ) -> Result<(), CryptoError> {
254        verify_public_key_encoding(scheme, public_key.encoding)?;
255        signature::UnparsedPublicKey::new(verification_algorithm(scheme), public_key.bytes)
256            .verify(message, signature)
257            .map_err(|_| CryptoError::InvalidSignature)
258    }
259}
260
261/// A ring key object kept in an allocation of this crate's own, overwritten with zeros when
262/// it is dropped (RFC 7714 section 13.1, RFC 8446 section 7.1).
263///
264/// ring keeps a key schedule inline in each key object (`aead::LessSafeKey`: the AES round
265/// keys and the GHASH table, or the ChaCha20 key; `aead::quic::HeaderProtectionKey`: the AES
266/// round keys or the ChaCha20 key; `hmac::Key`: the two SHA-2 states after `key XOR ipad` and
267/// `key XOR opad`) and does not overwrite it when the object is dropped (ring issue #15
268/// settled against destructor-based erasure). So the object is moved, once, into a
269/// `Box<MaybeUninit<T>>` that this type owns, is only ever lent out as `&T`, and when this is
270/// dropped the value is dropped in place and THEN the `size_of::<T>()` bytes of the slot are
271/// overwritten with volatile writes, before the box frees the allocation.
272///
273/// Soundness. After `assume_init_drop` the slot holds no live value: its bytes are the memory
274/// of a `MaybeUninit<T>` that this type owns, which may hold any bytes at all. Writing zeros
275/// there is a write to our own allocation through a raw byte pointer, so it is defined
276/// behaviour whatever ring's layout is (it does not depend on ring's fields, and an all-zero
277/// `T` is never read: `MaybeUninit` has no drop glue and the box is freed next). The volatile
278/// writes and the fence keep the compiler from removing them as stores to memory about to be
279/// freed.
280///
281/// What this type cannot reach, and so does not erase: a copy moved out of it (which is why
282/// it never hands the value out by move, only `&T`), and the copies that building the value
283/// left in the stack frames of the functions that built it. The engine's callers build a key
284/// object from a frame of their own and call [`crate::scrub_stack`] right after it. Bytes a
285/// provider type keeps outside the object (a heap allocation of its own, a global cache) are
286/// out of reach too; ring 0.17's AEAD, header-protection and HMAC keys keep none.
287struct ErasedOnDrop<T> {
288    slot: Box<MaybeUninit<T>>,
289}
290
291impl<T> ErasedOnDrop<T> {
292    fn new(value: T) -> Self {
293        let mut slot = Box::<T>::new_uninit();
294        MaybeUninit::write(&mut *slot, value);
295        Self { slot }
296    }
297
298    fn get(&self) -> &T {
299        // SAFETY: `new` initialized the slot, and the value is dropped only in `drop`.
300        unsafe { self.slot.assume_init_ref() }
301    }
302
303    /// Hands the value to an API that consumes it by value (ring's `agree_ephemeral` takes the
304    /// ECDHE private key so), overwriting the slot it leaves. The value returned is a copy in
305    /// the caller's frame, which this type cannot reach: the caller scrubs the stack after
306    /// the consuming call. Only for such APIs; everything else borrows with [`Self::get`].
307    fn into_inner(mut self) -> T {
308        // SAFETY: `new` initialized the slot; the value is read out once, the slot is then
309        // overwritten and freed without being dropped (`forget` below skips `Drop`).
310        let value = unsafe { self.slot.assume_init_read() };
311        self.overwrite();
312        // SAFETY: `self.slot` is read out once and `self` is forgotten, so the box is freed
313        // exactly once (as a `Box<MaybeUninit<T>>`, which drops no value).
314        let slot = unsafe { std::ptr::read(&self.slot) };
315        std::mem::forget(self);
316        drop(slot);
317        value
318    }
319
320    /// Overwrites the slot with zeros. Only once it holds no value.
321    fn overwrite(&mut self) {
322        let bytes = self.slot.as_mut_ptr().cast::<u8>();
323        for offset in 0..size_of::<T>() {
324            // SAFETY: `offset` is inside the slot, which this type owns and which holds no
325            // value any more; a `u8` has no validity requirement.
326            unsafe { std::ptr::write_volatile(bytes.add(offset), 0) };
327        }
328        compiler_fence(Ordering::SeqCst);
329    }
330}
331
332impl<T> Drop for ErasedOnDrop<T> {
333    fn drop(&mut self) {
334        // SAFETY: `new` initialized the slot; the value is dropped here, once, and never used
335        // again.
336        unsafe { self.slot.assume_init_drop() };
337        self.overwrite();
338    }
339}
340
341/// A keyed HMAC holding a `ring::hmac::Key`.
342///
343/// `Key::new` performs the ipad/opad derivation; `Context::with_key` only clones the resulting
344/// state. Keeping the key here is what moves that derivation off the per-packet path.
345struct RingHmac {
346    key: ErasedOnDrop<hmac::Key>,
347    output_len: usize,
348}
349
350impl Mac for RingHmac {
351    fn output_len(&self) -> usize {
352        self.output_len
353    }
354
355    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
356        common::check_tag_len(self.output_len, output.len())?;
357        let mut context = hmac::Context::with_key(self.key.get());
358        for part in input {
359            context.update(part);
360        }
361        output.copy_from_slice(context.sign().as_ref());
362        Ok(())
363    }
364
365    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
366        common::check_tag_len(self.output_len, expected.len())?;
367        let mut actual = vec![0; self.output_len];
368        self.sign(input, &mut actual)?;
369        if constant_time_eq(&actual, expected) {
370            Ok(())
371        } else {
372            Err(CryptoError::AuthenticationFailed)
373        }
374    }
375}
376
377fn hmac_algorithm(algorithm: HmacAlgorithm) -> hmac::Algorithm {
378    match algorithm {
379        HmacAlgorithm::Sha1 => hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
380        HmacAlgorithm::Sha256 => hmac::HMAC_SHA256,
381        HmacAlgorithm::Sha512 => hmac::HMAC_SHA512,
382        HmacAlgorithm::Sha384 => hmac::HMAC_SHA384,
383    }
384}
385
386/// A record-number mask generator on the backend's QUIC header-protection key, which is the
387/// computation RFC 9147 section 4.2.3 defines (AES-ECB of the sample, or the ChaCha20 block
388/// function keyed by it).
389struct RingHeaderMask {
390    key: ErasedOnDrop<aead::quic::HeaderProtectionKey>,
391}
392
393impl HeaderMask for RingHeaderMask {
394    fn mask(
395        &mut self,
396        sample: &[u8; HEADER_MASK_SAMPLE_LEN],
397    ) -> Result<[u8; HEADER_MASK_LEN], CryptoError> {
398        self.key
399            .get()
400            .new_mask(sample)
401            .map_err(|_| CryptoError::Provider("header mask generation failed".into()))
402    }
403}
404
405struct RingAead {
406    key: ErasedOnDrop<aead::LessSafeKey>,
407}
408
409impl RingAead {
410    fn create(
411        algorithm: &'static aead::Algorithm,
412        key: &[u8],
413    ) -> Result<Box<dyn AeadCipher>, CryptoError> {
414        common::check_key_len(algorithm.key_len(), key.len())?;
415        let key = aead::UnboundKey::new(algorithm, key)
416            .map(aead::LessSafeKey::new)
417            .map_err(|_| CryptoError::InvalidPrivateKey)?;
418        Ok(Box::new(Self {
419            key: ErasedOnDrop::new(key),
420        }))
421    }
422}
423
424impl AeadCipher for RingAead {
425    fn tag_len(&self) -> usize {
426        16
427    }
428
429    fn seal_in_place(
430        &mut self,
431        nonce: &[u8],
432        aad: &[u8],
433        plaintext_and_ciphertext: &mut [u8],
434        tag_out: &mut [u8],
435    ) -> Result<(), CryptoError> {
436        common::check_nonce_len(12, nonce.len())?;
437        common::check_tag_len(self.tag_len(), tag_out.len())?;
438        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
439            CryptoError::InvalidNonceLength {
440                expected: 12,
441                actual: nonce.len(),
442            }
443        })?;
444        let key = self.key.get();
445        record_call(key, || {
446            let tag = key
447                .seal_in_place_separate_tag(nonce, aead::Aad::from(aad), plaintext_and_ciphertext)
448                .map_err(|_| CryptoError::AuthenticationFailed)?;
449            tag_out.copy_from_slice(tag.as_ref());
450            Ok(())
451        })
452    }
453
454    fn open_in_place(
455        &mut self,
456        nonce: &[u8],
457        aad: &[u8],
458        ciphertext_and_plaintext: &mut [u8],
459        tag: &[u8],
460    ) -> Result<(), CryptoError> {
461        common::check_nonce_len(12, nonce.len())?;
462        common::check_tag_len(self.tag_len(), tag.len())?;
463        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
464            CryptoError::InvalidNonceLength {
465                expected: 12,
466                actual: nonce.len(),
467            }
468        })?;
469        let tag = aead::Tag::try_from(tag).map_err(|_| CryptoError::InvalidTagLength {
470            expected: self.tag_len(),
471            actual: tag.len(),
472        })?;
473        let key = self.key.get();
474        record_call(key, || {
475            key.open_in_place_separate_tag(
476                nonce,
477                aead::Aad::from(aad),
478                tag,
479                ciphertext_and_plaintext,
480                0..,
481            )
482            .map(|_| ())
483            .map_err(|_| CryptoError::AuthenticationFailed)
484        })
485    }
486}
487
488/// One record of a ring AEAD. ring's ChaCha20-Poly1305 copies the key to the stack for every
489/// record (measured: DTLS key-block bytes of the write keys in dead stack frames after the
490/// records, `rtci-dtls/tests/key_residue.rs`), so it runs under the stack overwrite of
491/// `set_record_stack_erasure`. ring's AES-GCM leaves nothing on its hardware path; on its
492/// portable path (vpaes or no-hardware AES with the fallback GHASH: a CPU without AES-NI and
493/// CLMUL) it leaves the GHASH key `H*x`, as the fallback key keeps it, in dead stack frames
494/// after the last record (the portable pass of `rtci-srtp/tests/key_residue.rs`: the SRTCP
495/// encryption key of the AES-GCM profiles, runs 46346020725 / 46346025637), so there it runs
496/// under the overwrite too.
497#[inline(always)]
498fn record_call<R>(key: &aead::LessSafeKey, work: impl FnOnce() -> R) -> R {
499    if key.algorithm() == &aead::CHACHA20_POLY1305 {
500        crate::secret::erased_record_call::<{ crate::secret::record_depth::RING_CHACHA20 }, _>(work)
501    } else if !ring_aes_gcm_hardware() {
502        crate::secret::erased_record_call::<{ crate::secret::record_depth::RING_AES_GCM_PORTABLE }, _>(
503            work,
504        )
505    } else {
506        work()
507    }
508}
509
510/// Whether ring's AES-GCM takes a hardware path on this CPU: ring 0.17.14 (`src/aead/aes_gcm.rs`
511/// `DynKey::new`) needs AES and carry-less multiplication (x86 / x86-64: AES-NI, PCLMULQDQ and
512/// SSSE3; AArch64: AES and PMULL); otherwise it uses vpaes or its no-hardware AES with the
513/// fallback GHASH. Asked conservatively: a CPU this calls portable at worst gets an overwrite
514/// it did not need.
515fn ring_aes_gcm_hardware() -> bool {
516    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
517    {
518        std::arch::is_x86_feature_detected!("aes")
519            && std::arch::is_x86_feature_detected!("pclmulqdq")
520            && std::arch::is_x86_feature_detected!("ssse3")
521    }
522    #[cfg(target_arch = "aarch64")]
523    {
524        std::arch::is_aarch64_feature_detected!("aes")
525            && std::arch::is_aarch64_feature_detected!("pmull")
526    }
527    #[cfg(not(any(target_arch = "x86", target_arch = "x86_64", target_arch = "aarch64")))]
528    {
529        false
530    }
531}
532
533struct RingKeyExchange {
534    algorithm: KeyExchangeAlgorithm,
535    backend_algorithm: &'static agreement::Algorithm,
536    /// ring's ephemeral private key keeps the scalar inline and does not erase it; it is
537    /// consumed by value by `agree_ephemeral`, so it leaves its slot through `into_inner`.
538    private_key: ErasedOnDrop<agreement::EphemeralPrivateKey>,
539    public_key: Vec<u8>,
540}
541
542impl RingKeyExchange {
543    fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
544        Self::start_with(algorithm, &SystemRandom::new())
545    }
546
547    fn start_with(
548        algorithm: KeyExchangeAlgorithm,
549        rng: &dyn ring::rand::SecureRandom,
550    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
551        let backend_algorithm = agreement_algorithm(algorithm)?;
552        let private_key = agreement::EphemeralPrivateKey::generate(backend_algorithm, rng)
553            .map_err(|_| CryptoError::RandomnessFailed)?;
554        let public_key = private_key
555            .compute_public_key()
556            .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
557            .as_ref()
558            .to_vec();
559        Ok(Box::new(Self {
560            algorithm,
561            backend_algorithm,
562            private_key: ErasedOnDrop::new(private_key),
563            public_key,
564        }))
565    }
566}
567
568impl ActiveKeyExchange for RingKeyExchange {
569    fn algorithm(&self) -> KeyExchangeAlgorithm {
570        self.algorithm
571    }
572
573    fn public_key(&self) -> &[u8] {
574        &self.public_key
575    }
576
577    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
578        let this = *self;
579        let peer = agreement::UnparsedPublicKey::new(this.backend_algorithm, peer_public_key);
580        agreement::agree_ephemeral(this.private_key.into_inner(), &peer, |secret| {
581            SecretVec::new(secret.to_vec())
582        })
583        .map_err(|_| CryptoError::InvalidPublicKey)
584    }
585}
586
587enum RingSigningKeyKind {
588    Ed25519(signature::Ed25519KeyPair),
589    EcdsaP256(signature::EcdsaKeyPair),
590    Rsa(signature::RsaKeyPair),
591}
592
593struct RingSigningKey {
594    scheme: SignatureScheme,
595    /// ring's key pairs keep the private key inline (an RSA key also in limb buffers of its
596    /// own) and do not erase it.
597    kind: ErasedOnDrop<RingSigningKeyKind>,
598    public_key: Vec<u8>,
599    public_key_encoding: PublicKeyEncoding,
600    pkcs8_der: SecretVec,
601}
602
603impl RingSigningKey {
604    fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
605        let rng = SystemRandom::new();
606        let pkcs8 = match scheme {
607            SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
608            SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
609                &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
610                &rng,
611            ),
612            _ => {
613                return Err(CryptoError::UnsupportedAlgorithm(
614                    CryptoAlgorithm::SigningKeyGeneration(scheme),
615                ));
616            }
617        }
618        .map_err(|_| CryptoError::RandomnessFailed)?;
619        Self::import(scheme, pkcs8.as_ref())
620    }
621
622    fn import(
623        scheme: SignatureScheme,
624        pkcs8_der: &[u8],
625    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
626        let rng = SystemRandom::new();
627        let (kind, public_key, public_key_encoding) = match scheme {
628            SignatureScheme::Ed25519 => {
629                let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
630                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
631                let public = key.public_key().as_ref().to_vec();
632                (
633                    RingSigningKeyKind::Ed25519(key),
634                    public,
635                    PublicKeyEncoding::Ed25519Raw,
636                )
637            }
638            SignatureScheme::EcdsaP256Sha256 => {
639                let key = signature::EcdsaKeyPair::from_pkcs8(
640                    &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
641                    pkcs8_der,
642                    &rng,
643                )
644                .map_err(|_| CryptoError::InvalidPrivateKey)?;
645                let public = key.public_key().as_ref().to_vec();
646                (
647                    RingSigningKeyKind::EcdsaP256(key),
648                    public,
649                    PublicKeyEncoding::EcUncompressedPoint,
650                )
651            }
652            SignatureScheme::RsaPkcs1Sha256 => {
653                let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
654                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
655                let public = key.public().as_ref().to_vec();
656                (
657                    RingSigningKeyKind::Rsa(key),
658                    public,
659                    PublicKeyEncoding::RsaPkcs1Der,
660                )
661            }
662            _ => {
663                return Err(CryptoError::UnsupportedAlgorithm(
664                    CryptoAlgorithm::SigningKeyImport(scheme),
665                ));
666            }
667        };
668        Ok(Arc::new(Self {
669            scheme,
670            kind: ErasedOnDrop::new(kind),
671            public_key,
672            public_key_encoding,
673            pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
674        }))
675    }
676}
677
678impl SigningKey for RingSigningKey {
679    fn supports(&self, scheme: SignatureScheme) -> bool {
680        // An RSA key with the rsaEncryption OID signs PKCS#1 v1.5 and RSASSA-PSS alike
681        // (RFC 8446 section 4.2.3, the rsa_pss_rsae schemes).
682        self.scheme == scheme
683            || (matches!(self.kind.get(), RingSigningKeyKind::Rsa(_))
684                && matches!(
685                    scheme,
686                    SignatureScheme::RsaPssSha256
687                        | SignatureScheme::RsaPssSha384
688                        | SignatureScheme::RsaPssSha512
689                ))
690    }
691
692    fn public_key(&self) -> PublicKey<'_> {
693        PublicKey {
694            encoding: self.public_key_encoding,
695            bytes: &self.public_key,
696        }
697    }
698
699    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
700        if !self.supports(scheme) {
701            return Err(CryptoError::UnsupportedAlgorithm(
702                CryptoAlgorithm::Signature(scheme),
703            ));
704        }
705        match self.kind.get() {
706            RingSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
707            RingSigningKeyKind::EcdsaP256(key) => key
708                .sign(&SystemRandom::new(), message)
709                .map(|signature| signature.as_ref().to_vec())
710                .map_err(|_| CryptoError::Provider("signature generation failed".into())),
711            RingSigningKeyKind::Rsa(key) => {
712                let encoding: &'static dyn signature::RsaEncoding = match scheme {
713                    SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
714                    SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
715                    SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
716                    _ => &signature::RSA_PKCS1_SHA256,
717                };
718                let mut signature = vec![0; key.public().modulus_len()];
719                key.sign(encoding, &SystemRandom::new(), message, &mut signature)
720                    .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
721                Ok(signature)
722            }
723        }
724    }
725
726    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
727        Ok(Some(self.pkcs8_der.clone()))
728    }
729}
730
731fn agreement_algorithm(
732    algorithm: KeyExchangeAlgorithm,
733) -> Result<&'static agreement::Algorithm, CryptoError> {
734    match algorithm {
735        KeyExchangeAlgorithm::P256 => Ok(&agreement::ECDH_P256),
736        KeyExchangeAlgorithm::P384 => Ok(&agreement::ECDH_P384),
737        KeyExchangeAlgorithm::X25519 => Ok(&agreement::X25519),
738        // ring has no ML-KEM.
739        KeyExchangeAlgorithm::X25519MlKem768 => Err(CryptoError::UnsupportedAlgorithm(
740            CryptoAlgorithm::KeyExchange(algorithm),
741        )),
742    }
743}
744
745fn verification_algorithm(
746    scheme: SignatureScheme,
747) -> &'static dyn signature::VerificationAlgorithm {
748    match scheme {
749        SignatureScheme::Ed25519 => &signature::ED25519,
750        SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
751        SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
752        SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
753        SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
754        SignatureScheme::RsaPkcs1Sha256 => {
755            &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
756        }
757        SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
758        SignatureScheme::RsaPkcs1Sha512 => {
759            &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
760        }
761        SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
762        SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
763        SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
764    }
765}
766
767fn verify_public_key_encoding(
768    scheme: SignatureScheme,
769    encoding: PublicKeyEncoding,
770) -> Result<(), CryptoError> {
771    let valid = matches!(
772        (scheme, encoding),
773        (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
774            | (
775                SignatureScheme::EcdsaP256Sha256
776                    | SignatureScheme::EcdsaP384Sha256
777                    | SignatureScheme::EcdsaP384Sha384,
778                PublicKeyEncoding::EcUncompressedPoint
779            )
780            | (
781                SignatureScheme::RsaPkcs1Sha1
782                    | SignatureScheme::RsaPkcs1Sha256
783                    | SignatureScheme::RsaPkcs1Sha384
784                    | SignatureScheme::RsaPkcs1Sha512
785                    | SignatureScheme::RsaPssSha256
786                    | SignatureScheme::RsaPssSha384
787                    | SignatureScheme::RsaPssSha512,
788                PublicKeyEncoding::RsaPkcs1Der
789            )
790    );
791    if valid {
792        Ok(())
793    } else {
794        Err(CryptoError::InvalidPublicKey)
795    }
796}
797
798type HmacSha1 = ::hmac::HmacReset<Sha1>;
799
800/// HMAC-SHA1 backed by RustCrypto (`hmac`, `sha1`), keyed once and computed in place.
801///
802/// `ring` exposes SHA-1 only as `HMAC_SHA1_FOR_LEGACY_USE_ONLY` and does not use the SHA
803/// instructions for it, measuring 4469 ns against RustCrypto's 1373 ns over a 1212-byte SRTP
804/// packet: 3.3x, and the whole of the SRTP AES-CM/HMAC regression. The built-in providers are
805/// already composite (AES-CTR, CCM, CBC and MD5 come from RustCrypto too), so HMAC-SHA1 is
806/// composed the same way rather than making the slower backend the default. `aws-lc-rs` has
807/// fast SHA-1 and keeps its own.
808///
809/// The keyed state is the key in another form: the SHA-1 states after `key XOR ipad` and
810/// `key XOR opad` compute any MAC under it (RFC 7714 section 13.1 for SRTP; the record MAC keys
811/// of the DTLS CBC suite). Where it lives:
812///
813/// * This object is boxed by `new_hmac`, and a MAC is computed in it, in place
814///   (`HmacReset`: `update`, then `finalize_reset`, which puts the inner state back from the
815///   copy the object keeps). No copy of the object is made per MAC. Until 0.2 each MAC was
816///   computed on a clone of the keyed object in a stack frame, which left both states in a
817///   dead frame for every packet (found by `rtci-srtp/tests/key_residue.rs`).
818/// * `finalize_reset` works on one copy of the outer state, in its own frame; with the
819///   `zeroize` features of `hmac` and `sha1` that copy, like every hash state of the object,
820///   is overwritten when it is dropped. That is the crates' doing, not this one's.
821pub(crate) struct RustCryptoHmacSha1 {
822    keyed: HmacSha1,
823}
824
825impl RustCryptoHmacSha1 {
826    pub(crate) fn new(key: &[u8]) -> Self {
827        Self {
828            // HMAC accepts any key length: it hashes longer keys and zero-pads shorter ones.
829            keyed: <HmacSha1 as ::hmac::KeyInit>::new_from_slice(key)
830                .expect("HMAC accepts keys of any length"),
831        }
832    }
833}
834
835impl Mac for RustCryptoHmacSha1 {
836    fn output_len(&self) -> usize {
837        20
838    }
839
840    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
841        check_tag_len(20, output.len())?;
842        let keyed = &mut self.keyed;
843        let mut mac = || {
844            for part in input {
845                keyed.update(part);
846            }
847            output.copy_from_slice(&keyed.finalize_reset().into_bytes());
848        };
849        // Without SHA instructions `sha1` runs its portable code, which leaves the HMAC states'
850        // copies in its stack frames: overwritten after the call (`record_depth`).
851        if crate::secret::rustcrypto_sha1_hardware() {
852            mac();
853        } else {
854            crate::secret::erased_record_call::<
855                { crate::secret::record_depth::RUSTCRYPTO_SHA1_PORTABLE },
856                _,
857            >(mac);
858        }
859        Ok(())
860    }
861
862    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
863        check_tag_len(20, expected.len())?;
864        let mut actual = [0u8; 20];
865        self.sign(input, &mut actual)?;
866        if crate::constant_time_eq(&actual, expected) {
867            Ok(())
868        } else {
869            Err(CryptoError::AuthenticationFailed)
870        }
871    }
872}
873
874/// Test support: the ring provider's key exchange with its private key drawn from `seed`
875/// (exactly the seed length of the curve), so that a test knows the private scalar. Not part
876/// of the supported API.
877#[cfg(feature = "test-support")]
878#[doc(hidden)]
879#[allow(deprecated)]
880pub fn ring_key_exchange_with_seed(
881    algorithm: KeyExchangeAlgorithm,
882    seed: &[u8],
883) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
884    RingKeyExchange::start_with(
885        algorithm,
886        &ring::test::rand::FixedSliceRandom { bytes: seed },
887    )
888}