feat: init commit,fork from google native-pkcs11

This commit is contained in:
2024-07-06 19:06:25 +08:00
parent 27039d66bb
commit 33f33d2aa6
43 changed files with 34868 additions and 10 deletions

View File

@@ -0,0 +1,377 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{collections::BTreeSet, ffi::CString};
use pkcs11_sys::*;
use strum_macros::Display;
use crate::{Error, Result};
#[derive(Debug, Display, PartialEq, Eq)]
pub enum AttributeType {
AlwaysAuthenticate,
AlwaysSensitive,
Application,
CertificateCategory,
CertificateType,
Class,
Coefficient,
Decrypt,
EcParams,
EcPoint,
Encrypt,
Exponent1,
Exponent2,
Extractable,
Id,
Issuer,
KeyType,
Label,
Modulus,
ModulusBits,
NeverExtractable,
Prime1,
Prime2,
Private,
PrivateExponent,
ProfileId,
PublicExponent,
Sensitive,
SerialNumber,
Sign,
SignRecover,
Subject,
Token,
Trusted,
Unwrap,
Value,
ValueLen,
Verify,
VerifyRecover,
Wrap,
}
impl TryFrom<CK_ATTRIBUTE_TYPE> for AttributeType {
type Error = Error;
fn try_from(type_: CK_ATTRIBUTE_TYPE) -> Result<Self> {
match type_ {
CKA_ALWAYS_AUTHENTICATE => Ok(AttributeType::AlwaysAuthenticate),
CKA_ALWAYS_SENSITIVE => Ok(AttributeType::AlwaysSensitive),
CKA_APPLICATION => Ok(AttributeType::Application),
CKA_CERTIFICATE_CATEGORY => Ok(AttributeType::CertificateCategory),
CKA_CERTIFICATE_TYPE => Ok(AttributeType::CertificateType),
CKA_CLASS => Ok(AttributeType::Class),
CKA_COEFFICIENT => Ok(AttributeType::Coefficient),
CKA_DECRYPT => Ok(AttributeType::Decrypt),
CKA_EC_PARAMS => Ok(AttributeType::EcParams),
CKA_EC_POINT => Ok(AttributeType::EcPoint),
CKA_ENCRYPT => Ok(AttributeType::Encrypt),
CKA_EXPONENT_1 => Ok(AttributeType::Exponent1),
CKA_EXPONENT_2 => Ok(AttributeType::Exponent2),
CKA_EXTRACTABLE => Ok(AttributeType::Extractable),
CKA_ID => Ok(AttributeType::Id),
CKA_ISSUER => Ok(AttributeType::Issuer),
CKA_KEY_TYPE => Ok(AttributeType::KeyType),
CKA_LABEL => Ok(AttributeType::Label),
CKA_MODULUS => Ok(AttributeType::Modulus),
CKA_MODULUS_BITS => Ok(AttributeType::ModulusBits),
CKA_NEVER_EXTRACTABLE => Ok(AttributeType::NeverExtractable),
CKA_PRIME_1 => Ok(AttributeType::Prime1),
CKA_PRIME_2 => Ok(AttributeType::Prime2),
CKA_PRIVATE => Ok(AttributeType::Private),
CKA_PRIVATE_EXPONENT => Ok(AttributeType::PrivateExponent),
CKA_PROFILE_ID => Ok(AttributeType::ProfileId),
CKA_PUBLIC_EXPONENT => Ok(AttributeType::PublicExponent),
CKA_SENSITIVE => Ok(AttributeType::Sensitive),
CKA_SIGN => Ok(AttributeType::Sign),
CKA_SIGN_RECOVER => Ok(AttributeType::SignRecover),
CKA_SERIAL_NUMBER => Ok(AttributeType::SerialNumber),
CKA_SUBJECT => Ok(AttributeType::Subject),
CKA_TOKEN => Ok(AttributeType::Token),
CKA_TRUSTED => Ok(AttributeType::Trusted),
CKA_UNWRAP => Ok(AttributeType::Unwrap),
CKA_VALUE => Ok(AttributeType::Value),
CKA_VALUE_LEN => Ok(AttributeType::ValueLen),
CKA_VERIFY => Ok(AttributeType::Verify),
CKA_VERIFY_RECOVER => Ok(AttributeType::VerifyRecover),
CKA_WRAP => Ok(AttributeType::Wrap),
_ => Err(Error::AttributeTypeInvalid(type_)),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Attribute {
AlwaysAuthenticate(bool),
AlwaysSensitive(bool),
Application(CString),
CertificateCategory(CK_CERTIFICATE_CATEGORY),
CertificateType(CK_CERTIFICATE_TYPE),
Class(CK_OBJECT_CLASS),
Coefficient(Vec<u8>),
Decrypt(bool),
EcParams(Vec<u8>),
EcPoint(Vec<u8>),
Encrypt(bool),
Exponent1(Vec<u8>),
Exponent2(Vec<u8>),
Extractable(bool),
Id(Vec<u8>),
Issuer(Vec<u8>),
KeyType(CK_KEY_TYPE),
Label(String),
Modulus(Vec<u8>),
ModulusBits(CK_ULONG),
NeverExtractable(bool),
Prime1(Vec<u8>),
Prime2(Vec<u8>),
Private(bool),
PrivateExponent(Vec<u8>),
ProfileId(CK_PROFILE_ID),
PublicExponent(Vec<u8>),
Sensitive(bool),
SerialNumber(Vec<u8>),
Sign(bool),
SignRecover(bool),
Subject(Vec<u8>),
Token(bool),
Trusted(bool),
Unwrap(bool),
Value(Vec<u8>),
ValueLen(CK_ULONG),
Verify(bool),
VerifyRecover(bool),
Wrap(bool),
}
impl Attribute {
pub fn attribute_type(&self) -> AttributeType {
match self {
Attribute::AlwaysAuthenticate(_) => AttributeType::AlwaysAuthenticate,
Attribute::AlwaysSensitive(_) => AttributeType::AlwaysSensitive,
Attribute::Application(_) => AttributeType::Application,
Attribute::CertificateCategory(_) => AttributeType::CertificateCategory,
Attribute::CertificateType(_) => AttributeType::CertificateType,
Attribute::Class(_) => AttributeType::Class,
Attribute::Coefficient(_) => AttributeType::Coefficient,
Attribute::Decrypt(_) => AttributeType::Decrypt,
Attribute::EcParams(_) => AttributeType::EcParams,
Attribute::EcPoint(_) => AttributeType::EcPoint,
Attribute::Encrypt(_) => AttributeType::Encrypt,
Attribute::Exponent1(_) => AttributeType::Exponent1,
Attribute::Exponent2(_) => AttributeType::Exponent2,
Attribute::Extractable(_) => AttributeType::Extractable,
Attribute::Id(_) => AttributeType::Id,
Attribute::Issuer(_) => AttributeType::Issuer,
Attribute::KeyType(_) => AttributeType::KeyType,
Attribute::Label(_) => AttributeType::Label,
Attribute::Modulus(_) => AttributeType::Modulus,
Attribute::ModulusBits(_) => AttributeType::ModulusBits,
Attribute::NeverExtractable(_) => AttributeType::NeverExtractable,
Attribute::Prime1(_) => AttributeType::Prime1,
Attribute::Prime2(_) => AttributeType::Prime2,
Attribute::Private(_) => AttributeType::Private,
Attribute::PrivateExponent(_) => AttributeType::PrivateExponent,
Attribute::ProfileId(_) => AttributeType::ProfileId,
Attribute::PublicExponent(_) => AttributeType::PublicExponent,
Attribute::Sensitive(_) => AttributeType::Sensitive,
Attribute::SerialNumber(_) => AttributeType::SerialNumber,
Attribute::Sign(_) => AttributeType::Sign,
Attribute::SignRecover(_) => AttributeType::SignRecover,
Attribute::Subject(_) => AttributeType::Subject,
Attribute::Token(_) => AttributeType::Token,
Attribute::Trusted(_) => AttributeType::Trusted,
Attribute::Unwrap(_) => AttributeType::Unwrap,
Attribute::Value(_) => AttributeType::Value,
Attribute::ValueLen(_) => AttributeType::ValueLen,
Attribute::Verify(_) => AttributeType::Verify,
Attribute::VerifyRecover(_) => AttributeType::VerifyRecover,
Attribute::Wrap(_) => AttributeType::Wrap,
}
}
pub fn as_raw_value(&self) -> Vec<u8> {
match self {
Attribute::AlwaysAuthenticate(bool)
| Attribute::AlwaysSensitive(bool)
| Attribute::Decrypt(bool)
| Attribute::Encrypt(bool)
| Attribute::Extractable(bool)
| Attribute::NeverExtractable(bool)
| Attribute::Private(bool)
| Attribute::Sensitive(bool)
| Attribute::Sign(bool)
| Attribute::SignRecover(bool)
| Attribute::Token(bool)
| Attribute::Trusted(bool)
| Attribute::Unwrap(bool)
| Attribute::Verify(bool)
| Attribute::VerifyRecover(bool)
| Attribute::Wrap(bool) => {
CK_BBOOL::to_ne_bytes(if *bool { CK_TRUE } else { CK_FALSE }).to_vec()
}
Attribute::CertificateCategory(int)
| Attribute::CertificateType(int)
| Attribute::Class(int)
| Attribute::KeyType(int)
| Attribute::ModulusBits(int)
| Attribute::ProfileId(int)
| Attribute::ValueLen(int) => int.to_ne_bytes().to_vec(),
Attribute::Coefficient(bytes)
| Attribute::EcParams(bytes)
| Attribute::EcPoint(bytes)
| Attribute::Exponent1(bytes)
| Attribute::Exponent2(bytes)
| Attribute::Id(bytes)
| Attribute::Issuer(bytes)
| Attribute::Modulus(bytes)
| Attribute::Prime1(bytes)
| Attribute::Prime2(bytes)
| Attribute::PrivateExponent(bytes)
| Attribute::PublicExponent(bytes)
| Attribute::SerialNumber(bytes)
| Attribute::Subject(bytes)
| Attribute::Value(bytes) => bytes.to_vec(),
Attribute::Application(c_string) => c_string.as_bytes().to_vec(),
Attribute::Label(string) => string.as_bytes().to_vec(),
}
}
}
impl TryFrom<CK_ATTRIBUTE> for Attribute {
type Error = Error;
fn try_from(attribute: CK_ATTRIBUTE) -> Result<Self> {
let attr_type = AttributeType::try_from(attribute.type_)?;
let val = if attribute.ulValueLen > 0 {
if attribute.pValue.is_null() {
return Err(Error::NullPtr);
}
unsafe {
std::slice::from_raw_parts(
attribute.pValue as *const u8,
attribute.ulValueLen.try_into()?,
)
}
} else {
&[]
};
match attr_type {
AttributeType::AlwaysAuthenticate => {
Ok(Attribute::AlwaysAuthenticate(try_u8_into_bool(val)?))
}
AttributeType::AlwaysSensitive => {
Ok(Attribute::AlwaysSensitive(try_u8_into_bool(val)?))
}
AttributeType::Application => Ok(Attribute::Application(CString::from_vec_with_nul(
val.to_vec(),
)?)),
AttributeType::CertificateCategory => Ok(Attribute::CertificateCategory(
CK_CERTIFICATE_CATEGORY::from_ne_bytes(val.try_into()?),
)),
AttributeType::CertificateType => Ok(Attribute::CertificateType(
CK_CERTIFICATE_TYPE::from_ne_bytes(val.try_into()?),
)),
AttributeType::Class => Ok(Attribute::Class(CK_OBJECT_CLASS::from_ne_bytes(
val.try_into()?,
))),
AttributeType::Coefficient => Ok(Attribute::Coefficient(val.to_vec())),
AttributeType::Decrypt => Ok(Attribute::Decrypt(try_u8_into_bool(val)?)),
AttributeType::EcParams => Ok(Attribute::EcParams(val.to_vec())),
AttributeType::EcPoint => Ok(Attribute::EcPoint(val.to_vec())),
AttributeType::Encrypt => Ok(Attribute::Encrypt(try_u8_into_bool(val)?)),
AttributeType::Exponent1 => Ok(Attribute::Exponent1(val.to_vec())),
AttributeType::Exponent2 => Ok(Attribute::Exponent2(val.to_vec())),
AttributeType::Extractable => Ok(Attribute::Extractable(try_u8_into_bool(val)?)),
AttributeType::Id => Ok(Attribute::Id(val.to_vec())),
AttributeType::Issuer => Ok(Attribute::Issuer(val.to_vec())),
AttributeType::KeyType => Ok(Attribute::KeyType(CK_KEY_TYPE::from_ne_bytes(
val.try_into()?,
))),
AttributeType::Label => Ok(Attribute::Label(String::from_utf8(val.to_vec())?)),
AttributeType::Modulus => Ok(Attribute::Modulus(val.to_vec())),
AttributeType::ModulusBits => Ok(Attribute::ModulusBits(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::NeverExtractable => {
Ok(Attribute::NeverExtractable(try_u8_into_bool(val)?))
}
AttributeType::Prime1 => Ok(Attribute::Prime1(val.to_vec())),
AttributeType::Prime2 => Ok(Attribute::Prime2(val.to_vec())),
AttributeType::Private => Ok(Attribute::Private(try_u8_into_bool(val)?)),
AttributeType::PrivateExponent => Ok(Attribute::PrivateExponent(val.to_vec())),
AttributeType::ProfileId => Ok(Attribute::ProfileId(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::PublicExponent => Ok(Attribute::PublicExponent(val.to_vec())),
AttributeType::Sensitive => Ok(Attribute::Sensitive(try_u8_into_bool(val)?)),
AttributeType::SerialNumber => Ok(Attribute::SerialNumber(val.to_vec())),
AttributeType::Subject => Ok(Attribute::Subject(val.to_vec())),
AttributeType::Sign => Ok(Attribute::Sign(try_u8_into_bool(val)?)),
AttributeType::SignRecover => Ok(Attribute::SignRecover(try_u8_into_bool(val)?)),
AttributeType::Token => Ok(Attribute::Token(try_u8_into_bool(val)?)),
AttributeType::Trusted => Ok(Attribute::Trusted(try_u8_into_bool(val)?)),
AttributeType::Unwrap => Ok(Attribute::Unwrap(try_u8_into_bool(val)?)),
AttributeType::Value => Ok(Attribute::Value(val.to_vec())),
AttributeType::ValueLen => Ok(Attribute::ValueLen(CK_ULONG::from_ne_bytes(
val.try_into()?,
))),
AttributeType::Verify => Ok(Attribute::Verify(try_u8_into_bool(val)?)),
AttributeType::VerifyRecover => Ok(Attribute::VerifyRecover(try_u8_into_bool(val)?)),
AttributeType::Wrap => Ok(Attribute::Wrap(try_u8_into_bool(val)?)),
}
}
}
// Borrowed from:
// https://github.com/parallaxsecond/rust-cryptoki/blob/89055f2a30e30d07a99e5904e9231d743c75d8e5/cryptoki/src/object.rs#L769
fn try_u8_into_bool(slice: &[u8]) -> Result<bool> {
let as_array: [u8; std::mem::size_of::<CK_BBOOL>()] = slice.try_into()?;
let as_byte = CK_BBOOL::from_ne_bytes(as_array);
Ok(!matches!(as_byte, 0u8))
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Attributes(BTreeSet<Attribute>);
impl Attributes {
pub fn get(&self, type_: AttributeType) -> Option<&Attribute> {
self.0.iter().find(|&attr| attr.attribute_type() == type_)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<'a> IntoIterator for &'a Attributes {
type Item = &'a Attribute;
type IntoIter = std::collections::btree_set::Iter<'a, Attribute>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl From<Vec<Attribute>> for Attributes {
fn from(value: Vec<Attribute>) -> Self {
Attributes(BTreeSet::from_iter(value))
}
}

View File

@@ -0,0 +1,141 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use attribute::AttributeType;
use pkcs11_sys::*;
use thiserror::Error;
pub mod attribute;
pub mod mechanism;
pub mod object;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Error, Debug)]
pub enum Error {
// Cryptoki errors.
#[error("arguments bad")]
ArgumentsBad,
#[error("{0} is not a valid attribute type")]
AttributeTypeInvalid(CK_ATTRIBUTE_TYPE),
#[error("the value for attribute {0} is invalid")]
AttributeValueInvalid(AttributeType),
#[error("buffer too small")]
BufferTooSmall,
#[error("cryptoki module has already been initialized")]
CryptokiAlreadyInitialized,
#[error("cryptoki module has not been initialized")]
CryptokiNotInitialized,
#[error("function not parallel")]
FunctionNotParallel,
#[error("function not supported")]
FunctionNotSupported,
#[error("key handle {0} is invalid")]
KeyHandleInvalid(CK_OBJECT_HANDLE),
#[error("module cannot function without being able to spawn threads")]
NeedToCreateThreads,
#[error("{0} is not a valid mechanism")]
MechanismInvalid(CK_MECHANISM_TYPE),
#[error("object {0} is invalid")]
ObjectHandleInvalid(CK_OBJECT_HANDLE),
#[error("operation has not been initialized")]
OperationNotInitialized,
#[error("no random number generator")]
RandomNoRng,
#[error("session handle {0} is invalid")]
SessionHandleInvalid(CK_SESSION_HANDLE),
#[error("token does not support parallel sessions")]
SessionParallelNotSupported,
#[error("slot id {0} is invalid")]
SlotIdInvalid(CK_SLOT_ID),
#[error("token is write protected")]
TokenWriteProtected,
// Other errors.
#[error("{0}")]
FromUtf8(#[from] std::string::FromUtf8Error),
#[error("{0}")]
FromVecWithNul(#[from] std::ffi::FromVecWithNulError),
#[error("null pointer error")]
NullPtr,
#[error("{0}")]
Pkcs11Piv(#[from] native_pkcs11_piv::Error),
#[error("{0}")]
TryFromInt(#[from] std::num::TryFromIntError),
#[error("{0}")]
TryFromSlice(#[from] std::array::TryFromSliceError),
// Catch-all for backend-related errors.
#[error("{0}")]
Backend(#[from] Box<dyn std::error::Error>),
#[error("{0}")]
Todo(String),
}
impl From<Error> for CK_RV {
fn from(e: Error) -> Self {
match e {
Error::ArgumentsBad => CKR_ARGUMENTS_BAD,
Error::AttributeTypeInvalid(_) => CKR_ATTRIBUTE_TYPE_INVALID,
Error::AttributeValueInvalid(_) => CKR_ATTRIBUTE_VALUE_INVALID,
Error::BufferTooSmall => CKR_BUFFER_TOO_SMALL,
Error::CryptokiAlreadyInitialized => CKR_CRYPTOKI_ALREADY_INITIALIZED,
Error::CryptokiNotInitialized => CKR_CRYPTOKI_NOT_INITIALIZED,
Error::FunctionNotParallel => CKR_FUNCTION_NOT_PARALLEL,
Error::FunctionNotSupported => CKR_FUNCTION_NOT_SUPPORTED,
Error::KeyHandleInvalid(_) => CKR_KEY_HANDLE_INVALID,
Error::MechanismInvalid(_) => CKR_MECHANISM_INVALID,
Error::NeedToCreateThreads => CKR_NEED_TO_CREATE_THREADS,
Error::ObjectHandleInvalid(_) => CKR_OBJECT_HANDLE_INVALID,
Error::OperationNotInitialized => CKR_OPERATION_NOT_INITIALIZED,
Error::RandomNoRng => CKR_RANDOM_NO_RNG,
Error::SessionHandleInvalid(_) => CKR_SESSION_HANDLE_INVALID,
Error::SessionParallelNotSupported => CKR_SESSION_PARALLEL_NOT_SUPPORTED,
Error::SlotIdInvalid(_) => CKR_SLOT_ID_INVALID,
Error::TokenWriteProtected => CKR_TOKEN_WRITE_PROTECTED,
Error::Backend(_)
| Error::FromUtf8(_)
| Error::FromVecWithNul(_)
| Error::NullPtr
| Error::Todo(_)
| Error::TryFromInt(_)
| Error::TryFromSlice(_) => CKR_GENERAL_ERROR,
Error::Pkcs11Piv(_) => CKR_GENERAL_ERROR,
}
}
}

View File

@@ -0,0 +1,147 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use native_pkcs11_traits::{DigestType, SignatureAlgorithm};
use pkcs11_sys::*;
use crate::Error;
pub const SUPPORTED_SIGNATURE_MECHANISMS: &[CK_MECHANISM_TYPE] = &[
CKM_RSA_PKCS,
CKM_SHA1_RSA_PKCS,
CKM_SHA256_RSA_PKCS,
CKM_SHA384_RSA_PKCS,
CKM_SHA512_RSA_PKCS,
CKM_ECDSA,
CKM_RSA_PKCS_PSS,
];
pub enum Mechanism {
Ecdsa,
RsaPkcs,
RsaPkcsSha1,
RsaPkcsSha256,
RsaPkcsSha384,
RsaPkcsSha512,
RsaPss {
digest_algorithm: native_pkcs11_traits::DigestType,
mask_generation_function: native_pkcs11_traits::DigestType,
salt_length: u64,
},
}
#[allow(clippy::missing_safety_doc)]
pub unsafe fn parse_mechanism(mechanism: CK_MECHANISM) -> Result<Mechanism, Error> {
match mechanism.mechanism {
CKM_ECDSA => Ok(Mechanism::Ecdsa),
CKM_RSA_PKCS => Ok(Mechanism::RsaPkcs),
CKM_SHA1_RSA_PKCS => Ok(Mechanism::RsaPkcsSha1),
CKM_SHA256_RSA_PKCS => Ok(Mechanism::RsaPkcsSha256),
CKM_SHA384_RSA_PKCS => Ok(Mechanism::RsaPkcsSha384),
CKM_SHA512_RSA_PKCS => Ok(Mechanism::RsaPkcsSha512),
CKM_RSA_PKCS_PSS => {
// Bind to locals to prevent unaligned reads https://github.com/rust-lang/rust/issues/82523
let mechanism_type = mechanism.mechanism;
let parameter_ptr = mechanism.pParameter;
let parameter_len = mechanism.ulParameterLen;
if parameter_ptr.is_null() {
tracing::error!("pParameter null");
return Err(Error::MechanismInvalid(mechanism_type));
}
if (parameter_len as usize) != std::mem::size_of::<CK_RSA_PKCS_PSS_PARAMS>() {
tracing::error!(
"pParameter incorrect: {} != {}",
parameter_len,
std::mem::size_of::<CK_RSA_PKCS_PSS_PARAMS>()
);
return Err(Error::MechanismInvalid(mechanism_type));
}
// TODO(kcking): check alignment as well?
let params: CK_RSA_PKCS_PSS_PARAMS =
unsafe { (parameter_ptr as *mut CK_RSA_PKCS_PSS_PARAMS).read() };
let mgf = params.mgf;
let hash_alg = params.hashAlg;
let salt_len = params.sLen;
let mgf = match mgf {
CKG_MGF1_SHA1 => DigestType::Sha1,
CKG_MGF1_SHA224 => DigestType::Sha224,
CKG_MGF1_SHA256 => DigestType::Sha256,
CKG_MGF1_SHA384 => DigestType::Sha384,
CKG_MGF1_SHA512 => DigestType::Sha512,
_ => {
tracing::error!("Unsupported mgf: {}", mgf);
return Err(Error::MechanismInvalid(mechanism_type));
}
};
let hash_alg = match hash_alg {
CKM_SHA_1 => DigestType::Sha1,
CKM_SHA224 => DigestType::Sha224,
CKM_SHA256 => DigestType::Sha256,
CKM_SHA384 => DigestType::Sha384,
CKM_SHA512 => DigestType::Sha512,
_ => {
tracing::error!("Unsupported hashAlg: {}", hash_alg);
return Err(Error::MechanismInvalid(mechanism_type));
}
};
#[allow(clippy::unnecessary_cast)]
Ok(Mechanism::RsaPss {
digest_algorithm: hash_alg,
mask_generation_function: mgf,
// Cast needed on windows
salt_length: salt_len as u64,
})
}
_ => Err(Error::MechanismInvalid(mechanism.mechanism)),
}
}
impl From<Mechanism> for CK_MECHANISM_TYPE {
fn from(mechanism: Mechanism) -> Self {
match mechanism {
Mechanism::Ecdsa => CKM_ECDSA,
Mechanism::RsaPkcs => CKM_RSA_PKCS,
Mechanism::RsaPkcsSha1 => CKM_SHA1_RSA_PKCS,
Mechanism::RsaPkcsSha256 => CKM_SHA256_RSA_PKCS,
Mechanism::RsaPkcsSha384 => CKM_SHA384_RSA_PKCS,
Mechanism::RsaPkcsSha512 => CKM_SHA512_RSA_PKCS,
Mechanism::RsaPss { .. } => CKM_RSA_PKCS_PSS,
}
}
}
impl From<Mechanism> for SignatureAlgorithm {
fn from(mechanism: Mechanism) -> Self {
match mechanism {
Mechanism::Ecdsa => SignatureAlgorithm::Ecdsa,
Mechanism::RsaPkcs => SignatureAlgorithm::RsaPkcs1v15Raw,
Mechanism::RsaPkcsSha1 => SignatureAlgorithm::RsaPkcs1v15Sha1,
Mechanism::RsaPkcsSha256 => SignatureAlgorithm::RsaPkcs1v15Sha256,
Mechanism::RsaPkcsSha384 => SignatureAlgorithm::RsaPkcs1v15Sha384,
Mechanism::RsaPkcsSha512 => SignatureAlgorithm::RsaPkcs1v15Sha512,
Mechanism::RsaPss {
digest_algorithm,
mask_generation_function,
salt_length,
} => SignatureAlgorithm::RsaPss {
digest: digest_algorithm,
mask_generation_function,
salt_length,
},
}
}
}

View File

@@ -0,0 +1,214 @@
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::{ffi::CString, fmt::Debug, sync::Arc};
use native_pkcs11_traits::{
backend,
Certificate,
CertificateExt,
KeyAlgorithm,
PrivateKey,
PublicKey,
};
use p256::pkcs8::{
der::{asn1::OctetString, Encode},
AssociatedOid,
};
use pkcs1::{der::Decode, RsaPublicKey};
use pkcs11_sys::{
CKC_X_509,
CKK_EC,
CKK_RSA,
CKO_CERTIFICATE,
CKO_PRIVATE_KEY,
CKO_PROFILE,
CKO_PUBLIC_KEY,
CK_CERTIFICATE_CATEGORY_UNSPECIFIED,
CK_PROFILE_ID,
};
use tracing::debug;
use crate::attribute::{Attribute, AttributeType, Attributes};
#[derive(Debug)]
pub struct DataObject {
pub application: CString,
pub label: String,
pub value: Vec<u8>,
}
// Usage of generics is a workaround for the following issue:
// https://github.com/rust-lang/rust/issues/78808#issuecomment-1664416547
#[derive(Debug, PartialEq, Hash, Eq)]
pub enum Object<
DynCertificate: ?Sized + PartialEq = dyn Certificate,
DynPrivateKey: ?Sized + PartialEq = dyn PrivateKey,
DynPublicKey: ?Sized + PartialEq = dyn PublicKey,
> {
Certificate(Arc<DynCertificate>),
PrivateKey(Arc<DynPrivateKey>),
Profile(CK_PROFILE_ID),
PublicKey(Arc<DynPublicKey>),
}
impl Clone for Object {
fn clone(&self) -> Self {
match self {
Object::Certificate(cert) => Object::Certificate(cert.clone()),
Object::PrivateKey(private_key) => Object::PrivateKey(private_key.clone()),
Object::Profile(id) => Object::Profile(*id),
Object::PublicKey(public_key) => Object::PublicKey(public_key.clone()),
}
}
}
impl Object {
pub fn attribute(&self, type_: AttributeType) -> Option<Attribute> {
match self {
Object::Certificate(cert) => match type_ {
AttributeType::CertificateCategory => Some(Attribute::CertificateCategory(
CK_CERTIFICATE_CATEGORY_UNSPECIFIED,
)),
AttributeType::CertificateType => Some(Attribute::CertificateType(CKC_X_509)),
AttributeType::Class => Some(Attribute::Class(CKO_CERTIFICATE)),
AttributeType::Id => Some(Attribute::Id(cert.public_key().public_key_hash())),
AttributeType::Issuer => Some(Attribute::Issuer(cert.issuer())),
AttributeType::Label => Some(Attribute::Label(cert.label())),
AttributeType::Token => Some(Attribute::Token(true)),
AttributeType::Trusted => Some(Attribute::Trusted(false)),
AttributeType::SerialNumber => Some(Attribute::SerialNumber(cert.serial_number())),
AttributeType::Subject => Some(Attribute::Subject(cert.subject())),
AttributeType::Value => Some(Attribute::Value(cert.to_der())),
_ => {
debug!("certificate: type_ unimplemented: {:?}", type_);
None
}
},
Object::PrivateKey(private_key) => match type_ {
AttributeType::AlwaysSensitive => Some(Attribute::AlwaysSensitive(true)),
AttributeType::AlwaysAuthenticate => Some(Attribute::AlwaysAuthenticate(false)),
AttributeType::Class => Some(Attribute::Class(CKO_PRIVATE_KEY)),
AttributeType::Decrypt => Some(Attribute::Decrypt(false)),
AttributeType::EcParams => {
Some(Attribute::EcParams(p256::NistP256::OID.to_der().ok()?))
}
AttributeType::Extractable => Some(Attribute::Extractable(false)),
AttributeType::Id => Some(Attribute::Id(private_key.public_key_hash())),
AttributeType::KeyType => Some(Attribute::KeyType(match private_key.algorithm() {
native_pkcs11_traits::KeyAlgorithm::Rsa => CKK_RSA,
native_pkcs11_traits::KeyAlgorithm::Ecc => CKK_EC,
})),
AttributeType::Label => Some(Attribute::Label(private_key.label())),
AttributeType::Modulus => {
let modulus = 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)
}
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)),
AttributeType::Token => Some(Attribute::Token(true)),
AttributeType::Unwrap => Some(Attribute::Unwrap(false)),
_ => {
debug!("private_key: type_ unimplemented: {:?}", type_);
None
}
},
Object::Profile(id) => match type_ {
AttributeType::Class => Some(Attribute::Class(CKO_PROFILE)),
AttributeType::ProfileId => Some(Attribute::ProfileId(*id)),
AttributeType::Token => Some(Attribute::Token(true)),
_ => {
debug!("profile: type_ unimplemented: {:?}", type_);
None
}
},
Object::PublicKey(pk) => match type_ {
AttributeType::Class => Some(Attribute::Class(CKO_PUBLIC_KEY)),
AttributeType::Label => Some(Attribute::Label(pk.label())),
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::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 => {
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()?))
}
_ => {
debug!("public_key: type_ unimplemented: {:?}", type_);
None
}
},
}
}
pub fn matches(&self, others: &Attributes) -> bool {
if let Some(class) = others.get(AttributeType::Class) {
if *class != self.attribute(AttributeType::Class).unwrap() {
return false;
}
}
for other in others {
if let Some(attr) = self.attribute(other.attribute_type()) {
if *other != attr {
return false;
}
} else {
return false;
}
}
true
}
}