aws_lc_rs/rsa/
key.rs

1// Copyright 2015-2016 Brian Smith.
2// SPDX-License-Identifier: ISC
3// Modifications copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0 OR ISC
5use super::signature::{RsaEncoding, RsaPadding};
6use super::{encoding, RsaParameters};
7#[cfg(feature = "fips")]
8use crate::aws_lc::RSA;
9use crate::aws_lc::{
10    EVP_PKEY_CTX_set_rsa_keygen_bits, EVP_PKEY_assign_RSA, EVP_PKEY_new, RSA_new, RSA_set0_key,
11    RSA_size, EVP_PKEY, EVP_PKEY_RSA, EVP_PKEY_RSA_PSS,
12};
13#[cfg(feature = "ring-io")]
14use crate::aws_lc::{RSA_get0_e, RSA_get0_n};
15use crate::encoding::{AsDer, Pkcs8V1Der, PublicKeyX509Der};
16use crate::error::{KeyRejected, Unspecified};
17#[cfg(feature = "ring-io")]
18use crate::io;
19#[cfg(feature = "ring-io")]
20use crate::ptr::ConstPointer;
21use crate::ptr::{DetachableLcPtr, LcPtr};
22use crate::rsa::PublicEncryptingKey;
23use crate::sealed::Sealed;
24use crate::{hex, rand};
25#[cfg(feature = "fips")]
26use aws_lc::RSA_check_fips;
27use core::fmt::{self, Debug, Formatter};
28use core::ptr::null_mut;
29
30// TODO: Uncomment when MSRV >= 1.64
31// use core::ffi::c_int;
32use std::os::raw::c_int;
33
34use crate::pkcs8::Version;
35use crate::rsa::encoding::{rfc5280, rfc8017};
36use crate::rsa::signature::configure_rsa_pkcs1_pss_padding;
37#[cfg(feature = "ring-io")]
38use untrusted::Input;
39use zeroize::Zeroize;
40
41/// RSA key-size.
42#[allow(clippy::module_name_repetitions)]
43#[non_exhaustive]
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
45pub enum KeySize {
46    /// 2048-bit key
47    Rsa2048,
48
49    /// 3072-bit key
50    Rsa3072,
51
52    /// 4096-bit key
53    Rsa4096,
54
55    /// 8192-bit key
56    Rsa8192,
57}
58
59#[allow(clippy::len_without_is_empty)]
60impl KeySize {
61    /// Returns the size of the key in bytes.
62    #[inline]
63    #[must_use]
64    pub fn len(self) -> usize {
65        match self {
66            Self::Rsa2048 => 256,
67            Self::Rsa3072 => 384,
68            Self::Rsa4096 => 512,
69            Self::Rsa8192 => 1024,
70        }
71    }
72
73    /// Returns the key size in bits.
74    #[inline]
75    pub(super) fn bits(self) -> i32 {
76        match self {
77            Self::Rsa2048 => 2048,
78            Self::Rsa3072 => 3072,
79            Self::Rsa4096 => 4096,
80            Self::Rsa8192 => 8192,
81        }
82    }
83}
84
85/// An RSA key pair, used for signing.
86#[allow(clippy::module_name_repetitions)]
87pub struct KeyPair {
88    // https://github.com/aws/aws-lc/blob/ebaa07a207fee02bd68fe8d65f6b624afbf29394/include/openssl/evp.h#L295
89    // An |EVP_PKEY| object represents a public or private RSA key. A given object may be
90    // used concurrently on multiple threads by non-mutating functions, provided no
91    // other thread is concurrently calling a mutating function. Unless otherwise
92    // documented, functions which take a |const| pointer are non-mutating and
93    // functions which take a non-|const| pointer are mutating.
94    pub(super) evp_pkey: LcPtr<EVP_PKEY>,
95    pub(super) serialized_public_key: PublicKey,
96}
97
98impl Sealed for KeyPair {}
99unsafe impl Send for KeyPair {}
100unsafe impl Sync for KeyPair {}
101
102impl KeyPair {
103    fn new(evp_pkey: LcPtr<EVP_PKEY>) -> Result<Self, KeyRejected> {
104        KeyPair::validate_private_key(&evp_pkey)?;
105        let serialized_public_key = PublicKey::new(&evp_pkey)?;
106        Ok(KeyPair {
107            evp_pkey,
108            serialized_public_key,
109        })
110    }
111
112    /// Generate a RSA `KeyPair` of the specified key-strength.
113    ///
114    /// Supports the following key sizes:
115    /// * `KeySize::Rsa2048`
116    /// * `KeySize::Rsa3072`
117    /// * `KeySize::Rsa4096`
118    /// * `KeySize::Rsa8192`
119    ///
120    /// # Errors
121    /// * `Unspecified`: Any key generation failure.
122    pub fn generate(size: KeySize) -> Result<Self, Unspecified> {
123        let private_key = generate_rsa_key(size.bits())?;
124        Ok(Self::new(private_key)?)
125    }
126
127    /// Generate a RSA `KeyPair` of the specified key-strength.
128    ///
129    /// ## Deprecated
130    /// This is equivalent to `KeyPair::generate`.
131    ///
132    /// # Errors
133    /// * `Unspecified`: Any key generation failure.
134    #[cfg(feature = "fips")]
135    #[deprecated]
136    pub fn generate_fips(size: KeySize) -> Result<Self, Unspecified> {
137        Self::generate(size)
138    }
139
140    /// Parses an unencrypted PKCS#8 DER encoded RSA private key.
141    ///
142    /// Keys can be generated using [`KeyPair::generate`].
143    ///
144    /// # *ring*-compatibility
145    ///
146    /// *aws-lc-rs* does not impose the same limitations that *ring* does for
147    /// RSA keys. Thus signatures may be generated by keys that are not accepted
148    /// by *ring*. In particular:
149    /// * RSA private keys ranging between 2048-bit keys and 8192-bit keys are supported.
150    /// * The public exponent does not have a required minimum size.
151    ///
152    /// # Errors
153    /// `error::KeyRejected` if bytes do not encode an RSA private key or if the key is otherwise
154    /// not acceptable.
155    pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
156        let key = LcPtr::<EVP_PKEY>::parse_rfc5208_private_key(pkcs8, EVP_PKEY_RSA)?;
157        Self::new(key)
158    }
159
160    /// Parses a DER-encoded `RSAPrivateKey` structure (RFC 8017).
161    ///
162    /// # Errors
163    /// `error:KeyRejected` on error.
164    pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
165        let key = encoding::rfc8017::decode_private_key_der(input)?;
166        Self::new(key)
167    }
168
169    /// Returns a boolean indicator if this RSA key is an approved FIPS 140-3 key.
170    #[cfg(feature = "fips")]
171    #[must_use]
172    pub fn is_valid_fips_key(&self) -> bool {
173        is_valid_fips_key(&self.evp_pkey)
174    }
175
176    fn validate_private_key(key: &LcPtr<EVP_PKEY>) -> Result<(), KeyRejected> {
177        if !is_rsa_key(key) {
178            return Err(KeyRejected::unspecified());
179        }
180        match key.key_size_bits() {
181            2048..=8192 => Ok(()),
182            _ => Err(KeyRejected::unspecified()),
183        }
184    }
185
186    /// Sign `msg`. `msg` is digested using the digest algorithm from
187    /// `padding_alg` and the digest is then padded using the padding algorithm
188    /// from `padding_alg`. The signature it written into `signature`;
189    /// `signature`'s length must be exactly the length returned by
190    /// `public_modulus_len()`.
191    ///
192    /// Many other crypto libraries have signing functions that takes a
193    /// precomputed digest as input, instead of the message to digest. This
194    /// function does *not* take a precomputed digest; instead, `sign`
195    /// calculates the digest itself.
196    ///
197    /// # *ring* Compatibility
198    /// Our implementation ignores the `SecureRandom` parameter.
199    // # FIPS
200    // The following conditions must be met:
201    // * RSA Key Sizes: 2048, 3072, 4096
202    // * Digest Algorithms: SHA256, SHA384, SHA512
203    //
204    /// # Errors
205    /// `error::Unspecified` on error.
206    /// With "fips" feature enabled, errors if digest length is greater than `u32::MAX`.
207    pub fn sign(
208        &self,
209        padding_alg: &'static dyn RsaEncoding,
210        _rng: &dyn rand::SecureRandom,
211        msg: &[u8],
212        signature: &mut [u8],
213    ) -> Result<(), Unspecified> {
214        let encoding = padding_alg.encoding();
215        let padding_fn = if let RsaPadding::RSA_PKCS1_PSS_PADDING = encoding.padding() {
216            Some(configure_rsa_pkcs1_pss_padding)
217        } else {
218            None
219        };
220
221        let sig_bytes = self
222            .evp_pkey
223            .sign(msg, Some(encoding.digest_algorithm()), padding_fn)?;
224
225        signature.copy_from_slice(&sig_bytes);
226        Ok(())
227    }
228
229    /// Returns the length in bytes of the key pair's public modulus.
230    ///
231    /// A signature has the same length as the public modulus.
232    #[must_use]
233    pub fn public_modulus_len(&self) -> usize {
234        // This was already validated to be an RSA key so this can't fail
235        match self.evp_pkey.get_rsa() {
236            Ok(rsa) => {
237                // https://github.com/awslabs/aws-lc/blob/main/include/openssl/rsa.h#L99
238                unsafe { RSA_size(*rsa) as usize }
239            }
240            Err(_) => unreachable!(),
241        }
242    }
243}
244
245impl Debug for KeyPair {
246    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
247        f.write_str(&format!(
248            "RsaKeyPair {{ public_key: {:?} }}",
249            self.serialized_public_key
250        ))
251    }
252}
253
254impl crate::signature::KeyPair for KeyPair {
255    type PublicKey = PublicKey;
256
257    fn public_key(&self) -> &Self::PublicKey {
258        &self.serialized_public_key
259    }
260}
261
262impl AsDer<Pkcs8V1Der<'static>> for KeyPair {
263    fn as_der(&self) -> Result<Pkcs8V1Der<'static>, Unspecified> {
264        Ok(Pkcs8V1Der::new(
265            self.evp_pkey.marshal_rfc5208_private_key(Version::V1)?,
266        ))
267    }
268}
269
270/// A serialized RSA public key.
271#[derive(Clone)]
272#[allow(clippy::module_name_repetitions)]
273pub struct PublicKey {
274    key: Box<[u8]>,
275    #[cfg(feature = "ring-io")]
276    modulus: Box<[u8]>,
277    #[cfg(feature = "ring-io")]
278    exponent: Box<[u8]>,
279}
280
281impl Drop for PublicKey {
282    fn drop(&mut self) {
283        self.key.zeroize();
284        #[cfg(feature = "ring-io")]
285        self.modulus.zeroize();
286        #[cfg(feature = "ring-io")]
287        self.exponent.zeroize();
288    }
289}
290
291impl PublicKey {
292    pub(super) fn new(evp_pkey: &LcPtr<EVP_PKEY>) -> Result<Self, KeyRejected> {
293        let key = encoding::rfc8017::encode_public_key_der(evp_pkey)?;
294        #[cfg(feature = "ring-io")]
295        {
296            let pubkey = evp_pkey.get_rsa()?;
297            let modulus = ConstPointer::new(unsafe { RSA_get0_n(*pubkey) })?;
298            let modulus = modulus.to_be_bytes().into_boxed_slice();
299            let exponent = ConstPointer::new(unsafe { RSA_get0_e(*pubkey) })?;
300            let exponent = exponent.to_be_bytes().into_boxed_slice();
301            Ok(PublicKey {
302                key,
303                modulus,
304                exponent,
305            })
306        }
307
308        #[cfg(not(feature = "ring-io"))]
309        Ok(PublicKey { key })
310    }
311
312    /// Parses an RSA public key from either RFC8017 or RFC5280
313    /// # Errors
314    /// `KeyRejected` if the encoding is not for a valid RSA key.
315    pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
316        // These both invoke `RSA_check_key`:
317        // https://github.com/aws/aws-lc/blob/4368aaa6975ba41bd76d3bb12fac54c4680247fb/crypto/rsa_extra/rsa_asn1.c#L105-L109
318        PublicKey::new(
319            &rfc8017::decode_public_key_der(input).or(rfc5280::decode_public_key_der(input))?,
320        )
321    }
322}
323
324impl Debug for PublicKey {
325    fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
326        f.write_str(&format!(
327            "RsaPublicKey(\"{}\")",
328            hex::encode(self.key.as_ref())
329        ))
330    }
331}
332
333impl AsRef<[u8]> for PublicKey {
334    /// DER encode a RSA public key to (RFC 8017) `RSAPublicKey` structure.
335    fn as_ref(&self) -> &[u8] {
336        self.key.as_ref()
337    }
338}
339
340impl AsDer<PublicKeyX509Der<'static>> for PublicKey {
341    fn as_der(&self) -> Result<PublicKeyX509Der<'static>, Unspecified> {
342        // TODO: refactor
343        let evp_pkey = rfc8017::decode_public_key_der(self.as_ref())?;
344        rfc5280::encode_public_key_der(&evp_pkey)
345    }
346}
347
348#[cfg(feature = "ring-io")]
349impl PublicKey {
350    /// The public modulus (n).
351    #[must_use]
352    pub fn modulus(&self) -> io::Positive<'_> {
353        io::Positive::new_non_empty_without_leading_zeros(Input::from(self.modulus.as_ref()))
354    }
355
356    /// The public exponent (e).
357    #[must_use]
358    pub fn exponent(&self) -> io::Positive<'_> {
359        io::Positive::new_non_empty_without_leading_zeros(Input::from(self.exponent.as_ref()))
360    }
361
362    /// Returns the length in bytes of the public modulus.
363    #[must_use]
364    pub fn modulus_len(&self) -> usize {
365        self.modulus.len()
366    }
367}
368
369/// Low-level API for RSA public keys.
370///
371/// When the public key is in DER-encoded PKCS#1 ASN.1 format, it is
372/// recommended to use `aws_lc_rs::signature::verify()` with
373/// `aws_lc_rs::signature::RSA_PKCS1_*`, because `aws_lc_rs::signature::verify()`
374/// will handle the parsing in that case. Otherwise, this function can be used
375/// to pass in the raw bytes for the public key components as
376/// `untrusted::Input` arguments.
377#[allow(clippy::module_name_repetitions)]
378#[derive(Clone)]
379pub struct PublicKeyComponents<B>
380where
381    B: AsRef<[u8]> + Debug,
382{
383    /// The public modulus, encoded in big-endian bytes without leading zeros.
384    pub n: B,
385    /// The public exponent, encoded in big-endian bytes without leading zeros.
386    pub e: B,
387}
388
389impl<B: AsRef<[u8]> + Debug> Debug for PublicKeyComponents<B> {
390    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
391        f.debug_struct("RsaPublicKeyComponents")
392            .field("n", &self.n)
393            .field("e", &self.e)
394            .finish()
395    }
396}
397
398impl<B: Copy + AsRef<[u8]> + Debug> Copy for PublicKeyComponents<B> {}
399
400impl<B> PublicKeyComponents<B>
401where
402    B: AsRef<[u8]> + Debug,
403{
404    #[inline]
405    fn build_rsa(&self) -> Result<LcPtr<EVP_PKEY>, ()> {
406        let n_bytes = self.n.as_ref();
407        if n_bytes.is_empty() || n_bytes[0] == 0u8 {
408            return Err(());
409        }
410        let n_bn = DetachableLcPtr::try_from(n_bytes)?;
411
412        let e_bytes = self.e.as_ref();
413        if e_bytes.is_empty() || e_bytes[0] == 0u8 {
414            return Err(());
415        }
416        let e_bn = DetachableLcPtr::try_from(e_bytes)?;
417
418        let rsa = DetachableLcPtr::new(unsafe { RSA_new() })?;
419        if 1 != unsafe { RSA_set0_key(*rsa, *n_bn, *e_bn, null_mut()) } {
420            return Err(());
421        }
422        n_bn.detach();
423        e_bn.detach();
424
425        let mut pkey = LcPtr::new(unsafe { EVP_PKEY_new() })?;
426        if 1 != unsafe { EVP_PKEY_assign_RSA(*pkey.as_mut(), *rsa) } {
427            return Err(());
428        }
429        rsa.detach();
430
431        Ok(pkey)
432    }
433
434    /// Verifies that `signature` is a valid signature of `message` using `self`
435    /// as the public key. `params` determine what algorithm parameters
436    /// (padding, digest algorithm, key length range, etc.) are used in the
437    /// verification.
438    ///
439    /// # Errors
440    /// `error::Unspecified` if `message` was not verified.
441    pub fn verify(
442        &self,
443        params: &RsaParameters,
444        message: &[u8],
445        signature: &[u8],
446    ) -> Result<(), Unspecified> {
447        let rsa = self.build_rsa()?;
448        super::signature::verify_rsa_signature(
449            params.digest_algorithm(),
450            params.padding(),
451            &rsa,
452            message,
453            signature,
454            params.bit_size_range(),
455        )
456    }
457}
458
459#[cfg(feature = "ring-io")]
460impl From<&PublicKey> for PublicKeyComponents<Vec<u8>> {
461    fn from(public_key: &PublicKey) -> Self {
462        PublicKeyComponents {
463            n: public_key.modulus.to_vec(),
464            e: public_key.exponent.to_vec(),
465        }
466    }
467}
468
469impl<B> TryInto<PublicEncryptingKey> for PublicKeyComponents<B>
470where
471    B: AsRef<[u8]> + Debug,
472{
473    type Error = Unspecified;
474
475    /// Try to build a `PublicEncryptingKey` from the public key components.
476    ///
477    /// # Errors
478    /// `error::Unspecified` if the key failed to verify.
479    fn try_into(self) -> Result<PublicEncryptingKey, Self::Error> {
480        let rsa = self.build_rsa()?;
481        PublicEncryptingKey::new(rsa)
482    }
483}
484
485pub(super) fn generate_rsa_key(size: c_int) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
486    let params_fn = |ctx| {
487        if 1 == unsafe { EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, size) } {
488            Ok(())
489        } else {
490            Err(())
491        }
492    };
493
494    LcPtr::<EVP_PKEY>::generate(EVP_PKEY_RSA, Some(params_fn))
495}
496
497#[cfg(feature = "fips")]
498#[must_use]
499pub(super) fn is_valid_fips_key(key: &LcPtr<EVP_PKEY>) -> bool {
500    // This should always be an RSA key and must-never panic.
501    let rsa_key = key.get_rsa().expect("RSA EVP_PKEY");
502
503    1 == unsafe { RSA_check_fips(*rsa_key as *mut RSA) }
504}
505
506pub(super) fn is_rsa_key(key: &LcPtr<EVP_PKEY>) -> bool {
507    let id = key.id();
508    id == EVP_PKEY_RSA || id == EVP_PKEY_RSA_PSS
509}