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::{ManuallyDrop, 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 3711 section 9.3, 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 tag = self
445            .key
446            .get()
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    fn open_in_place(
454        &mut self,
455        nonce: &[u8],
456        aad: &[u8],
457        ciphertext_and_plaintext: &mut [u8],
458        tag: &[u8],
459    ) -> Result<(), CryptoError> {
460        common::check_nonce_len(12, nonce.len())?;
461        common::check_tag_len(self.tag_len(), tag.len())?;
462        let nonce = aead::Nonce::try_assume_unique_for_key(nonce).map_err(|_| {
463            CryptoError::InvalidNonceLength {
464                expected: 12,
465                actual: nonce.len(),
466            }
467        })?;
468        let tag = aead::Tag::try_from(tag).map_err(|_| CryptoError::InvalidTagLength {
469            expected: self.tag_len(),
470            actual: tag.len(),
471        })?;
472        self.key
473            .get()
474            .open_in_place_separate_tag(
475                nonce,
476                aead::Aad::from(aad),
477                tag,
478                ciphertext_and_plaintext,
479                0..,
480            )
481            .map(|_| ())
482            .map_err(|_| CryptoError::AuthenticationFailed)
483    }
484}
485
486struct RingKeyExchange {
487    algorithm: KeyExchangeAlgorithm,
488    backend_algorithm: &'static agreement::Algorithm,
489    /// ring's ephemeral private key keeps the scalar inline and does not erase it; it is
490    /// consumed by value by `agree_ephemeral`, so it leaves its slot through `into_inner`.
491    private_key: ErasedOnDrop<agreement::EphemeralPrivateKey>,
492    public_key: Vec<u8>,
493}
494
495impl RingKeyExchange {
496    fn start(algorithm: KeyExchangeAlgorithm) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
497        Self::start_with(algorithm, &SystemRandom::new())
498    }
499
500    fn start_with(
501        algorithm: KeyExchangeAlgorithm,
502        rng: &dyn ring::rand::SecureRandom,
503    ) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
504        let backend_algorithm = agreement_algorithm(algorithm)?;
505        let private_key = agreement::EphemeralPrivateKey::generate(backend_algorithm, rng)
506            .map_err(|_| CryptoError::RandomnessFailed)?;
507        let public_key = private_key
508            .compute_public_key()
509            .map_err(|_| CryptoError::Provider("key exchange public-key generation failed".into()))?
510            .as_ref()
511            .to_vec();
512        Ok(Box::new(Self {
513            algorithm,
514            backend_algorithm,
515            private_key: ErasedOnDrop::new(private_key),
516            public_key,
517        }))
518    }
519}
520
521impl ActiveKeyExchange for RingKeyExchange {
522    fn algorithm(&self) -> KeyExchangeAlgorithm {
523        self.algorithm
524    }
525
526    fn public_key(&self) -> &[u8] {
527        &self.public_key
528    }
529
530    fn complete(self: Box<Self>, peer_public_key: &[u8]) -> Result<SecretVec, CryptoError> {
531        let this = *self;
532        let peer = agreement::UnparsedPublicKey::new(this.backend_algorithm, peer_public_key);
533        agreement::agree_ephemeral(this.private_key.into_inner(), &peer, |secret| {
534            SecretVec::new(secret.to_vec())
535        })
536        .map_err(|_| CryptoError::InvalidPublicKey)
537    }
538}
539
540enum RingSigningKeyKind {
541    Ed25519(signature::Ed25519KeyPair),
542    EcdsaP256(signature::EcdsaKeyPair),
543    Rsa(signature::RsaKeyPair),
544}
545
546struct RingSigningKey {
547    scheme: SignatureScheme,
548    /// ring's key pairs keep the private key inline (an RSA key also in limb buffers of its
549    /// own) and do not erase it.
550    kind: ErasedOnDrop<RingSigningKeyKind>,
551    public_key: Vec<u8>,
552    public_key_encoding: PublicKeyEncoding,
553    pkcs8_der: SecretVec,
554}
555
556impl RingSigningKey {
557    fn generate(scheme: SignatureScheme) -> Result<Arc<dyn SigningKey>, CryptoError> {
558        let rng = SystemRandom::new();
559        let pkcs8 = match scheme {
560            SignatureScheme::Ed25519 => signature::Ed25519KeyPair::generate_pkcs8(&rng),
561            SignatureScheme::EcdsaP256Sha256 => signature::EcdsaKeyPair::generate_pkcs8(
562                &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
563                &rng,
564            ),
565            _ => {
566                return Err(CryptoError::UnsupportedAlgorithm(
567                    CryptoAlgorithm::SigningKeyGeneration(scheme),
568                ));
569            }
570        }
571        .map_err(|_| CryptoError::RandomnessFailed)?;
572        Self::import(scheme, pkcs8.as_ref())
573    }
574
575    fn import(
576        scheme: SignatureScheme,
577        pkcs8_der: &[u8],
578    ) -> Result<Arc<dyn SigningKey>, CryptoError> {
579        let rng = SystemRandom::new();
580        let (kind, public_key, public_key_encoding) = match scheme {
581            SignatureScheme::Ed25519 => {
582                let key = signature::Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8_der)
583                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
584                let public = key.public_key().as_ref().to_vec();
585                (
586                    RingSigningKeyKind::Ed25519(key),
587                    public,
588                    PublicKeyEncoding::Ed25519Raw,
589                )
590            }
591            SignatureScheme::EcdsaP256Sha256 => {
592                let key = signature::EcdsaKeyPair::from_pkcs8(
593                    &signature::ECDSA_P256_SHA256_ASN1_SIGNING,
594                    pkcs8_der,
595                    &rng,
596                )
597                .map_err(|_| CryptoError::InvalidPrivateKey)?;
598                let public = key.public_key().as_ref().to_vec();
599                (
600                    RingSigningKeyKind::EcdsaP256(key),
601                    public,
602                    PublicKeyEncoding::EcUncompressedPoint,
603                )
604            }
605            SignatureScheme::RsaPkcs1Sha256 => {
606                let key = signature::RsaKeyPair::from_pkcs8(pkcs8_der)
607                    .map_err(|_| CryptoError::InvalidPrivateKey)?;
608                let public = key.public().as_ref().to_vec();
609                (
610                    RingSigningKeyKind::Rsa(key),
611                    public,
612                    PublicKeyEncoding::RsaPkcs1Der,
613                )
614            }
615            _ => {
616                return Err(CryptoError::UnsupportedAlgorithm(
617                    CryptoAlgorithm::SigningKeyImport(scheme),
618                ));
619            }
620        };
621        Ok(Arc::new(Self {
622            scheme,
623            kind: ErasedOnDrop::new(kind),
624            public_key,
625            public_key_encoding,
626            pkcs8_der: SecretVec::new(pkcs8_der.to_vec()),
627        }))
628    }
629}
630
631impl SigningKey for RingSigningKey {
632    fn supports(&self, scheme: SignatureScheme) -> bool {
633        // An RSA key with the rsaEncryption OID signs PKCS#1 v1.5 and RSASSA-PSS alike
634        // (RFC 8446 section 4.2.3, the rsa_pss_rsae schemes).
635        self.scheme == scheme
636            || (matches!(self.kind.get(), RingSigningKeyKind::Rsa(_))
637                && matches!(
638                    scheme,
639                    SignatureScheme::RsaPssSha256
640                        | SignatureScheme::RsaPssSha384
641                        | SignatureScheme::RsaPssSha512
642                ))
643    }
644
645    fn public_key(&self) -> PublicKey<'_> {
646        PublicKey {
647            encoding: self.public_key_encoding,
648            bytes: &self.public_key,
649        }
650    }
651
652    fn sign(&self, scheme: SignatureScheme, message: &[u8]) -> Result<Vec<u8>, CryptoError> {
653        if !self.supports(scheme) {
654            return Err(CryptoError::UnsupportedAlgorithm(
655                CryptoAlgorithm::Signature(scheme),
656            ));
657        }
658        match self.kind.get() {
659            RingSigningKeyKind::Ed25519(key) => Ok(key.sign(message).as_ref().to_vec()),
660            RingSigningKeyKind::EcdsaP256(key) => key
661                .sign(&SystemRandom::new(), message)
662                .map(|signature| signature.as_ref().to_vec())
663                .map_err(|_| CryptoError::Provider("signature generation failed".into())),
664            RingSigningKeyKind::Rsa(key) => {
665                let encoding: &'static dyn signature::RsaEncoding = match scheme {
666                    SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_SHA256,
667                    SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_SHA384,
668                    SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_SHA512,
669                    _ => &signature::RSA_PKCS1_SHA256,
670                };
671                let mut signature = vec![0; key.public().modulus_len()];
672                key.sign(encoding, &SystemRandom::new(), message, &mut signature)
673                    .map_err(|_| CryptoError::Provider("signature generation failed".into()))?;
674                Ok(signature)
675            }
676        }
677    }
678
679    fn to_pkcs8_der(&self) -> Result<Option<SecretVec>, CryptoError> {
680        Ok(Some(self.pkcs8_der.clone()))
681    }
682}
683
684fn agreement_algorithm(
685    algorithm: KeyExchangeAlgorithm,
686) -> Result<&'static agreement::Algorithm, CryptoError> {
687    match algorithm {
688        KeyExchangeAlgorithm::P256 => Ok(&agreement::ECDH_P256),
689        KeyExchangeAlgorithm::P384 => Ok(&agreement::ECDH_P384),
690        KeyExchangeAlgorithm::X25519 => Ok(&agreement::X25519),
691        // ring has no ML-KEM.
692        KeyExchangeAlgorithm::X25519MlKem768 => Err(CryptoError::UnsupportedAlgorithm(
693            CryptoAlgorithm::KeyExchange(algorithm),
694        )),
695    }
696}
697
698fn verification_algorithm(
699    scheme: SignatureScheme,
700) -> &'static dyn signature::VerificationAlgorithm {
701    match scheme {
702        SignatureScheme::Ed25519 => &signature::ED25519,
703        SignatureScheme::EcdsaP256Sha256 => &signature::ECDSA_P256_SHA256_ASN1,
704        SignatureScheme::EcdsaP384Sha256 => &signature::ECDSA_P384_SHA256_ASN1,
705        SignatureScheme::EcdsaP384Sha384 => &signature::ECDSA_P384_SHA384_ASN1,
706        SignatureScheme::RsaPkcs1Sha1 => &signature::RSA_PKCS1_1024_8192_SHA1_FOR_LEGACY_USE_ONLY,
707        SignatureScheme::RsaPkcs1Sha256 => {
708            &signature::RSA_PKCS1_1024_8192_SHA256_FOR_LEGACY_USE_ONLY
709        }
710        SignatureScheme::RsaPkcs1Sha384 => &signature::RSA_PKCS1_2048_8192_SHA384,
711        SignatureScheme::RsaPkcs1Sha512 => {
712            &signature::RSA_PKCS1_1024_8192_SHA512_FOR_LEGACY_USE_ONLY
713        }
714        SignatureScheme::RsaPssSha256 => &signature::RSA_PSS_2048_8192_SHA256,
715        SignatureScheme::RsaPssSha384 => &signature::RSA_PSS_2048_8192_SHA384,
716        SignatureScheme::RsaPssSha512 => &signature::RSA_PSS_2048_8192_SHA512,
717    }
718}
719
720fn verify_public_key_encoding(
721    scheme: SignatureScheme,
722    encoding: PublicKeyEncoding,
723) -> Result<(), CryptoError> {
724    let valid = matches!(
725        (scheme, encoding),
726        (SignatureScheme::Ed25519, PublicKeyEncoding::Ed25519Raw)
727            | (
728                SignatureScheme::EcdsaP256Sha256
729                    | SignatureScheme::EcdsaP384Sha256
730                    | SignatureScheme::EcdsaP384Sha384,
731                PublicKeyEncoding::EcUncompressedPoint
732            )
733            | (
734                SignatureScheme::RsaPkcs1Sha1
735                    | SignatureScheme::RsaPkcs1Sha256
736                    | SignatureScheme::RsaPkcs1Sha384
737                    | SignatureScheme::RsaPkcs1Sha512
738                    | SignatureScheme::RsaPssSha256
739                    | SignatureScheme::RsaPssSha384
740                    | SignatureScheme::RsaPssSha512,
741                PublicKeyEncoding::RsaPkcs1Der
742            )
743    );
744    if valid {
745        Ok(())
746    } else {
747        Err(CryptoError::InvalidPublicKey)
748    }
749}
750
751type HmacSha1 = ::hmac::Hmac<Sha1>;
752
753/// HMAC-SHA1 backed by RustCrypto, keyed once.
754///
755/// `ring` exposes SHA-1 only as `HMAC_SHA1_FOR_LEGACY_USE_ONLY` and does not use the ARMv8 SHA-1
756/// instructions, measuring 4469 ns against RustCrypto's 1373 ns over a 1212-byte SRTP packet —
757/// 3.3x, and the whole of the SRTP AES-CM/HMAC regression. The built-in providers are already
758/// composite (AES-CTR, CCM, CBC and MD5 come from RustCrypto too), so HMAC-SHA1 is composed the
759/// same way rather than making the slower backend the default. `aws-lc-rs` has fast SHA-1 and
760/// keeps its own.
761///
762/// The keyed state is the key in another form: the SHA-1 states after `key XOR ipad` and
763/// `key XOR opad` compute any MAC under it. RustCrypto `hmac` 0.12 has no `zeroize` support, so
764/// the state is overwritten here when this is dropped (RFC 7714 section 13.1; RFC 3711 section
765/// 9.3 for SRTP; the record MAC keys of the DTLS CBC suite).
766pub(crate) struct RustCryptoHmacSha1 {
767    keyed: ManuallyDrop<HmacSha1>,
768}
769
770impl RustCryptoHmacSha1 {
771    pub(crate) fn new(key: &[u8]) -> Self {
772        Self {
773            // HMAC accepts any key length: it hashes longer keys and zero-pads shorter ones.
774            keyed: ManuallyDrop::new(
775                <HmacSha1 as RustCryptoMac>::new_from_slice(key)
776                    .expect("HMAC accepts keys of any length"),
777            ),
778        }
779    }
780}
781
782impl Drop for RustCryptoHmacSha1 {
783    fn drop(&mut self) {
784        // SAFETY: the state is dropped once, here, and never used again: `ManuallyDrop` keeps
785        // the drop glue from touching it after the overwrite. `Hmac<Sha1>` is plain data (block
786        // buffers and hash words; no pointers, no heap), so overwriting its bytes once it has
787        // been dropped is a write to memory this value owns.
788        unsafe {
789            ManuallyDrop::drop(&mut self.keyed);
790            zeroize::zeroize_flat_type(&mut self.keyed as *mut ManuallyDrop<HmacSha1>);
791        }
792    }
793}
794
795impl Mac for RustCryptoHmacSha1 {
796    fn output_len(&self) -> usize {
797        20
798    }
799
800    fn sign(&mut self, input: &[&[u8]], output: &mut [u8]) -> Result<(), CryptoError> {
801        check_tag_len(20, output.len())?;
802        let mut mac = HmacSha1::clone(&self.keyed);
803        for part in input {
804            mac.update(part);
805        }
806        output.copy_from_slice(&mac.finalize().into_bytes());
807        Ok(())
808    }
809
810    fn verify(&mut self, input: &[&[u8]], expected: &[u8]) -> Result<(), CryptoError> {
811        check_tag_len(20, expected.len())?;
812        let mut actual = [0u8; 20];
813        self.sign(input, &mut actual)?;
814        if crate::constant_time_eq(&actual, expected) {
815            Ok(())
816        } else {
817            Err(CryptoError::AuthenticationFailed)
818        }
819    }
820}
821
822/// Test support: the ring provider's key exchange with its private key drawn from `seed`
823/// (exactly the seed length of the curve), so that a test knows the private scalar. Not part
824/// of the supported API.
825#[cfg(feature = "test-support")]
826#[doc(hidden)]
827#[allow(deprecated)]
828pub fn ring_key_exchange_with_seed(
829    algorithm: KeyExchangeAlgorithm,
830    seed: &[u8],
831) -> Result<Box<dyn ActiveKeyExchange>, CryptoError> {
832    RingKeyExchange::start_with(
833        algorithm,
834        &ring::test::rand::FixedSliceRandom { bytes: seed },
835    )
836}