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 EC keys, fix Attributes processing #369

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions native-pkcs11-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ p256 = { version = "0.13.2", default-features = false, features = [
"pkcs8",
"std",
] }
spki = "0.7"
der = "0.7"
pkcs1 = { version = "0.7.5", default-features = false }
pkcs11-sys = { version = "0.2.0", path = "../pkcs11-sys" }
strum = "0.26"
Expand Down
136 changes: 94 additions & 42 deletions native-pkcs11-core/src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@

use std::{ffi::CString, fmt::Debug, sync::Arc};

use der::{
asn1::{ObjectIdentifier, OctetString},
Encode,
};
use native_pkcs11_traits::{
backend,
Certificate,
Expand All @@ -22,10 +26,6 @@ use native_pkcs11_traits::{
PrivateKey,
PublicKey,
};
use p256::pkcs8::{
der::{asn1::OctetString, Encode},
AssociatedOid,
};
use pkcs1::{der::Decode, RsaPublicKey};
use pkcs11_sys::{
CKC_X_509,
Expand All @@ -38,6 +38,7 @@ use pkcs11_sys::{
CK_CERTIFICATE_CATEGORY_UNSPECIFIED,
CK_PROFILE_ID,
};
use spki::SubjectPublicKeyInfoRef;
use tracing::debug;

use crate::attribute::{Attribute, AttributeType, Attributes};
Expand Down Expand Up @@ -74,6 +75,36 @@ impl Clone for Object {
}
}

fn extract_ec_params(der_bytes: &[u8]) -> Option<(Vec<u8>, Vec<u8>)> {
let spki: SubjectPublicKeyInfoRef<'_> = SubjectPublicKeyInfoRef::try_from(der_bytes).unwrap();
// For EC keys, the algorithm parameters contain the curve OID
// For EC keys, the subject public key is the EC point
Some((
ObjectIdentifier::from_bytes(spki.algorithm.parameters.unwrap().value())
.unwrap()
.to_der()
.unwrap(),
OctetString::new(spki.subject_public_key.raw_bytes())
.unwrap()
.to_der()
.unwrap(),
))
}

fn extract_rsa_params(der_bytes: &[u8]) -> Option<(Vec<u8>, Vec<u8>, u64)> {
// Parse the DER-encoded SPKI
let spki: SubjectPublicKeyInfoRef<'_> = SubjectPublicKeyInfoRef::try_from(der_bytes).unwrap();
// Parse the RSA public key bytes from the SPKI
let rsa_pubkey = RsaPublicKey::from_der(spki.subject_public_key.raw_bytes()).ok()?;
let modulus = rsa_pubkey.modulus.as_bytes();

Some((
modulus.to_vec(),
rsa_pubkey.public_exponent.as_bytes().to_vec(),
(modulus.len() * 8) as u64,
))
}

impl Object {
pub fn attribute(&self, type_: AttributeType) -> Option<Attribute> {
match self {
Expand Down Expand Up @@ -102,8 +133,22 @@ impl Object {
AttributeType::Class => Some(Attribute::Class(CKO_PRIVATE_KEY)),
AttributeType::Decrypt => Some(Attribute::Decrypt(false)),
AttributeType::Derive => Some(Attribute::Derive(false)),
AttributeType::EcParams => {
Some(Attribute::EcParams(p256::NistP256::OID.to_der().ok()?))
AttributeType::EcParams | AttributeType::EcPoint => {
if private_key.algorithm() != KeyAlgorithm::Ecc {
return None;
}
private_key
.find_public_key(backend())
.ok()
.flatten()
.and_then(|public_key| {
let der_bytes = public_key.to_der();
extract_ec_params(&der_bytes).map(|(params, point)| match type_ {
AttributeType::EcParams => Attribute::EcParams(params),
AttributeType::EcPoint => Attribute::EcPoint(point),
_ => unreachable!(),
})
})
}
AttributeType::Extractable => Some(Attribute::Extractable(false)),
AttributeType::Id => Some(Attribute::Id(private_key.public_key_hash())),
Expand All @@ -113,34 +158,32 @@ impl Object {
})),
AttributeType::Label => Some(Attribute::Label(private_key.label())),
AttributeType::Local => Some(Attribute::Local(false)),
AttributeType::Modulus => {
let modulus = private_key
AttributeType::Modulus
| AttributeType::ModulusBits
| AttributeType::PublicExponent => {
if private_key.algorithm() != KeyAlgorithm::Rsa {
return None;
}
private_key
.find_public_key(backend())
.ok()
.flatten()
.and_then(|public_key| {
let der = public_key.to_der();
RsaPublicKey::from_der(&der)
.map(|pk| pk.modulus.as_bytes().to_vec())
.ok()
});
modulus.map(Attribute::Modulus)
let der_bytes = public_key.to_der();
extract_rsa_params(&der_bytes).map(|(modulus, exponent, bits)| {
match type_ {
AttributeType::Modulus => Attribute::Modulus(modulus),
AttributeType::ModulusBits => Attribute::ModulusBits(bits),
AttributeType::PublicExponent => {
Attribute::PublicExponent(exponent)
}
_ => unreachable!(),
}
})
})
}
AttributeType::NeverExtractable => Some(Attribute::NeverExtractable(true)),
AttributeType::Private => Some(Attribute::Private(true)),
AttributeType::PublicExponent => {
let public_exponent = private_key
.find_public_key(backend())
.ok()
.flatten()
.and_then(|public_key| {
let der = public_key.to_der();
RsaPublicKey::from_der(&der)
.map(|pk| pk.public_exponent.as_bytes().to_vec())
.ok()
});
public_exponent.map(Attribute::PublicExponent)
}
AttributeType::Sensitive => Some(Attribute::Sensitive(true)),
AttributeType::Sign => Some(Attribute::Sign(true)),
AttributeType::SignRecover => Some(Attribute::SignRecover(false)),
Expand All @@ -162,33 +205,42 @@ impl Object {
},
Object::PublicKey(pk) => match type_ {
AttributeType::Class => Some(Attribute::Class(CKO_PUBLIC_KEY)),
AttributeType::Verify => Some(Attribute::Verify(true)),
AttributeType::VerifyRecover => Some(Attribute::VerifyRecover(false)),
AttributeType::Wrap => Some(Attribute::Wrap(false)),
AttributeType::Encrypt => Some(Attribute::Encrypt(false)),
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added some missed attributes with default values that pkcs11-tool/p11-kit tools complains about.

AttributeType::Derive => Some(Attribute::Derive(false)),
AttributeType::Label => Some(Attribute::Label(pk.label())),
AttributeType::Local => Some(Attribute::Local(false)),
AttributeType::Modulus => {
let key = pk.to_der();
let key = RsaPublicKey::from_der(&key).unwrap();
Some(Attribute::Modulus(key.modulus.as_bytes().to_vec()))
}
AttributeType::PublicExponent => {
let key = pk.to_der();
let key = RsaPublicKey::from_der(&key).unwrap();
Some(Attribute::Modulus(key.public_exponent.as_bytes().to_vec()))
AttributeType::Modulus
| AttributeType::ModulusBits
| AttributeType::PublicExponent => {
if pk.algorithm() != KeyAlgorithm::Rsa {
return None;
}
let der_bytes = pk.to_der();
extract_rsa_params(&der_bytes).map(|(modulus, exponent, bits)| match type_ {
AttributeType::Modulus => Attribute::Modulus(modulus),
AttributeType::ModulusBits => Attribute::ModulusBits(bits),
AttributeType::PublicExponent => Attribute::PublicExponent(exponent),
_ => unreachable!(),
})
}
AttributeType::KeyType => Some(Attribute::KeyType(match pk.algorithm() {
native_pkcs11_traits::KeyAlgorithm::Rsa => CKK_RSA,
native_pkcs11_traits::KeyAlgorithm::Ecc => CKK_EC,
})),
AttributeType::Id => Some(Attribute::Id(pk.public_key_hash())),
AttributeType::EcPoint => {
AttributeType::EcParams | AttributeType::EcPoint => {
if pk.algorithm() != KeyAlgorithm::Ecc {
return None;
}
let wrapped = OctetString::new(pk.to_der()).ok()?;
Some(Attribute::EcPoint(wrapped.to_der().ok()?))
}
AttributeType::EcParams => {
Some(Attribute::EcParams(p256::NistP256::OID.to_der().ok()?))
let der_bytes = pk.to_der();
extract_ec_params(&der_bytes).map(|(params, point)| match type_ {
AttributeType::EcParams => Attribute::EcParams(params),
AttributeType::EcPoint => Attribute::EcPoint(point),
_ => unreachable!(),
})
}
_ => {
debug!("public_key: type_ unimplemented: {:?}", type_);
Expand Down
2 changes: 1 addition & 1 deletion native-pkcs11-traits/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ use std::{
use x509_cert::der::Decode;

pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub type Digest = [u8; 20];
pub type Digest = [u8; 64];
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was small to fit ECC P-256 digest value


// The Backend is first staged so it can be stored in a Box<dyn Backend>. This
// allows the Backend to be reference with `&'static`.
Expand Down
1 change: 1 addition & 0 deletions native-pkcs11/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ license.workspace = true
custom-function-list = []

[dependencies]
ctor = { version = "0.2" }
cached = { version = "~0.54", default-features = false }
native-pkcs11-core = { version = "^0.2.14", path = "../native-pkcs11-core" }
native-pkcs11-traits = { version = "0.2.0", path = "../native-pkcs11-traits" }
Expand Down
Loading