feat: init commit,fork from google native-pkcs11
This commit is contained in:
28
native-pkcs11-core/Cargo.toml
Normal file
28
native-pkcs11-core/Cargo.toml
Normal file
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "native-pkcs11-core"
|
||||
version = "0.2.18"
|
||||
description = "Shared cross-platform PKCS#11 module logic for native-pkcs11."
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
native-pkcs11-traits = { version = "0.2.0", path = "../native-pkcs11-traits" }
|
||||
once_cell = "1.19.0"
|
||||
p256 = { version = "0.13.2", default-features = false, features = [
|
||||
"arithmetic",
|
||||
"pkcs8",
|
||||
"std",
|
||||
] }
|
||||
pkcs1 = { version = "0.7.5", default-features = false }
|
||||
pkcs11-sys = { version = "0.2.0", path = "../pkcs11-sys" }
|
||||
strum = "0.26.3"
|
||||
strum_macros = "0.26.4"
|
||||
thiserror = "1.0.61"
|
||||
tracing = "0.1.40"
|
||||
native-pkcs11-piv = { version = "0.2.0", path = "../native-pkcs11-piv" }
|
||||
|
||||
[dev-dependencies]
|
||||
serial_test = { version = "3.1.1", default-features = false }
|
||||
201
native-pkcs11-core/LICENSE
Normal file
201
native-pkcs11-core/LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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.
|
||||
377
native-pkcs11-core/src/attribute.rs
Normal file
377
native-pkcs11-core/src/attribute.rs
Normal 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))
|
||||
}
|
||||
}
|
||||
141
native-pkcs11-core/src/lib.rs
Normal file
141
native-pkcs11-core/src/lib.rs
Normal 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
147
native-pkcs11-core/src/mechanism.rs
Normal file
147
native-pkcs11-core/src/mechanism.rs
Normal 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,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
214
native-pkcs11-core/src/object.rs
Normal file
214
native-pkcs11-core/src/object.rs
Normal 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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user