Skip to content

[DRAFT] ParsedPublicKey for signature and agreement #853

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

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
239 changes: 137 additions & 102 deletions aws-lc-rs/src/agreement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,30 +55,29 @@ use crate::ec::encoding::sec1::{
marshal_sec1_private_key, marshal_sec1_public_point, marshal_sec1_public_point_into_buffer,
parse_sec1_private_bn,
};
use crate::ec::evp_key_generate;
#[cfg(feature = "fips")]
use crate::ec::validate_ec_evp_key;
#[cfg(not(feature = "fips"))]
use crate::ec::verify_evp_key_nid;
use crate::ec::{encoding, evp_key_generate};
use crate::error::{KeyRejected, Unspecified};
use crate::hex;
pub use ephemeral::{agree_ephemeral, EphemeralPrivateKey};

use crate::aws_lc::{
EVP_PKEY_derive, EVP_PKEY_derive_init, EVP_PKEY_derive_set_peer, EVP_PKEY_get0_EC_KEY,
NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, EVP_PKEY, EVP_PKEY_EC, EVP_PKEY_X25519,
NID_X25519,
i2d_ECPrivateKey, EVP_PKEY_get0_EC_KEY, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1,
EVP_PKEY, EVP_PKEY_EC, EVP_PKEY_X25519, NID_X25519,
};

use crate::buffer::Buffer;
use crate::ec;
use crate::ec::encoding::parse_ec_public_key;
use crate::ec::encoding::rfc5915::parse_rfc5915_private_key;
use crate::encoding::{
AsBigEndian, AsDer, Curve25519SeedBin, EcPrivateKeyBin, EcPrivateKeyRfc5915Der,
EcPublicKeyCompressedBin, EcPublicKeyUncompressedBin, Pkcs8V1Der, PublicKeyX509Der,
};
use crate::evp_pkey::No_EVP_PKEY_CTX_consumer;
use crate::fips::indicator_check;
use crate::pkcs8::Version;
use crate::ptr::LcPtr;
use core::fmt;
Expand Down Expand Up @@ -455,7 +454,7 @@ impl AsDer<EcPrivateKeyRfc5915Der<'static>> for PrivateKey {
|evp_pkey| EVP_PKEY_get0_EC_KEY(*evp_pkey.as_const())
})?
};
let length = usize::try_from(unsafe { aws_lc::i2d_ECPrivateKey(*ec_key, &mut outp) })
let length = usize::try_from(unsafe { i2d_ECPrivateKey(*ec_key, &mut outp) })
.map_err(|_| Unspecified)?;
let mut outp = LcPtr::new(outp)?;
Ok(EcPrivateKeyRfc5915Der::take_from_slice(unsafe {
Expand Down Expand Up @@ -665,6 +664,118 @@ impl<B: AsRef<[u8]>> UnparsedPublicKey<B> {
}
}

#[derive(Debug)]
/// TODO
pub struct ParsedPublicKey {
format: ParsedPublicKeyFormat,
nid: i32,
key: LcPtr<EVP_PKEY>,
}

unsafe impl Send for ParsedPublicKey {}
unsafe impl Sync for ParsedPublicKey {}

#[derive(Clone, Copy, PartialEq, Eq, Debug)]
/// The format of a parsed public key.
///
/// This is used to distinguish between different types of public key formats
/// supported by *aws-lc-rs*.
#[non_exhaustive]
pub enum ParsedPublicKeyFormat {
/// The key is in an X.509 SubjectPublicKeyInfo format.
X509,
/// The key is in an uncompressed form (X9.62).
Uncompressed,
/// The key is in a compressed form (SEC 1: Elliptic Curve Cryptography, Version 2.0).
Compressed,
/// The key is in a raw form.
Raw,
}

/// A parsed public key for key agreement.
impl ParsedPublicKey {
fn nid(&self) -> i32 {
self.nid
}

#[allow(unused)]
fn format(&self) -> ParsedPublicKeyFormat {
self.format
}

pub(crate) fn key(&self) -> &LcPtr<EVP_PKEY> {
&self.key
}

/// The algorithm of the public key.
#[must_use]
#[allow(non_upper_case_globals)]
pub fn alg(&self) -> &'static Algorithm {
match self.nid() {
NID_X25519 => &X25519,
NID_X9_62_prime256v1 => &ECDH_P256,
NID_secp384r1 => &ECDH_P384,
NID_secp521r1 => &ECDH_P521,
_ => unreachable!("Unreachable agreement algorithm nid: {}", self.nid()),
}
}
}

impl ParsedPublicKey {
#[allow(non_upper_case_globals)]
pub(crate) fn new(bytes: impl AsRef<[u8]>, nid: i32) -> Result<Self, KeyRejected> {
let key_bytes = bytes.as_ref();
if key_bytes.is_empty() {
return Err(KeyRejected::unspecified());
}
let format = match key_bytes[0] {
0x04 => ParsedPublicKeyFormat::Uncompressed,
0x02 | 0x03 => ParsedPublicKeyFormat::Compressed,
_ => ParsedPublicKeyFormat::X509,
};
match nid {
NID_X25519 => {
let pub_key = try_parse_x25519_public_key_bytes(key_bytes)?;
Ok(ParsedPublicKey {
format,
nid,
key: pub_key,
})
}
NID_X9_62_prime256v1 | NID_secp384r1 | NID_secp521r1 => {
let pub_key = parse_ec_public_key(key_bytes, nid)?;
Ok(ParsedPublicKey {
format,
nid,
key: pub_key,
})
}
_ => Err(KeyRejected::unspecified()),
}
}
}

impl<B: AsRef<[u8]>> UnparsedPublicKey<B> {
#[allow(dead_code)]
fn parse(&self) -> Result<ParsedPublicKey, KeyRejected> {
ParsedPublicKey::new(&self.bytes, self.alg.id.nid())
}
}

impl<B: AsRef<[u8]>> TryFrom<&UnparsedPublicKey<B>> for ParsedPublicKey {
type Error = KeyRejected;
fn try_from(upk: &UnparsedPublicKey<B>) -> Result<Self, Self::Error> {
upk.parse()
}
}

impl<B: AsRef<[u8]>> TryFrom<UnparsedPublicKey<B>> for ParsedPublicKey {
type Error = KeyRejected;
fn try_from(upk: UnparsedPublicKey<B>) -> Result<Self, Self::Error> {
upk.parse()
}
}

/// Performs a key agreement with a private key and the given public key.
///
/// `my_private_key` is the private key to use. Only a reference to the key
Expand Down Expand Up @@ -694,125 +805,49 @@ impl<B: AsRef<[u8]>> UnparsedPublicKey<B> {
/// `error_value` on internal failure.
#[inline]
#[allow(clippy::missing_panics_doc)]
pub fn agree<B: AsRef<[u8]>, F, R, E>(
pub fn agree<B: TryInto<ParsedPublicKey>, F, R, E>(
my_private_key: &PrivateKey,
peer_public_key: &UnparsedPublicKey<B>,
peer_public_key: B,
error_value: E,
kdf: F,
) -> Result<R, E>
where
F: FnOnce(&[u8]) -> Result<R, E>,
{
let expected_alg = my_private_key.algorithm();
let expected_nid = expected_alg.id.nid();

if peer_public_key.alg != expected_alg {
return Err(error_value);
}

let peer_pub_bytes = peer_public_key.bytes.as_ref();
let parse_result = peer_public_key.try_into();

let mut buffer = [0u8; MAX_AGREEMENT_SECRET_LEN];

let secret: &[u8] = match &my_private_key.inner_key {
KeyInner::X25519(priv_key) => {
x25519_diffie_hellman(&mut buffer, priv_key, peer_pub_bytes).or(Err(error_value))?
}
KeyInner::ECDH_P256(priv_key)
| KeyInner::ECDH_P384(priv_key)
| KeyInner::ECDH_P521(priv_key) => {
ec_key_ecdh(&mut buffer, priv_key, peer_pub_bytes, expected_nid).or(Err(error_value))?
if let Ok(peer_pub_key) = parse_result {
if peer_pub_key.alg() != expected_alg {
return Err(error_value);
}
};
kdf(secret)
}

// Current max secret length is P-521's.
const MAX_AGREEMENT_SECRET_LEN: usize = AlgorithmID::ECDH_P521.private_key_len();

#[inline]
#[allow(clippy::needless_pass_by_value)]
fn ec_key_ecdh<'a>(
buffer: &'a mut [u8; MAX_AGREEMENT_SECRET_LEN],
priv_key: &LcPtr<EVP_PKEY>,
peer_pub_key_bytes: &[u8],
nid: i32,
) -> Result<&'a [u8], Unspecified> {
let mut pub_key = encoding::parse_ec_public_key(peer_pub_key_bytes, nid)?;

let mut pkey_ctx = priv_key.create_EVP_PKEY_CTX()?;

if 1 != unsafe { EVP_PKEY_derive_init(*pkey_ctx.as_mut()) } {
return Err(Unspecified);
}

if 1 != unsafe { EVP_PKEY_derive_set_peer(*pkey_ctx.as_mut(), *pub_key.as_mut()) } {
return Err(Unspecified);
let secret = my_private_key
.inner_key
.get_evp_pkey()
.agree(peer_pub_key.key())
.or(Err(error_value))?;

kdf(secret.as_ref())
} else {
Err(error_value)
}

let mut out_key_len = buffer.len();

if 1 != indicator_check!(unsafe {
EVP_PKEY_derive(*pkey_ctx.as_mut(), buffer.as_mut_ptr(), &mut out_key_len)
}) {
return Err(Unspecified);
}

if 0 == out_key_len {
return Err(Unspecified);
}

Ok(&buffer[0..out_key_len])
}

#[inline]
fn x25519_diffie_hellman<'a>(
buffer: &'a mut [u8; MAX_AGREEMENT_SECRET_LEN],
priv_key: &LcPtr<EVP_PKEY>,
peer_pub_key: &[u8],
) -> Result<&'a [u8], ()> {
let mut pkey_ctx = priv_key.create_EVP_PKEY_CTX()?;

if 1 != unsafe { EVP_PKEY_derive_init(*pkey_ctx.as_mut()) } {
return Err(());
}

let mut pub_key = try_parse_x25519_public_key_bytes(peer_pub_key)?;

if 1 != unsafe { EVP_PKEY_derive_set_peer(*pkey_ctx.as_mut(), *pub_key.as_mut()) } {
return Err(());
}

let mut out_key_len = buffer.len();

if 1 != indicator_check!(unsafe {
EVP_PKEY_derive(*pkey_ctx.as_mut(), buffer.as_mut_ptr(), &mut out_key_len)
}) {
return Err(());
}

debug_assert!(out_key_len == AlgorithmID::X25519.pub_key_len());

Ok(&buffer[0..AlgorithmID::X25519.pub_key_len()])
}

pub(crate) fn try_parse_x25519_public_key_bytes(
key_bytes: &[u8],
) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
) -> Result<LcPtr<EVP_PKEY>, KeyRejected> {
LcPtr::<EVP_PKEY>::parse_rfc5280_public_key(key_bytes, EVP_PKEY_X25519)
.or(try_parse_x25519_public_key_raw_bytes(key_bytes))
}

fn try_parse_x25519_public_key_raw_bytes(key_bytes: &[u8]) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
fn try_parse_x25519_public_key_raw_bytes(key_bytes: &[u8]) -> Result<LcPtr<EVP_PKEY>, KeyRejected> {
let expected_pub_key_len = X25519.id.pub_key_len();
if key_bytes.len() != expected_pub_key_len {
return Err(Unspecified);
return Err(KeyRejected::invalid_encoding());
}

Ok(LcPtr::<EVP_PKEY>::parse_raw_public_key(
key_bytes,
EVP_PKEY_X25519,
)?)
LcPtr::<EVP_PKEY>::parse_raw_public_key(key_bytes, EVP_PKEY_X25519)
}

#[cfg(test)]
Expand Down Expand Up @@ -893,7 +928,7 @@ mod tests {
assert!(PrivateKey::from_private_key_der(alg, test_key).is_err());
assert!(agree(
my_private_key,
&UnparsedPublicKey::new(alg, test_key),
UnparsedPublicKey::new(alg, test_key),
(),
|_| Ok(())
)
Expand Down
8 changes: 4 additions & 4 deletions aws-lc-rs/src/agreement/ephemeral.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC

use crate::agreement::{agree, Algorithm, PrivateKey, PublicKey, UnparsedPublicKey};
use crate::agreement::{agree, Algorithm, ParsedPublicKey, PrivateKey, PublicKey};
use crate::error::Unspecified;
use crate::rand::SecureRandom;
use core::fmt;
Expand Down Expand Up @@ -98,9 +98,9 @@ impl EphemeralPrivateKey {
#[allow(clippy::needless_pass_by_value)]
#[allow(clippy::missing_panics_doc)]
#[allow(clippy::module_name_repetitions)]
pub fn agree_ephemeral<B: AsRef<[u8]>, F, R, E>(
pub fn agree_ephemeral<B: TryInto<ParsedPublicKey>, F, R, E>(
my_private_key: EphemeralPrivateKey,
peer_public_key: &UnparsedPublicKey<B>,
peer_public_key: B,
error_value: E,
kdf: F,
) -> Result<R, E>
Expand Down Expand Up @@ -496,7 +496,7 @@ mod tests {
let private_key =
agreement::EphemeralPrivateKey::generate_for_test(&agreement::X25519, &rng)?;
let public_key = agreement::UnparsedPublicKey::new(&agreement::X25519, public_key);
agreement::agree_ephemeral(private_key, &public_key, Unspecified, |agreed_value| {
agreement::agree_ephemeral(private_key, public_key, Unspecified, |agreed_value| {
Ok(Vec::from(agreed_value))
})
}
Expand Down
Loading
Loading