Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for borrowed RemoteKeyPair #212

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions rcgen/examples/sign-leaf-with-ca.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn main() {
println!("ca certificate: {ca_cert_pem}",);
}

fn new_ca() -> CertifiedKey {
fn new_ca<'a>() -> CertifiedKey<'a> {
let mut params = CertificateParams::new(Vec::default());
let (yesterday, tomorrow) = validity_period();
params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained);
Expand All @@ -35,7 +35,7 @@ fn new_ca() -> CertifiedKey {
Certificate::generate_self_signed(params).unwrap()
}

fn new_end_entity() -> Certificate {
fn new_end_entity<'a>() -> Certificate<'a> {
let name = "entity.other.host";
let mut params = CertificateParams::new(vec![name.into()]);
let (yesterday, tomorrow) = validity_period();
Expand Down
6 changes: 3 additions & 3 deletions rcgen/src/csr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ impl PublicKeyData for PublicKey {
}

/// Parameters for a certificate signing request
pub struct CertificateSigningRequestParams {
pub struct CertificateSigningRequestParams<'a> {
/// Parameters for the certificate to be signed.
pub params: CertificateParams,
pub params: CertificateParams<'a>,
/// Public key to include in the certificate signing request.
pub public_key: PublicKey,
}

impl CertificateSigningRequestParams {
impl CertificateSigningRequestParams<'_> {
/// Parse a certificate signing request from the ASCII PEM format
///
/// See [`from_der`](Self::from_der) for more details.
Expand Down
121 changes: 80 additions & 41 deletions rcgen/src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,18 @@ use crate::{Error, SignatureAlgorithm};

/// A key pair variant
#[allow(clippy::large_enum_variant)]
pub(crate) enum KeyPairKind {
pub(crate) enum KeyPairKind<'a> {
/// A Ecdsa key pair
Ec(EcdsaKeyPair),
/// A Ed25519 key pair
Ed(Ed25519KeyPair),
/// A RSA key pair
Rsa(RsaKeyPair, &'static dyn RsaEncoding),
/// A remote key pair
Remote(Box<dyn RemoteKeyPair + Send + Sync>),
Remote(&'a (dyn RemoteKeyPair + Send + Sync)),
}

impl fmt::Debug for KeyPairKind {
impl fmt::Debug for KeyPairKind<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Ec(key_pair) => write!(f, "{:?}", key_pair),
Expand All @@ -49,13 +49,13 @@ impl fmt::Debug for KeyPairKind {
/// for how to generate RSA keys in the wanted format
/// and conversion between the formats.
#[derive(Debug)]
pub struct KeyPair {
pub(crate) kind: KeyPairKind,
pub struct KeyPair<'a> {
pub(crate) kind: KeyPairKind<'a>,
pub(crate) alg: &'static SignatureAlgorithm,
pub(crate) serialized_der: Vec<u8>,
pub(crate) serialized_der: Option<Vec<u8>>,
}

impl KeyPair {
impl<'a> KeyPair<'a> {
/// Parses the key pair from the DER format
///
/// Equivalent to using the [`TryFrom`] implementation.
Expand All @@ -77,11 +77,11 @@ impl KeyPair {
}

/// Obtains the key pair from a raw public key and a remote private key
pub fn from_remote(key_pair: Box<dyn RemoteKeyPair + Send + Sync>) -> Result<Self, Error> {
pub fn from_remote(key_pair: &'a (dyn RemoteKeyPair + Send + Sync)) -> Result<Self, Error> {
Ok(Self {
alg: key_pair.algorithm(),
kind: KeyPairKind::Remote(key_pair),
serialized_der: Vec::new(),
serialized_der: None,
})
}

Expand Down Expand Up @@ -148,13 +148,13 @@ impl KeyPair {
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8_vec,
serialized_der: Some(pkcs8_vec),
})
}

pub(crate) fn from_raw(
pkcs8: &[u8],
) -> Result<(KeyPairKind, &'static SignatureAlgorithm), Error> {
) -> Result<(KeyPairKind<'a>, &'static SignatureAlgorithm), Error> {
let rng = SystemRandom::new();
let (kind, alg) = if let Ok(edkp) = Ed25519KeyPair::from_pkcs8_maybe_unchecked(pkcs8) {
(KeyPairKind::Ed(edkp), &PKCS_ED25519)
Expand Down Expand Up @@ -190,7 +190,7 @@ impl KeyPair {
Ok(KeyPair {
kind: KeyPairKind::Ec(key_pair),
alg,
serialized_der: key_pair_serialized,
serialized_der: Some(key_pair_serialized),
})
},
SignAlgo::EdDsa(_sign_alg) => {
Expand All @@ -201,7 +201,7 @@ impl KeyPair {
Ok(KeyPair {
kind: KeyPairKind::Ed(key_pair),
alg,
serialized_der: key_pair_serialized,
serialized_der: Some(key_pair_serialized),
})
},
// Ring doesn't have RSA key generation yet:
Expand All @@ -219,7 +219,7 @@ impl KeyPair {
/// If `None` is provided for `existing_key_pair` a new key pair compatible with `sig_alg`
/// is generated from scratch.
pub(crate) fn validate_or_generate(
existing_key_pair: &mut Option<KeyPair>,
existing_key_pair: &mut Option<KeyPair<'a>>,
sig_alg: &'static SignatureAlgorithm,
) -> Result<Self, Error> {
match existing_key_pair.take() {
Expand Down Expand Up @@ -251,32 +251,39 @@ impl KeyPair {
std::iter::once(self.alg)
}

pub(crate) fn sign(&self, msg: &[u8], writer: DERWriter) -> Result<(), Error> {
match &self.kind {
fn sign_raw(&self, msg: &[u8]) -> Result<Vec<u8>, Error> {
let signature = match &self.kind {
KeyPairKind::Ec(kp) => {
let system_random = SystemRandom::new();
let signature = kp.sign(&system_random, msg)._err()?;
let sig = &signature.as_ref();
writer.write_bitvec_bytes(&sig, &sig.len() * 8);

signature.as_ref().to_vec()
},
KeyPairKind::Ed(kp) => {
let signature = kp.sign(msg);
let sig = &signature.as_ref();
writer.write_bitvec_bytes(&sig, &sig.len() * 8);

signature.as_ref().to_vec()
},
KeyPairKind::Rsa(kp, padding_alg) => {
let system_random = SystemRandom::new();
let mut signature = vec![0; rsa_key_pair_public_modulus_len(kp)];
kp.sign(*padding_alg, &system_random, msg, &mut signature)
._err()?;
let sig = &signature.as_ref();
writer.write_bitvec_bytes(&sig, &sig.len() * 8);

signature
},
KeyPairKind::Remote(kp) => {
let signature = kp.sign(msg)?;
writer.write_bitvec_bytes(&signature, &signature.len() * 8);

signature
},
}
};
Ok(signature)
}

pub(crate) fn sign(&self, msg: &[u8], writer: DERWriter) -> Result<(), Error> {
let sig = self.sign_raw(msg)?;
writer.write_bitvec_bytes(&sig, &sig.len() * 8);
Ok(())
}

Expand All @@ -303,29 +310,27 @@ impl KeyPair {
///
/// Panics if called on a remote key pair.
pub fn serialize_der(&self) -> Vec<u8> {
if let KeyPairKind::Remote(_) = self.kind {
panic!("Serializing a remote key pair is not supported")
match &self.serialized_der {
Some(serialized_der) => serialized_der.clone(),
None => panic!("Serializing a remote key pair is not supported"),
}

self.serialized_der.clone()
}

/// Returns a reference to the serialized key pair (including the private key)
/// in PKCS#8 format in DER
///
/// Panics if called on a remote key pair.
pub fn serialized_der(&self) -> &[u8] {
if let KeyPairKind::Remote(_) = self.kind {
panic!("Serializing a remote key pair is not supported")
match &self.serialized_der {
Some(serialized_der) => serialized_der,
None => panic!("Serializing a remote key pair is not supported"),
}

&self.serialized_der
}

/// Access the remote key pair if it is a remote one
pub fn as_remote(&self) -> Option<&(dyn RemoteKeyPair + Send + Sync)> {
if let KeyPairKind::Remote(remote) = &self.kind {
Some(remote.as_ref())
if let KeyPairKind::Remote(remote) = self.kind {
Some(remote)
} else {
None
}
Expand All @@ -340,33 +345,33 @@ impl KeyPair {
}
}

impl TryFrom<&[u8]> for KeyPair {
impl<'a> TryFrom<&[u8]> for KeyPair<'a> {
type Error = Error;

fn try_from(pkcs8: &[u8]) -> Result<KeyPair, Error> {
fn try_from(pkcs8: &[u8]) -> Result<KeyPair<'a>, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8)?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8.to_vec(),
serialized_der: pkcs8.to_vec().into(),
})
}
}

impl TryFrom<Vec<u8>> for KeyPair {
impl<'a> TryFrom<Vec<u8>> for KeyPair<'a> {
type Error = Error;

fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair, Error> {
fn try_from(pkcs8: Vec<u8>) -> Result<KeyPair<'a>, Error> {
let (kind, alg) = KeyPair::from_raw(pkcs8.as_slice())?;
Ok(KeyPair {
kind,
alg,
serialized_der: pkcs8,
serialized_der: Some(pkcs8),
})
}
}

impl PublicKeyData for KeyPair {
impl PublicKeyData for KeyPair<'_> {
fn alg(&self) -> &SignatureAlgorithm {
self.alg
}
Expand Down Expand Up @@ -395,6 +400,20 @@ pub trait RemoteKeyPair {
fn algorithm(&self) -> &'static SignatureAlgorithm;
}

impl RemoteKeyPair for KeyPair<'_> {
fn public_key(&self) -> &[u8] {
self.public_key_raw()
}

fn sign(&self, msg: &[u8]) -> Result<Vec<u8>, Error> {
self.sign_raw(msg)
}

fn algorithm(&self) -> &'static SignatureAlgorithm {
self.alg
}
}

impl<T> ExternalError<T> for Result<T, ring_error::KeyRejected> {
fn _err(self) -> Result<T, Error> {
self.map_err(|e| Error::RingKeyRejected(e.to_string()))
Expand Down Expand Up @@ -444,4 +463,24 @@ mod test {
let key_pair = KeyPair::from_der(&der).unwrap();
assert_eq!(key_pair.algorithm(), &PKCS_ECDSA_P256_SHA256);
}

#[test]
fn test_remote_key_pair() {
let key_pair = KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap();
assert_eq!(key_pair.algorithm(), &PKCS_ECDSA_P256_SHA256);
let remote_key1 = KeyPair::from_remote(&key_pair).unwrap();
let remote_key2 = KeyPair::from_remote(&key_pair).unwrap();
assert_eq!(remote_key1.algorithm(), key_pair.algorithm());
assert_eq!(remote_key2.algorithm(), key_pair.algorithm());
assert_eq!(remote_key1.public_key_der(), key_pair.public_key_der());
assert_eq!(remote_key2.public_key_der(), key_pair.public_key_der());
}

#[test]
#[should_panic = "Serializing a remote key pair is not supported"]
fn test_remote_key_pair_is_unserializable() {
let key_pair = KeyPair::generate(&PKCS_ECDSA_P256_SHA256).unwrap();
let remote_key = KeyPair::from_remote(&key_pair).unwrap();
remote_key.serialize_der();
}
}
Loading