Skip to content

Commit a0cb980

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

File tree

4 files changed

+267
-146
lines changed

4 files changed

+267
-146
lines changed

tss-esapi/Cargo.toml

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,6 @@ hostname-validator = "1.1.0"
3434
regex = "1.3.9"
3535
zeroize = { version = "1.5.7", features = ["zeroize_derive"] }
3636
tss-esapi-sys = { path = "../tss-esapi-sys", version = "0.5.0" }
37-
oid = { version = "0.2.1", optional = true }
38-
picky-asn1 = { version = "0.9.0", optional = true }
39-
picky-asn1-x509 = { version = "0.13.0", optional = true }
4037
x509-cert = { version = "0.2.0", optional = true }
4138
ecdsa = { version = "0.16.9", features = ["der", "hazmat", "arithmetic", "verifying"], optional = true }
4239
elliptic-curve = { version = "0.13.8", optional = true, features = ["alloc", "pkcs8"] }
@@ -45,6 +42,7 @@ p224 = { version = "0.13.2", optional = true }
4542
p256 = { version = "0.13.2", optional = true }
4643
p384 = { version = "0.13.0", optional = true }
4744
p521 = { version = "0.13.3", optional = true }
45+
pkcs8 = { version = "0.10.2", optional = true }
4846
rsa = { version = "0.9", optional = true }
4947
sha1 = { version = "0.10.6", optional = true }
5048
sha2 = { version = "0.10.8", optional = true }
@@ -77,8 +75,8 @@ semver = "1.0.7"
7775
[features]
7876
default = ["abstraction"]
7977
generate-bindings = ["tss-esapi-sys/generate-bindings"]
80-
abstraction = ["oid", "picky-asn1", "picky-asn1-x509"]
78+
abstraction = ["rustcrypto"]
8179
integration-tests = ["strum", "strum_macros"]
8280

83-
rustcrypto = ["ecdsa", "elliptic-curve", "signature", "x509-cert"]
81+
rustcrypto = ["ecdsa", "elliptic-curve", "pkcs8", "signature", "x509-cert"]
8482
rustcrypto-full = ["rustcrypto", "p192", "p224", "p256", "p384", "p521", "rsa", "sha1", "sha2", "sha3", "sm2", "sm3"]

tss-esapi/src/abstraction/public.rs

Lines changed: 216 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -2,127 +2,253 @@
22
// SPDX-License-Identifier: Apache-2.0
33

44
use crate::interface_types::ecc::EccCurve;
5-
use crate::structures::{Public, RsaExponent};
5+
use crate::structures::Public;
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+
generic_array::typenum::Unsigned,
12+
sec1::{EncodedPoint, FromEncodedPoint, ModulusSize, ToEncodedPoint},
13+
AffinePoint, CurveArithmetic, FieldBytesSize, PublicKey,
1414
};
1515

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),
16+
use x509_cert::spki::SubjectPublicKeyInfoOwned;
17+
18+
#[cfg(all(feature = "rustcrypto", feature = "rsa"))]
19+
use {
20+
crate::structures::RsaExponent,
21+
rsa::{BigUint, RsaPublicKey},
22+
};
23+
24+
#[cfg(all(
25+
feature = "rustcrypto",
26+
any(
27+
feature = "p192",
28+
feature = "p224",
29+
feature = "p256",
30+
feature = "p384",
31+
feature = "p521",
32+
feature = "rsa",
33+
feature = "sm2"
34+
)
35+
))]
36+
use pkcs8::EncodePublicKey;
37+
38+
/// Default exponent for RSA keys.
39+
// Also known as 0x10001
40+
#[cfg(all(feature = "rustcrypto", feature = "rsa"))]
41+
const RSA_DEFAULT_EXP: u64 = 65537;
42+
43+
impl<C> TryFrom<&Public> for PublicKey<C>
44+
where
45+
C: CurveArithmetic + AssociatedTpmCurve,
46+
FieldBytesSize<C>: ModulusSize,
47+
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
48+
{
49+
type Error = Error;
50+
51+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
52+
match value {
53+
Public::Ecc {
54+
parameters, unique, ..
55+
} => {
56+
if parameters.ecc_curve() != C::TPM_CURVE {
57+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
58+
}
59+
60+
let x = unique.x().as_bytes();
61+
let y = unique.y().as_bytes();
62+
63+
if x.len() != FieldBytesSize::<C>::USIZE {
64+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
65+
}
66+
if y.len() != FieldBytesSize::<C>::USIZE {
67+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
68+
}
69+
70+
let encoded_point =
71+
EncodedPoint::<C>::from_affine_coordinates(x.into(), y.into(), false);
72+
let public_key = PublicKey::<C>::try_from(&encoded_point)
73+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
74+
75+
Ok(public_key)
76+
}
77+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
78+
}
79+
}
3080
}
3181

32-
impl TryFrom<Public> for DecodedKey {
82+
#[cfg(all(feature = "rustcrypto", feature = "rsa"))]
83+
impl TryFrom<&Public> for RsaPublicKey {
3384
type Error = Error;
3485

35-
fn try_from(value: Public) -> Result<Self, Self::Error> {
36-
public_to_decoded_key(&value)
86+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
87+
match value {
88+
Public::Rsa {
89+
unique, parameters, ..
90+
} => {
91+
let exponent = match parameters.exponent() {
92+
RsaExponent::ZERO_EXPONENT => BigUint::from(RSA_DEFAULT_EXP),
93+
_ => BigUint::from(parameters.exponent().value()),
94+
};
95+
let modulus = BigUint::from_bytes_be(unique.as_bytes());
96+
97+
let public_key = RsaPublicKey::new(modulus, exponent)
98+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
99+
100+
Ok(public_key)
101+
}
102+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
103+
}
37104
}
38105
}
39106

40-
impl TryFrom<Public> for SubjectPublicKeyInfo {
107+
impl TryFrom<&Public> for SubjectPublicKeyInfoOwned {
41108
type Error = Error;
42109

43-
/// Converts [`crate::structures::Public::Rsa`] and [`crate::structures::Public::Ecc`] to [`picky_asn1_x509::SubjectPublicKeyInfo`].
110+
/// Converts [`crate::structures::Public::Rsa`] and [`crate::structures::Public::Ecc`] to [`x509_cert::spki::SubjectPublicKeyInfoOwned`].
44111
///
45112
/// # Details
46-
/// The result can be used to convert TPM public keys to DER using `picky_asn1_der`.
113+
/// The result can be used to convert TPM public keys to DER using `x509-cert`.
47114
///
48115
/// # Errors
49116
/// * 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-
})
117+
fn try_from(value: &Public) -> Result<Self, Self::Error> {
118+
match value {
119+
#[cfg(all(feature = "rustcrypto", feature = "rsa"))]
120+
Public::Rsa { .. } => {
121+
let public_key = RsaPublicKey::try_from(value)?;
122+
123+
Ok(public_key
124+
.to_public_key_der()
125+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?
126+
.decode_msg::<Self>()
127+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?)
128+
}
129+
#[allow(unused)]
130+
Public::Ecc { parameters, .. } => {
131+
macro_rules! read_key {
132+
($curve:expr, $key_type:ty) => {
133+
if parameters.ecc_curve() == <$key_type>::TPM_CURVE {
134+
let public_key = PublicKey::<$key_type>::try_from(value)?;
135+
136+
return public_key
137+
.to_public_key_der()
138+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?
139+
.decode_msg::<Self>()
140+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam));
141+
}
142+
};
143+
}
144+
145+
#[cfg(all(feature = "rustcrypto", feature = "p192"))]
146+
read_key!(EccCurve::NistP192, p192::NistP192);
147+
#[cfg(all(feature = "rustcrypto", feature = "p224"))]
148+
read_key!(EccCurve::NistP224, p224::NistP224);
149+
#[cfg(all(feature = "rustcrypto", feature = "p256"))]
150+
read_key!(EccCurve::NistP256, p256::NistP256);
151+
#[cfg(all(feature = "rustcrypto", feature = "p384"))]
152+
read_key!(EccCurve::NistP384, p384::NistP384);
153+
#[cfg(all(feature = "rustcrypto", feature = "p521"))]
154+
read_key!(EccCurve::NistP521, p521::NistP521);
155+
#[cfg(all(feature = "rustcrypto", feature = "sm2"))]
156+
read_key!(EccCurve::Sm2P256, sm2::Sm2);
157+
158+
Err(Error::local_error(WrapperErrorKind::UnsupportedParam))
65159
}
66160
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
67161
}
68162
}
69163
}
70164

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(),
165+
impl<C> TryFrom<&TpmPublicKey> for PublicKey<C>
166+
where
167+
C: CurveArithmetic + AssociatedTpmCurve,
168+
FieldBytesSize<C>: ModulusSize,
169+
AffinePoint<C>: FromEncodedPoint<C> + ToEncodedPoint<C>,
170+
{
171+
type Error = Error;
172+
173+
fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> {
174+
match value {
175+
TpmPublicKey::Ecc { x, y } => {
176+
let x = x.as_slice();
177+
let y = y.as_slice();
178+
179+
// TODO: When elliptic_curve bumps to 0.14, we can use the TryFrom implementation instead
180+
// of checking lengths manually
181+
if x.len() != FieldBytesSize::<C>::USIZE {
182+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
183+
}
184+
if y.len() != FieldBytesSize::<C>::USIZE {
185+
return Err(Error::local_error(WrapperErrorKind::InvalidParam));
186+
}
187+
188+
let encoded_point =
189+
EncodedPoint::<C>::from_affine_coordinates(x.into(), y.into(), false);
190+
let public_key = PublicKey::<C>::try_from(&encoded_point)
191+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
192+
193+
Ok(public_key)
86194
}
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-
)))
195+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
99196
}
197+
}
198+
}
199+
200+
#[cfg(all(feature = "rustcrypto", feature = "rsa"))]
201+
impl TryFrom<&TpmPublicKey> for RsaPublicKey {
202+
type Error = Error;
100203

101-
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
204+
fn try_from(value: &TpmPublicKey) -> Result<Self, Self::Error> {
205+
match value {
206+
TpmPublicKey::Rsa(modulus) => {
207+
let exponent = BigUint::from(RSA_DEFAULT_EXP);
208+
let modulus = BigUint::from_bytes_be(modulus.as_slice());
209+
210+
let public_key = RsaPublicKey::new(modulus, exponent)
211+
.map_err(|_| Error::local_error(WrapperErrorKind::InvalidParam))?;
212+
213+
Ok(public_key)
214+
}
215+
_ => Err(Error::local_error(WrapperErrorKind::UnsupportedParam)),
216+
}
102217
}
103218
}
104219

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
220+
/// Provides the value of the curve used in this crate for the specific curve.
221+
pub trait AssociatedTpmCurve {
222+
/// Value of the curve when interacting with the TPM.
223+
const TPM_CURVE: EccCurve;
113224
}
114225

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-
}
226+
#[cfg(all(feature = "rustcrypto", feature = "p192"))]
227+
impl AssociatedTpmCurve for p192::NistP192 {
228+
const TPM_CURVE: EccCurve = EccCurve::NistP192;
229+
}
230+
231+
#[cfg(all(feature = "rustcrypto", feature = "p224"))]
232+
impl AssociatedTpmCurve for p224::NistP224 {
233+
const TPM_CURVE: EccCurve = EccCurve::NistP224;
234+
}
235+
236+
#[cfg(all(feature = "rustcrypto", feature = "p256"))]
237+
impl AssociatedTpmCurve for p256::NistP256 {
238+
const TPM_CURVE: EccCurve = EccCurve::NistP256;
239+
}
240+
241+
#[cfg(all(feature = "rustcrypto", feature = "p384"))]
242+
impl AssociatedTpmCurve for p384::NistP384 {
243+
const TPM_CURVE: EccCurve = EccCurve::NistP384;
244+
}
245+
246+
#[cfg(all(feature = "rustcrypto", feature = "p521"))]
247+
impl AssociatedTpmCurve for p521::NistP521 {
248+
const TPM_CURVE: EccCurve = EccCurve::NistP521;
249+
}
250+
251+
#[cfg(all(feature = "rustcrypto", feature = "sm2"))]
252+
impl AssociatedTpmCurve for sm2::Sm2 {
253+
const TPM_CURVE: EccCurve = EccCurve::Sm2P256;
128254
}

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)