Skip to content

Commit ba6cb4b

Browse files
committed
tss-esapi: move public keys to rustcrypto ecosystem
Signed-off-by: Arthur Gautier <arthur.gautier@arista.com>
1 parent 75e9879 commit ba6cb4b

File tree

4 files changed

+251
-144
lines changed

4 files changed

+251
-144
lines changed

tss-esapi/Cargo.toml

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,15 @@ hostname-validator = "1.1.0"
2727
regex = "1.3.9"
2828
zeroize = { version = "1.5.7", features = ["zeroize_derive"] }
2929
tss-esapi-sys = { path = "../tss-esapi-sys", version = "0.5.0" }
30-
oid = { version = "0.2.1", optional = true }
31-
picky-asn1 = { version = "0.8.0", optional = true }
32-
picky-asn1-x509 = { version = "0.12.0", optional = true }
30+
x509-cert = { version = "0.2.0", optional = true }
31+
elliptic-curve = { version = "0.13.8", optional = true, features = ["alloc", "pkcs8"] }
32+
p192 = { version = "0.13.0", optional = true }
33+
p224 = { version = "0.13.2", optional = true }
34+
p256 = { version = "0.13.2", optional = true }
35+
p384 = { version = "0.13.0", optional = true }
36+
p521 = { version = "0.13.3", optional = true }
37+
sm2 = { version = "0.13.3", optional = true }
38+
rsa = { version = "0.9", optional = true }
3339
cfg-if = "1.0.0"
3440
strum = { version = "0.25.0", optional = true }
3541
strum_macros = { version = "0.25.0", optional = true }
@@ -47,5 +53,5 @@ semver = "1.0.7"
4753
[features]
4854
default = ["abstraction"]
4955
generate-bindings = ["tss-esapi-sys/generate-bindings"]
50-
abstraction = ["oid", "picky-asn1", "picky-asn1-x509"]
56+
abstraction = ["elliptic-curve", "rsa", "x509-cert", "p192", "p224", "p256", "p384", "p521", "sm2"]
5157
integration-tests = ["strum", "strum_macros"]

tss-esapi/src/abstraction/public.rs

Lines changed: 195 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -3,126 +3,232 @@
33

44
use crate::interface_types::ecc::EccCurve;
55
use crate::structures::{Public, RsaExponent};
6+
use crate::utils::PublicKey as TpmPublicKey;
67
use crate::{Error, WrapperErrorKind};
78

89
use core::convert::TryFrom;
9-
use oid::ObjectIdentifier;
10-
use picky_asn1::bit_string::BitString;
11-
use picky_asn1::wrapper::{IntegerAsn1, OctetStringAsn1};
12-
use picky_asn1_x509::{
13-
AlgorithmIdentifier, EcParameters, EcPoint, PublicKey, RsaPublicKey, SubjectPublicKeyInfo,
10+
use elliptic_curve::{
11+
// See TODO below, you're upgrading from 0.13 to 0.14 and
12+
// that moved the implementation from generic-array to
13+
// hybrid-array, you can now use TryFrom
14+
generic_array::typenum::Unsigned,
15+
sec1::{EncodedPoint, FromEncodedPoint, ModulusSize, ToEncodedPoint},
16+
AffinePoint,
17+
CurveArithmetic,
18+
FieldBytesSize,
19+
PublicKey,
1420
};
21+
use rsa::{pkcs8::EncodePublicKey, BigUint, RsaPublicKey};
22+
use x509_cert::spki::SubjectPublicKeyInfoOwned;
1523

16-
/// Can be converted from [`crate::structures::Public`] when not a fully constructed
17-
/// [`picky_asn1_x509::SubjectPublicKeyInfo`] is required.
18-
///
19-
/// # Details
20-
/// Holds either [`picky_asn1_x509::RsaPublicKey`] for [`crate::structures::Public::Rsa`] or
21-
/// [`picky_asn1_x509::EcPoint`] for [`crate::structures::Public::Ecc`].
22-
///
23-
/// This object can be serialized and deserialized
24-
/// using serde if the `serde` feature is enabled.
25-
#[derive(Debug, PartialEq, Eq, Clone)]
26-
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
27-
pub enum DecodedKey {
28-
RsaPublicKey(RsaPublicKey),
29-
EcPoint(EcPoint),
24+
impl<C> TryFrom<&Public> for PublicKey<C>
25+
where
26+
C: CurveArithmetic + AssociatedTpmCurve,
27+
FieldBytesSize<C>: ModulusSize,
28+
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
29+
{
30+
type Error = Error;
31+
32+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
33+
match value {
34+
Public::Ecc {
35+
parameters, unique, ..
36+
} => {
37+
if parameters.ecc_curve() != C::TPM_CURVE {
38+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
39+
}
40+
41+
let x = unique.x().as_bytes();
42+
let y = unique.y().as_bytes();
43+
44+
// TODO: When elliptic_curve bumps to 0.14, we can use the TryFrom implementation instead
45+
// of checking lengths manually
46+
if x.len() != FieldBytesSize::<C>::USIZE {
47+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
48+
}
49+
if y.len() != FieldBytesSize::<C>::USIZE {
50+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
51+
}
52+
53+
let encoded_point =
54+
EncodedPoint::<C>::from_affine_coordinates(x.into(), y.into(), false);
55+
let public_key = PublicKey::<C>::try_from(&encoded_point)
56+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
57+
58+
Ok(public_key)
59+
}
60+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
61+
}
62+
}
3063
}
3164

32-
impl TryFrom<Public> for DecodedKey {
65+
impl TryFrom<&Public> for RsaPublicKey {
3366
type Error = Error;
3467

35-
fn try_from(value: Public) -> Result<Self, Self::Error> {
36-
public_to_decoded_key(&value)
68+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
69+
match value {
70+
Public::Rsa {
71+
unique, parameters, ..
72+
} => {
73+
let exponent = match parameters.exponent() {
74+
RsaExponent::ZERO_EXPONENT => BigUint::from(65537u32),
75+
_ => BigUint::from(parameters.exponent().value()),
76+
};
77+
let modulus = BigUint::from_bytes_be(unique.as_bytes());
78+
79+
let public_key = RsaPublicKey::new(modulus, exponent)
80+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
81+
82+
Ok(public_key)
83+
}
84+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
85+
}
3786
}
3887
}
3988

40-
impl TryFrom<Public> for SubjectPublicKeyInfo {
89+
impl TryFrom<&Public> for SubjectPublicKeyInfoOwned {
4190
type Error = Error;
4291

43-
/// Converts [`crate::structures::Public::Rsa`] and [`crate::structures::Public::Ecc`] to [`picky_asn1_x509::SubjectPublicKeyInfo`].
92+
/// Converts [`crate::structures::Public::Rsa`] and [`crate::structures::Public::Ecc`] to [`x509_cert::spki::SubjectPublicKeyInfoOwned`].
4493
///
4594
/// # Details
46-
/// The result can be used to convert TPM public keys to DER using `picky_asn1_der`.
95+
/// The result can be used to convert TPM public keys to DER using `x509-cert`.
4796
///
4897
/// # Errors
4998
/// * if other instances of [`crate::structures::Public`] are used `UnsupportedParam` will be returned.
50-
fn try_from(value: Public) -> Result<Self, Self::Error> {
51-
let decoded_key = public_to_decoded_key(&value)?;
52-
53-
match (value, decoded_key) {
54-
(Public::Rsa { .. }, DecodedKey::RsaPublicKey(key)) => Ok(SubjectPublicKeyInfo {
55-
algorithm: AlgorithmIdentifier::new_rsa_encryption(),
56-
subject_public_key: PublicKey::Rsa(key.into()),
57-
}),
58-
(Public::Ecc { parameters, .. }, DecodedKey::EcPoint(point)) => {
59-
Ok(SubjectPublicKeyInfo {
60-
algorithm: AlgorithmIdentifier::new_elliptic_curve(EcParameters::NamedCurve(
61-
curve_oid(parameters.ecc_curve())?.into(),
62-
)),
63-
subject_public_key: PublicKey::Ec(BitString::with_bytes(point).into()),
64-
})
99+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
100+
match value {
101+
Public::Rsa { .. } => {
102+
let public_key = RsaPublicKey::try_from(value)?;
103+
104+
Ok(public_key
105+
.to_public_key_der()
106+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?
107+
.decode_msg::<Self>()
108+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?)
109+
}
110+
#[allow(unused)]
111+
Public::Ecc { parameters, .. } => {
112+
macro_rules! read_key {
113+
($curve:expr, $key_type:ty) => {
114+
if parameters.ecc_curve() == <$key_type>::TPM_CURVE {
115+
let public_key = PublicKey::<$key_type>::try_from(value)?;
116+
117+
return public_key
118+
.to_public_key_der()
119+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?
120+
.decode_msg::<Self>()
121+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam));
122+
}
123+
};
124+
}
125+
126+
#[cfg(feature = "p192")]
127+
read_key!(EccCurve::NistP192, p192::NistP192);
128+
#[cfg(feature = "p224")]
129+
read_key!(EccCurve::NistP224, p224::NistP224);
130+
#[cfg(feature = "p256")]
131+
read_key!(EccCurve::NistP256, p256::NistP256);
132+
#[cfg(feature = "p384")]
133+
read_key!(EccCurve::NistP384, p384::NistP384);
134+
#[cfg(feature = "p521")]
135+
read_key!(EccCurve::NistP521, p521::NistP521);
136+
#[cfg(feature = "sm2")]
137+
read_key!(EccCurve::Sm2P256, sm2::Sm2);
138+
139+
Err(Error::local_error(WrapperErrorKind::UnsupportedParam))
65140
}
66141
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
67142
}
68143
}
69144
}
70145

71-
/// Converts [`crate::structures::Public::Rsa`] and [`crate::structures::Public::Ecc`] to [DecodedKey].
72-
///
73-
/// # Details
74-
/// Does basic key conversion to either RSA or ECC. In RSA conversion the TPM zero exponent is replaced with `65537`.
75-
///
76-
/// # Errors
77-
/// * if other instances of [`crate::structures::Public`] are used `UnsupportedParam` will be returned.
78-
fn public_to_decoded_key(public: &Public) -> Result<DecodedKey, Error> {
79-
match public {
80-
Public::Rsa {
81-
unique, parameters, ..
82-
} => {
83-
let exponent = match parameters.exponent() {
84-
RsaExponent::ZERO_EXPONENT => 65537,
85-
_ => parameters.exponent().value(),
146+
impl<C> TryFrom<&TpmPublicKey> for PublicKey<C>
147+
where
148+
C: CurveArithmetic + AssociatedTpmCurve,
149+
FieldBytesSize<C>: ModulusSize,
150+
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
151+
{
152+
type Error = Error;
153+
154+
fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> {
155+
match value {
156+
TpmPublicKey::Ecc { x, y } => {
157+
let x = x.as_slice();
158+
let y = y.as_slice();
159+
160+
// TODO: When elliptic_curve bumps to 0.14, we can use the TryFrom implementation instead
161+
// of checking lengths manually
162+
if x.len() != FieldBytesSize::<C>::USIZE {
163+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
164+
}
165+
if y.len() != FieldBytesSize::<C>::USIZE {
166+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
167+
}
168+
169+
let encoded_point =
170+
EncodedPoint::<C>::from_affine_coordinates(x.into(), y.into(), false);
171+
let public_key = PublicKey::<C>::try_from(&encoded_point)
172+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
173+
174+
Ok(public_key)
86175
}
87-
.to_be_bytes();
88-
Ok(DecodedKey::RsaPublicKey(RsaPublicKey {
89-
modulus: IntegerAsn1::from_bytes_be_unsigned(unique.as_bytes().to_vec()),
90-
public_exponent: IntegerAsn1::from_bytes_be_signed(exponent.to_vec()),
91-
}))
92-
}
93-
Public::Ecc { unique, .. } => {
94-
let x = unique.x().as_bytes().to_vec();
95-
let y = unique.y().as_bytes().to_vec();
96-
Ok(DecodedKey::EcPoint(OctetStringAsn1(
97-
elliptic_curve_point_to_octet_string(x, y),
98-
)))
176+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
99177
}
178+
}
179+
}
180+
181+
impl TryFrom<&TpmPublicKey> for RsaPublicKey {
182+
type Error = Error;
183+
184+
fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> {
185+
match value {
186+
TpmPublicKey::Rsa(modulus) => {
187+
let exponent = BigUint::from(65537u32);
188+
let modulus = BigUint::from_bytes_be(modulus.as_slice());
189+
190+
let public_key = RsaPublicKey::new(modulus, exponent)
191+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
100192

101-
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
193+
Ok(public_key)
194+
}
195+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
196+
}
102197
}
103198
}
104199

105-
// Taken from https://github.com/parallaxsecond/parsec/blob/561235f3cc37bcff3d9a6cb29c84eeae5d55100b/src/providers/tpm/utils.rs#L319
106-
// Points on elliptic curves are represented as defined in section 2.3.3 of https://www.secg.org/sec1-v2.pdf
107-
// The (uncompressed) representation is [ 0x04 || x || y ] where x and y are the coordinates of the point
108-
fn elliptic_curve_point_to_octet_string(mut x: Vec<u8>, mut y: Vec<u8>) -> Vec<u8> {
109-
let mut octet_string = vec![0x04];
110-
octet_string.append(&mut x);
111-
octet_string.append(&mut y);
112-
octet_string
200+
/// Provides the value of the curve used in this crate for the specific curve.
201+
pub trait AssociatedTpmCurve {
202+
/// Value of the curve when interacting with the TPM.
203+
const TPM_CURVE: EccCurve;
113204
}
114205

115-
// Map TPM supported ECC curves to their respective OIDs
116-
fn curve_oid(ecc_curve: EccCurve) -> Result<ObjectIdentifier, Error> {
117-
match ecc_curve {
118-
EccCurve::NistP192 => Ok(picky_asn1_x509::oids::secp192r1()),
119-
EccCurve::NistP224 => Ok(picky_asn1_x509::oids::secp256r1()),
120-
EccCurve::NistP256 => Ok(picky_asn1_x509::oids::secp256r1()),
121-
EccCurve::NistP384 => Ok(picky_asn1_x509::oids::secp384r1()),
122-
EccCurve::NistP521 => Ok(picky_asn1_x509::oids::secp521r1()),
123-
// Barreto-Naehrig curves seem to not have any OIDs
124-
EccCurve::BnP256 => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
125-
EccCurve::BnP638 => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
126-
EccCurve::Sm2P256 => Ok(ObjectIdentifier::try_from("1.2.156.10197.1.301").unwrap()),
127-
}
206+
#[cfg(feature = "p192")]
207+
impl AssociatedTpmCurve for p192::NistP192 {
208+
const TPM_CURVE: EccCurve = EccCurve::NistP192;
209+
}
210+
211+
#[cfg(feature = "p224")]
212+
impl AssociatedTpmCurve for p224::NistP224 {
213+
const TPM_CURVE: EccCurve = EccCurve::NistP224;
214+
}
215+
216+
#[cfg(feature = "p256")]
217+
impl AssociatedTpmCurve for p256::NistP256 {
218+
const TPM_CURVE: EccCurve = EccCurve::NistP256;
219+
}
220+
221+
#[cfg(feature = "p384")]
222+
impl AssociatedTpmCurve for p384::NistP384 {
223+
const TPM_CURVE: EccCurve = EccCurve::NistP384;
224+
}
225+
226+
#[cfg(feature = "p521")]
227+
impl AssociatedTpmCurve for p521::NistP521 {
228+
const TPM_CURVE: EccCurve = EccCurve::NistP521;
229+
}
230+
231+
#[cfg(feature = "sm2")]
232+
impl AssociatedTpmCurve for sm2::Sm2 {
233+
const TPM_CURVE: EccCurve = EccCurve::Sm2P256;
128234
}

tss-esapi/src/structures/tagged/public.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ use crate::{
1313
Error, Result, ReturnCode, WrapperErrorKind,
1414
};
1515

16+
use self::rsa::PublicRsaParameters;
1617
use ecc::PublicEccParameters;
1718
use keyed_hash::PublicKeyedHashParameters;
18-
use rsa::PublicRsaParameters;
1919

2020
use log::error;
2121
use std::convert::{TryFrom, TryInto};

0 commit comments

Comments
 (0)