use core::{
cmp::Ordering,
fmt::{self, Debug, Formatter},
mem::MaybeUninit,
ptr::null_mut,
};
use crate::{
encoding::{AsDer, Pkcs8V1Der},
fips::indicator_check,
};
#[cfg(feature = "fips")]
use aws_lc::RSA_check_fips;
use aws_lc::{
EVP_DigestSignInit, EVP_PKEY_assign_RSA, EVP_PKEY_new, RSA_generate_key_ex,
RSA_generate_key_fips, RSA_get0_e, RSA_get0_n, RSA_get0_p, RSA_get0_q, RSA_new,
RSA_parse_private_key, RSA_parse_public_key, RSA_public_key_to_bytes, RSA_set0_key, RSA_size,
BIGNUM, EVP_PKEY, EVP_PKEY_CTX, RSA,
};
use mirai_annotations::verify_unreachable;
#[cfg(feature = "ring-io")]
use untrusted::Input;
use zeroize::Zeroize;
use super::{
encoding,
signature::{compute_rsa_signature, RsaEncoding, RsaPadding},
RsaParameters,
};
#[cfg(feature = "ring-io")]
use crate::io;
use crate::{
cbs, digest,
error::{KeyRejected, Unspecified},
hex,
ptr::{ConstPointer, DetachableLcPtr, LcPtr},
rand,
sealed::Sealed,
};
#[allow(clippy::module_name_repetitions)]
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum KeySize {
Rsa2048,
Rsa3072,
Rsa4096,
Rsa8192,
}
#[allow(clippy::len_without_is_empty)]
impl KeySize {
#[inline]
#[must_use]
pub fn len(self) -> usize {
match self {
Self::Rsa2048 => 256,
Self::Rsa3072 => 384,
Self::Rsa4096 => 512,
Self::Rsa8192 => 1024,
}
}
#[inline]
fn bit_len(self) -> i32 {
match self {
Self::Rsa2048 => 2048,
Self::Rsa3072 => 3072,
Self::Rsa4096 => 4096,
Self::Rsa8192 => 8192,
}
}
}
#[allow(clippy::module_name_repetitions)]
pub struct KeyPair {
evp_pkey: LcPtr<EVP_PKEY>,
serialized_public_key: PublicKey,
}
impl Sealed for KeyPair {}
unsafe impl Send for KeyPair {}
unsafe impl Sync for KeyPair {}
impl KeyPair {
fn new(evp_pkey: LcPtr<EVP_PKEY>) -> Result<Self, KeyRejected> {
unsafe {
let rsa_key = evp_pkey.get_rsa()?;
let serialized_public_key = PublicKey::new(&rsa_key.as_const())?;
Ok(KeyPair {
evp_pkey,
serialized_public_key,
})
}
}
pub fn generate(size: KeySize) -> Result<Self, Unspecified> {
let private_key = generate_rsa_key(size.bit_len(), false)?;
Self::new(private_key).map_err(|_| Unspecified)
}
#[cfg(feature = "fips")]
pub fn generate_fips(size: KeySize) -> Result<Self, Unspecified> {
let private_key = generate_rsa_key(size.bit_len(), true)?;
Self::new(private_key).map_err(|_| Unspecified)
}
pub fn from_pkcs8(pkcs8: &[u8]) -> Result<Self, KeyRejected> {
unsafe {
let evp_pkey = encoding::pkcs8::decode_der(pkcs8)?;
Self::validate_rsa_pkey(&evp_pkey)?;
Self::new(evp_pkey)
}
}
pub fn from_der(input: &[u8]) -> Result<Self, KeyRejected> {
unsafe {
let pkey = build_private_RSA_PKEY(input)?;
Self::validate_rsa_pkey(&pkey)?;
Self::new(pkey)
}
}
const MIN_RSA_PRIME_BITS: u32 = 1024;
const MAX_RSA_PRIME_BITS: u32 = 4096;
unsafe fn validate_rsa_pkey(rsa: &LcPtr<EVP_PKEY>) -> Result<(), KeyRejected> {
let rsa = rsa.get_rsa()?.as_const();
let p = ConstPointer::new(RSA_get0_p(*rsa))?;
let q = ConstPointer::new(RSA_get0_q(*rsa))?;
let p_bits = p.num_bits();
let q_bits = q.num_bits();
if p_bits != q_bits {
return Err(KeyRejected::inconsistent_components());
}
if p_bits < Self::MIN_RSA_PRIME_BITS {
return Err(KeyRejected::too_small());
}
if p_bits > Self::MAX_RSA_PRIME_BITS {
return Err(KeyRejected::too_large());
}
if p_bits % 512 != 0 {
return Err(KeyRejected::private_modulus_len_not_multiple_of_512_bits());
}
let e = ConstPointer::new(RSA_get0_e(*rsa))?;
let min_exponent = DetachableLcPtr::try_from(65537)?;
match e.compare(&min_exponent.as_const()) {
Ordering::Less => Err(KeyRejected::too_small()),
Ordering::Equal | Ordering::Greater => Ok(()),
}?;
#[cfg(feature = "fips")]
if 1 != RSA_check_fips(*rsa as *mut RSA) {
return Err(KeyRejected::inconsistent_components());
}
Ok(())
}
pub fn sign(
&self,
padding_alg: &'static dyn RsaEncoding,
_rng: &dyn rand::SecureRandom,
msg: &[u8],
signature: &mut [u8],
) -> Result<(), Unspecified> {
let encoding = padding_alg.encoding();
let mut md_ctx = digest::digest_ctx::DigestContext::new_uninit();
let mut pctx = null_mut::<EVP_PKEY_CTX>();
let digest = digest::match_digest_type(&encoding.digest_algorithm().id);
if 1 != unsafe {
EVP_DigestSignInit(
md_ctx.as_mut_ptr(),
&mut pctx,
*digest,
null_mut(),
*self.evp_pkey,
)
} {
return Err(Unspecified);
}
if let RsaPadding::RSA_PKCS1_PSS_PADDING = encoding.padding() {
let pctx = DetachableLcPtr::new(pctx)?.detach();
super::signature::configure_rsa_pkcs1_pss_padding(pctx)?;
}
let max_len = super::signature::get_signature_length(&mut md_ctx)?;
debug_assert!(signature.len() >= max_len);
let computed_signature = compute_rsa_signature(&mut md_ctx, msg, signature)?;
debug_assert!(computed_signature.len() >= signature.len());
Ok(())
}
#[must_use]
pub fn public_modulus_len(&self) -> usize {
match self.evp_pkey.get_rsa() {
Ok(rsa) => {
unsafe { (RSA_size(*rsa)) as usize }
}
Err(_) => verify_unreachable!(),
}
}
}
impl Debug for KeyPair {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&format!(
"RsaKeyPair {{ public_key: {:?} }}",
self.serialized_public_key
))
}
}
impl crate::signature::KeyPair for KeyPair {
type PublicKey = PublicKey;
fn public_key(&self) -> &Self::PublicKey {
&self.serialized_public_key
}
}
impl AsDer<Pkcs8V1Der<'static>> for KeyPair {
fn as_der(&self) -> Result<Pkcs8V1Der<'static>, Unspecified> {
Ok(Pkcs8V1Der::new(encoding::pkcs8::encode_v1_der(
&self.evp_pkey,
)?))
}
}
#[inline]
#[allow(non_snake_case)]
unsafe fn build_private_RSA_PKEY(private_key: &[u8]) -> Result<LcPtr<EVP_PKEY>, KeyRejected> {
let mut cbs = cbs::build_CBS(private_key);
let rsa = DetachableLcPtr::new(RSA_parse_private_key(&mut cbs))?;
let pkey = LcPtr::new(EVP_PKEY_new())?;
if 1 != EVP_PKEY_assign_RSA(*pkey, *rsa) {
return Err(KeyRejected::unexpected_error());
}
rsa.detach();
Ok(pkey)
}
#[inline]
#[allow(non_snake_case)]
pub(super) unsafe fn build_public_RSA_PKEY(
public_key: &[u8],
) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
let mut cbs = cbs::build_CBS(public_key);
let rsa = DetachableLcPtr::new(RSA_parse_public_key(&mut cbs))?;
let pkey = LcPtr::new(EVP_PKEY_new())?;
if 1 != EVP_PKEY_assign_RSA(*pkey, *rsa) {
return Err(Unspecified);
}
rsa.detach();
Ok(pkey)
}
#[derive(Clone)]
#[allow(clippy::module_name_repetitions)]
pub struct PublicKey {
key: Box<[u8]>,
#[cfg(feature = "ring-io")]
modulus: Box<[u8]>,
#[cfg(feature = "ring-io")]
exponent: Box<[u8]>,
}
impl Drop for PublicKey {
fn drop(&mut self) {
self.key.zeroize();
#[cfg(feature = "ring-io")]
self.modulus.zeroize();
#[cfg(feature = "ring-io")]
self.exponent.zeroize();
}
}
impl PublicKey {
pub(super) unsafe fn new(pubkey: &ConstPointer<RSA>) -> Result<Self, ()> {
let key = serialize_RSA_pubkey(pubkey)?;
#[cfg(feature = "ring-io")]
{
let modulus = ConstPointer::new(RSA_get0_n(**pubkey))?;
let modulus = modulus.to_be_bytes().into_boxed_slice();
let exponent = ConstPointer::new(RSA_get0_e(**pubkey))?;
let exponent = exponent.to_be_bytes().into_boxed_slice();
Ok(PublicKey {
key,
modulus,
exponent,
})
}
#[cfg(not(feature = "ring-io"))]
Ok(PublicKey { key })
}
}
impl Debug for PublicKey {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), fmt::Error> {
f.write_str(&format!(
"RsaPublicKey(\"{}\")",
hex::encode(self.key.as_ref())
))
}
}
impl AsRef<[u8]> for PublicKey {
fn as_ref(&self) -> &[u8] {
self.key.as_ref()
}
}
#[cfg(feature = "ring-io")]
impl PublicKey {
#[must_use]
pub fn modulus(&self) -> io::Positive<'_> {
io::Positive::new_non_empty_without_leading_zeros(Input::from(self.modulus.as_ref()))
}
#[must_use]
pub fn exponent(&self) -> io::Positive<'_> {
io::Positive::new_non_empty_without_leading_zeros(Input::from(self.exponent.as_ref()))
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Clone)]
pub struct PublicKeyComponents<B>
where
B: AsRef<[u8]> + Debug,
{
pub n: B,
pub e: B,
}
impl<B: AsRef<[u8]> + Debug> Debug for PublicKeyComponents<B> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("RsaPublicKeyComponents")
.field("n", &self.n)
.field("e", &self.e)
.finish()
}
}
impl<B: Copy + AsRef<[u8]> + Debug> Copy for PublicKeyComponents<B> {}
impl<B> PublicKeyComponents<B>
where
B: AsRef<[u8]> + Debug,
{
#[allow(non_snake_case)]
#[inline]
unsafe fn build_RSA(&self) -> Result<LcPtr<EVP_PKEY>, ()> {
let n_bytes = self.n.as_ref();
if n_bytes.is_empty() || n_bytes[0] == 0u8 {
return Err(());
}
let n_bn = DetachableLcPtr::try_from(n_bytes)?;
let e_bytes = self.e.as_ref();
if e_bytes.is_empty() || e_bytes[0] == 0u8 {
return Err(());
}
let e_bn = DetachableLcPtr::try_from(e_bytes)?;
let rsa = DetachableLcPtr::new(RSA_new())?;
if 1 != RSA_set0_key(*rsa, *n_bn, *e_bn, null_mut()) {
return Err(());
}
n_bn.detach();
e_bn.detach();
let pkey = LcPtr::new(EVP_PKEY_new())?;
if 1 != EVP_PKEY_assign_RSA(*pkey, *rsa) {
return Err(());
}
rsa.detach();
Ok(pkey)
}
pub fn verify(
&self,
params: &RsaParameters,
message: &[u8],
signature: &[u8],
) -> Result<(), Unspecified> {
unsafe {
let rsa = self.build_RSA()?;
super::signature::verify_RSA(
params.digest_algorithm(),
params.padding(),
&rsa,
message,
signature,
params.bit_size_range(),
)
}
}
}
#[allow(non_snake_case)]
unsafe fn serialize_RSA_pubkey(pubkey: &ConstPointer<RSA>) -> Result<Box<[u8]>, ()> {
let mut pubkey_bytes = null_mut::<u8>();
let mut outlen = MaybeUninit::<usize>::uninit();
if 1 != RSA_public_key_to_bytes(&mut pubkey_bytes, outlen.as_mut_ptr(), **pubkey) {
return Err(());
}
let pubkey_bytes = LcPtr::new(pubkey_bytes)?;
let outlen = outlen.assume_init();
let pubkey_slice = pubkey_bytes.as_slice(outlen);
let pubkey_vec = Vec::from(pubkey_slice);
Ok(pubkey_vec.into_boxed_slice())
}
pub(super) fn generate_rsa_key(
size: std::os::raw::c_int,
fips: bool,
) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
const RSA_F4: u64 = 65537;
let rsa = DetachableLcPtr::new(unsafe { RSA_new() })?;
if 1 != if fips {
indicator_check!(unsafe { RSA_generate_key_fips(*rsa, size, null_mut()) })
} else {
let e: LcPtr<BIGNUM> = RSA_F4.try_into()?;
unsafe { RSA_generate_key_ex(*rsa, size, *e, null_mut()) }
} {
return Err(Unspecified);
}
let evp_pkey = LcPtr::new(unsafe { EVP_PKEY_new() })?;
if 1 != unsafe { EVP_PKEY_assign_RSA(*evp_pkey, *rsa) } {
return Err(Unspecified);
};
rsa.detach();
Ok(evp_pkey)
}