Skip to content

Commit

Permalink
Move logic to ec::encoding::sec1 module
Browse files Browse the repository at this point in the history
  • Loading branch information
justsmth committed Jan 24, 2025
1 parent 002cf1f commit 7141306
Show file tree
Hide file tree
Showing 8 changed files with 306 additions and 270 deletions.
22 changes: 12 additions & 10 deletions aws-lc-rs/src/agreement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
//! ```
mod ephemeral;

use crate::ec::encoding::sec1::parse_sec1_private_bn;
pub use ephemeral::{agree_ephemeral, EphemeralPrivateKey};

use crate::aws_lc::{
Expand All @@ -60,7 +61,7 @@ use crate::aws_lc::{
EVP_PKEY_new_raw_public_key, NID_X9_62_prime256v1, NID_secp384r1, NID_secp521r1, EVP_PKEY,
EVP_PKEY_X25519, NID_X25519,
};
use crate::ec::evp_key_generate;
use crate::ec::{encoding, evp_key_generate};
use crate::error::{KeyRejected, Unspecified};
use crate::fips::indicator_check;
use crate::ptr::{ConstPointer, LcPtr};
Expand Down Expand Up @@ -299,7 +300,7 @@ impl PrivateKey {
if AlgorithmID::X25519 == alg.id {
return Err(KeyRejected::invalid_encoding());
}
let evp_pkey = ec::unmarshal_der_to_private_key(key_bytes, alg.id.nid())?;
let evp_pkey = encoding::unmarshal_der_to_private_key(key_bytes, alg.id.nid())?;
Ok(Self::new(alg, evp_pkey))
}

Expand Down Expand Up @@ -328,7 +329,7 @@ impl PrivateKey {
)
})?
} else {
LcPtr::<EVP_PKEY>::parse_ec_private_bn(key_bytes, alg.id.nid())
parse_sec1_private_bn(key_bytes, alg.id.nid())
.map_err(|_| KeyRejected::invalid_encoding())?
};
Ok(Self::new(alg, evp_pkey))
Expand Down Expand Up @@ -384,23 +385,23 @@ impl PrivateKey {

#[cfg(test)]
fn from_p256_private_key(priv_key: &[u8]) -> Result<Self, Unspecified> {
let pkey = LcPtr::<EVP_PKEY>::parse_ec_private_bn(priv_key, ECDH_P256.id.nid())?;
let pkey = parse_sec1_private_bn(priv_key, ECDH_P256.id.nid())?;
Ok(PrivateKey {
inner_key: KeyInner::ECDH_P256(pkey),
})
}

#[cfg(test)]
fn from_p384_private_key(priv_key: &[u8]) -> Result<Self, Unspecified> {
let pkey = LcPtr::<EVP_PKEY>::parse_ec_private_bn(priv_key, ECDH_P384.id.nid())?;
let pkey = parse_sec1_private_bn(priv_key, ECDH_P384.id.nid())?;
Ok(PrivateKey {
inner_key: KeyInner::ECDH_P384(pkey),
})
}

#[cfg(test)]
fn from_p521_private_key(priv_key: &[u8]) -> Result<Self, Unspecified> {
let pkey = LcPtr::<EVP_PKEY>::parse_ec_private_bn(priv_key, ECDH_P521.id.nid())?;
let pkey = parse_sec1_private_bn(priv_key, ECDH_P521.id.nid())?;
Ok(PrivateKey {
inner_key: KeyInner::ECDH_P521(pkey),
})
Expand All @@ -416,7 +417,7 @@ impl PrivateKey {
| KeyInner::ECDH_P384(evp_pkey)
| KeyInner::ECDH_P521(evp_pkey) => {
let mut buffer = [0u8; MAX_PUBLIC_KEY_LEN];
let key_len = ec::marshal_public_key_to_buffer(&mut buffer, evp_pkey, false)?;
let key_len = encoding::marshal_public_key_to_buffer(&mut buffer, evp_pkey, false)?;
Ok(PublicKey {
inner_key: self.inner_key.clone(),
public_key: buffer,
Expand Down Expand Up @@ -492,7 +493,7 @@ impl AsBigEndian<EcPrivateKeyBin<'static>> for PrivateKey {
if AlgorithmID::X25519 == self.inner_key.algorithm().id {
return Err(Unspecified);
}
let buffer = ec::marshal_private_key_to_buffer(
let buffer = encoding::marshal_private_key_to_buffer(
self.inner_key.algorithm().id.private_key_len(),
&self.inner_key.get_evp_pkey().as_const(),
)?;
Expand Down Expand Up @@ -623,7 +624,7 @@ impl AsBigEndian<EcPublicKeyCompressedBin<'static>> for PublicKey {

let mut buffer = vec![0u8; self.algorithm().id.compressed_pub_key_len()];

let out_len = ec::marshal_ec_public_key_to_buffer(&mut buffer, &ec_key, true)?;
let out_len = encoding::marshal_ec_public_key_to_buffer(&mut buffer, &ec_key, true)?;

debug_assert_eq!(buffer.len(), out_len);

Expand Down Expand Up @@ -766,7 +767,8 @@ fn ec_key_ecdh<'a>(
peer_pub_key_bytes: &[u8],
nid: i32,
) -> Result<&'a [u8], ()> {
let mut pub_key = ec::try_parse_public_key_bytes(peer_pub_key_bytes, nid).map_err(|_| ())?;
let mut pub_key =
encoding::try_parse_public_key_bytes(peer_pub_key_bytes, nid).map_err(|_| ())?;

let mut pkey_ctx = priv_key.create_EVP_PKEY_CTX()?;

Expand Down
2 changes: 1 addition & 1 deletion aws-lc-rs/src/cbb.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0 OR ISC

use crate::aws_lc::{CBB_cleanup, CBB_finish, CBB_init, CBB};
use crate::error::Unspecified;
use crate::ptr::LcPtr;
use crate::aws_lc::{CBB_cleanup, CBB_finish, CBB_init, CBB};
use core::marker::PhantomData;
use core::mem::MaybeUninit;
use core::ptr::null_mut;
Expand Down
155 changes: 12 additions & 143 deletions aws-lc-rs/src/ec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,24 @@ use core::ptr::null_mut;
// TODO: Uncomment when MSRV >= 1.64
use std::os::raw::c_int;

use crate::error::{KeyRejected, Unspecified};
use crate::fips::indicator_check;
use crate::ptr::{ConstPointer, LcPtr};
use crate::signature::Signature;
#[cfg(feature = "fips")]
use aws_lc::EC_KEY_check_fips;
use crate::aws_lc::EC_KEY_check_fips;
#[cfg(not(feature = "fips"))]
use crate::aws_lc::EC_KEY_check_key;
use crate::aws_lc::{
EC_KEY_check_key, d2i_PrivateKey, point_conversion_form_t, BN_bn2bin_padded, BN_num_bytes, ECDSA_SIG_from_bytes,
ECDSA_SIG_get0_r, ECDSA_SIG_get0_s, EC_GROUP_get_curve_name, EC_KEY_get0_group,
EC_KEY_get0_private_key, EC_KEY_get0_public_key, EC_POINT_new,
EC_POINT_oct2point, EC_POINT_point2oct, EC_group_p224, EC_group_p256, EC_group_p384,
EC_group_p521, EC_group_secp256k1, EVP_PKEY_CTX_new_id, EVP_PKEY_CTX_set_ec_paramgen_curve_nid,
ECDSA_SIG_from_bytes, ECDSA_SIG_get0_r, ECDSA_SIG_get0_s, EC_GROUP_get_curve_name,
EC_KEY_get0_group, EC_group_p224, EC_group_p256, EC_group_p384, EC_group_p521,
EC_group_secp256k1, EVP_PKEY_CTX_new_id, EVP_PKEY_CTX_set_ec_paramgen_curve_nid,
EVP_PKEY_get0_EC_KEY, EVP_PKEY_keygen, EVP_PKEY_keygen_init, NID_X9_62_prime256v1,
NID_secp224r1, NID_secp256k1, NID_secp384r1, NID_secp521r1, EC_GROUP, EC_KEY, EC_POINT,
EVP_PKEY, EVP_PKEY_EC,
NID_secp224r1, NID_secp256k1, NID_secp384r1, NID_secp521r1, EC_GROUP, EC_KEY, EVP_PKEY,
EVP_PKEY_EC,
};
use crate::error::{KeyRejected, Unspecified};
use crate::fips::indicator_check;
use crate::ptr::{ConstPointer, LcPtr};
use crate::signature::Signature;

pub(crate) mod encoding;
pub(crate) mod key_pair;
pub(crate) mod signature;

Expand Down Expand Up @@ -83,90 +83,6 @@ pub(crate) fn validate_evp_key(
Ok(())
}

pub(crate) fn marshal_private_key_to_buffer(
private_size: usize,
evp_pkey: &ConstPointer<EVP_PKEY>,
) -> Result<Vec<u8>, Unspecified> {
let ec_key = ConstPointer::new(unsafe { EVP_PKEY_get0_EC_KEY(**evp_pkey) })?;
let private_bn = ConstPointer::new(unsafe { EC_KEY_get0_private_key(*ec_key) })?;
{
let size: usize = unsafe { BN_num_bytes(*private_bn).try_into()? };
debug_assert!(size <= private_size);
}

let mut buffer = vec![0u8; private_size];
if 1 != unsafe { BN_bn2bin_padded(buffer.as_mut_ptr(), private_size, *private_bn) } {
return Err(Unspecified);
}

Ok(buffer)
}

pub(crate) fn unmarshal_der_to_private_key(
key_bytes: &[u8],
nid: i32,
) -> Result<LcPtr<EVP_PKEY>, KeyRejected> {
let mut out = null_mut();
// `d2i_PrivateKey` -> ... -> `EC_KEY_parse_private_key` -> `EC_KEY_check_key`
let evp_pkey = LcPtr::new(unsafe {
d2i_PrivateKey(
EVP_PKEY_EC,
&mut out,
&mut key_bytes.as_ptr(),
key_bytes
.len()
.try_into()
.map_err(|_| KeyRejected::too_large())?,
)
})?;
#[cfg(not(feature = "fips"))]
verify_evp_key_nid(&evp_pkey.as_const(), nid)?;
#[cfg(feature = "fips")]
validate_evp_key(&evp_pkey.as_const(), nid)?;

Ok(evp_pkey)
}

pub(crate) fn marshal_public_key_to_buffer(
buffer: &mut [u8],
evp_pkey: &LcPtr<EVP_PKEY>,
compressed: bool,
) -> Result<usize, Unspecified> {
let ec_key = ConstPointer::new(unsafe { EVP_PKEY_get0_EC_KEY(*evp_pkey.as_const()) })?;
marshal_ec_public_key_to_buffer(buffer, &ec_key, compressed)
}

pub(crate) fn marshal_ec_public_key_to_buffer(
buffer: &mut [u8],
ec_key: &ConstPointer<EC_KEY>,
compressed: bool,
) -> Result<usize, Unspecified> {
let ec_group = ConstPointer::new(unsafe { EC_KEY_get0_group(**ec_key) })?;

let ec_point = ConstPointer::new(unsafe { EC_KEY_get0_public_key(**ec_key) })?;

let point_conversion_form = if compressed {
point_conversion_form_t::POINT_CONVERSION_COMPRESSED
} else {
point_conversion_form_t::POINT_CONVERSION_UNCOMPRESSED
};

let out_len = ec_point_to_bytes(&ec_group, &ec_point, buffer, point_conversion_form)?;
Ok(out_len)
}

pub(crate) fn try_parse_public_key_bytes(
key_bytes: &[u8],
expected_curve_nid: i32,
) -> Result<LcPtr<EVP_PKEY>, KeyRejected> {
LcPtr::<EVP_PKEY>::parse_rfc5280_public_key(key_bytes, EVP_PKEY_EC)
.or(LcPtr::<EVP_PKEY>::parse_ec_public_point(
key_bytes,
expected_curve_nid,
))
.and_then(|key| validate_evp_key(&key.as_const(), expected_curve_nid).map(|()| key))
}

#[inline]
pub(crate) fn evp_key_generate(nid: c_int) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
let mut pkey_ctx = LcPtr::new(unsafe { EVP_PKEY_CTX_new_id(EVP_PKEY_EC, null_mut()) })?;
Expand Down Expand Up @@ -206,53 +122,6 @@ pub(crate) fn ec_group_from_nid(nid: i32) -> Result<ConstPointer<EC_GROUP>, Unsp
}?)?)
}

#[inline]
pub(crate) fn ec_point_from_bytes(
ec_group: &ConstPointer<EC_GROUP>,
bytes: &[u8],
) -> Result<LcPtr<EC_POINT>, KeyRejected> {
let mut ec_point = LcPtr::new(unsafe { EC_POINT_new(**ec_group) })?;

if 1 != unsafe {
EC_POINT_oct2point(
**ec_group,
*ec_point.as_mut(),
bytes.as_ptr(),
bytes.len(),
null_mut(),
)
} {
return Err(KeyRejected::invalid_encoding());
}

Ok(ec_point)
}

#[inline]
fn ec_point_to_bytes(
ec_group: &ConstPointer<EC_GROUP>,
ec_point: &ConstPointer<EC_POINT>,
buf: &mut [u8],
pt_conv_form: point_conversion_form_t,
) -> Result<usize, Unspecified> {
let buf_len = buf.len();
let out_len = unsafe {
EC_POINT_point2oct(
**ec_group,
**ec_point,
pt_conv_form,
buf.as_mut_ptr(),
buf_len,
null_mut(),
)
};
if out_len == 0 {
return Err(Unspecified);
}

Ok(out_len)
}

#[inline]
fn ecdsa_asn1_to_fixed(alg_id: &'static AlgorithmID, sig: &[u8]) -> Result<Signature, Unspecified> {
let expected_number_size = alg_id.private_key_size();
Expand Down
Loading

0 comments on commit 7141306

Please sign in to comment.