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

4
.gitignore vendored
View File

@@ -1,12 +1,10 @@
.idea/
# ---> Rust
# Generated by Cargo
# will have compiled files and executables
debug/
target/
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
Cargo.lock
# These are backup files generated by rustfmt
**/*.rs.bk

3
.gitmodules vendored Normal file
View File

@@ -0,0 +1,3 @@
[submodule "pkcs11test"]
path = pkcs11test
url = https://github.com/google/pkcs11test

1501
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

23
Cargo.toml Normal file
View File

@@ -0,0 +1,23 @@
[workspace]
resolver = "2"
members = [
"native-pkcs11",
"native-pkcs11-core",
"native-pkcs11-traits",
"native-pkcs11-piv",
"pkcs11-sys",
]
[workspace.package]
authors = [
"Brandon Weeks <bweeks@google.com>",
"Kevin King <kcking@google.com>",
]
edition = "2021"
rust-version = "1.65"
repository = "https://github.com/google/native-pkcs11"
license = "Apache-2.0"
[profile.release]
strip = "symbols"
panic = "abort"

202
LICENSE
View File

@@ -1,9 +1,201 @@
MIT License
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
Copyright (c) <year> <copyright holders>
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1. Definitions.
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"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.

View File

@@ -1,3 +1,5 @@
# yubikey-piv-pkcs11
Yubikey PIV PKCS#11
> Fork form: https://github.com/google/native-pkcs11
Yubikey PIV PKCS#11

29
deny.toml Normal file
View File

@@ -0,0 +1,29 @@
targets = [
{ triple = "aarch64-apple-darwin" },
{ triple = "x86_64-apple-darwin" },
{ triple = "x86_64-pc-windows-msvc" },
{ triple = "x86_64-unknown-linux-gnu" },
]
[advisories]
vulnerability = "deny"
unmaintained = "deny"
unsound = "deny"
yanked = "deny"
notice = "deny"
ignore = ["RUSTSEC-2023-0071"]
[licenses]
allow = ["Apache-2.0", "BSD-3-Clause", "ISC", "MIT", "Unicode-DFS-2016"]
copyleft = "deny"
[bans]
multiple-versions = "deny"
skip = [
{ name = "regex-automata", version = "=0.1.10" },
{ name = "regex-syntax", version = "=0.6.29" },
]
[sources]
unknown-registry = "deny"
unknown-git = "deny"

View 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
View 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.

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
}
}

View File

@@ -0,0 +1,35 @@
[package]
name = "native-pkcs11-piv"
version = "0.2.18"
description = "native-pkcs11 backend for macos keychain."
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" }
p256 = { version = "0.13.2", default-features = false, features = [
"arithmetic",
"pkcs8",
"std",
] }
rand = "0.8.5"
rsa = { version = "0.9.6", default-features = false, features = ["std"] }
# TODO: temporary workaround for RustCrypto/traits#1262, remove after upgrading
# the p256 package past 0.13.0.
spki = { version = "0.7.3", features = ["std"] }
thiserror = "1.0.61"
tracing = "0.1.40"
tracing-error = { version = "0.2.0", default-features = false }
x509-cert = { version = "0.2.5", default-features = false }
yubikey = { version = "0.8.0", features = ["untested"] }
[dev-dependencies]
serial_test = { version = "3.1.1", default-features = false }
[target.'cfg(target_os="macos")'.dependencies]
core-foundation = { version = "0.9.4", features = ["mac_os_10_8_features"] }
security-framework = { version = "2.11.0", features = ["OSX_10_15"] }
security-framework-sys = { version = "2.11.0", features = ["OSX_10_15"] }

201
native-pkcs11-piv/LICENSE Normal file
View 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.

View File

@@ -0,0 +1,19 @@
// 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.
/// Workaround for platform-specific crates in workspace root.
/// https://github.com/rust-lang/cargo/issues/5220
mod piv;
pub use piv::*;

View File

@@ -0,0 +1,189 @@
// 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::HashMap, sync::Arc};
use core_foundation::{
base::{TCFType, ToVoid},
string::CFString,
};
use native_pkcs11_traits::Backend;
use security_framework::{item::KeyClass, key::SecKey};
use security_framework_sys::item::kSecAttrLabel;
use tracing::instrument;
use crate::{
certificate::{find_all_certificates, YubikeyPivCertificate},
key::{
find_all_keys,
find_key,
find_key2,
generate_key,
Algorithm,
YubikeyPivPrivateKey,
YubikeyPivPublicKey,
},
keychain,
};
#[derive(Debug, Default)]
pub struct YubikeyPivBackend;
impl YubikeyPivBackend {
pub fn new() -> Self {
Self
}
}
impl Backend for YubikeyPivBackend {
fn name(&self) -> String {
"Keychain".into()
}
#[instrument]
fn find_all_certificates(
&self,
) -> native_pkcs11_traits::Result<Vec<Box<dyn native_pkcs11_traits::Certificate>>> {
let certs = find_all_certificates()?
.into_iter()
.map(YubikeyPivCertificate::new)
.filter_map(Result::ok)
.map(|cert| Box::new(cert) as _)
.collect();
Ok(certs)
}
#[instrument]
fn find_private_key(
&self,
query: native_pkcs11_traits::KeySearchOptions,
) -> native_pkcs11_traits::Result<Option<Arc<dyn native_pkcs11_traits::PrivateKey>>> {
let mut pubkeys_by_pubkey_hash: HashMap<Vec<u8>, SecKey> =
HashMap::from_iter(find_all_certificates()?.into_iter().filter_map(|c| {
c.certificate()
.ok()
.and_then(|cert| cert.public_key().ok())
.and_then(|pk| pk.application_label().map(|pubkey_hash| (pubkey_hash, pk)))
}));
let mut find_pubkey_for_seckey = |sec_key: &SecKey| -> Option<YubikeyPivPublicKey> {
sec_key
.application_label()
.and_then(|pubkey_hash| pubkeys_by_pubkey_hash.remove(&pubkey_hash))
// TODO(kcking): populate label if searching by label
.and_then(|sec_key| YubikeyPivPublicKey::new(sec_key, "").ok())
};
let opt_key = match query {
native_pkcs11_traits::KeySearchOptions::Label(label) => {
find_key(KeyClass::private(), &label)
.ok()
.map(|sec_key| {
let cert = find_pubkey_for_seckey(&sec_key);
YubikeyPivPrivateKey::new(sec_key, label, cert)
})
.transpose()?
}
native_pkcs11_traits::KeySearchOptions::PublicKeyHash(public_key_hash) => {
find_key2(KeyClass::private(), &public_key_hash)?
.map(|sec_key| {
let cert = find_pubkey_for_seckey(&sec_key);
YubikeyPivPrivateKey::new(sec_key, "", cert)
})
.transpose()?
}
};
Ok(opt_key.map(|sec_key| Arc::new(sec_key) as _))
}
#[instrument]
fn find_public_key(
&self,
query: native_pkcs11_traits::KeySearchOptions,
) -> native_pkcs11_traits::Result<Option<Box<dyn native_pkcs11_traits::PublicKey>>> {
let opt_key = match query {
native_pkcs11_traits::KeySearchOptions::Label(label) => {
find_key(KeyClass::public(), &label)
.ok()
.map(|sec_key| YubikeyPivPublicKey::new(sec_key, label))
.transpose()?
}
native_pkcs11_traits::KeySearchOptions::PublicKeyHash(public_key_hash) => {
find_key2(KeyClass::public(), &public_key_hash)?
.map(|sec_key| YubikeyPivPublicKey::new(sec_key, ""))
.transpose()?
}
};
Ok(opt_key.map(|sec_key| Box::new(sec_key) as _))
}
#[instrument]
fn generate_key(
&self,
algorithm: native_pkcs11_traits::KeyAlgorithm,
label: Option<&str>,
) -> native_pkcs11_traits::Result<Arc<dyn native_pkcs11_traits::PrivateKey>> {
let alg = match algorithm {
native_pkcs11_traits::KeyAlgorithm::Rsa => Algorithm::RSA,
native_pkcs11_traits::KeyAlgorithm::Ecc => Algorithm::ECC,
};
let label = label.unwrap_or("");
Ok(generate_key(alg, label, Some(keychain::location()?))
.map(|key| YubikeyPivPrivateKey::new(key, label, None).map(Arc::new))??)
}
fn find_all_private_keys(
&self,
) -> native_pkcs11_traits::Result<Vec<Arc<dyn native_pkcs11_traits::PrivateKey>>> {
let sec_keys = find_all_keys(KeyClass::private())?;
let keys = sec_keys
.into_iter()
.filter_map(|sec_key| {
let label: Option<String> = sec_key
.attributes()
.find(unsafe { kSecAttrLabel }.to_void())
.map(|label| {
unsafe { CFString::wrap_under_get_rule(label.cast()) }.to_string()
});
let label: String = label.unwrap_or_default();
YubikeyPivPrivateKey::new(sec_key, label, None).ok()
})
.map(|k| Arc::new(k) as _);
Ok(keys.collect())
}
fn find_all_public_keys(
&self,
) -> native_pkcs11_traits::Result<Vec<Arc<dyn native_pkcs11_traits::PublicKey>>> {
let sec_keys = find_all_keys(KeyClass::public())?;
let keys = sec_keys
.into_iter()
.filter_map(|sec_key| {
let label: Option<String> = sec_key
.attributes()
.find(unsafe { kSecAttrLabel }.to_void())
.map(|label| {
unsafe { CFString::wrap_under_get_rule(label.cast()) }.to_string()
});
let label: String = label.unwrap_or_default();
YubikeyPivPublicKey::new(sec_key, label).ok()
})
.map(|k| Arc::new(k) as _);
Ok(keys.collect())
}
}

View File

@@ -0,0 +1,412 @@
// 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::{
str::FromStr,
time::{Duration, SystemTime},
};
use native_pkcs11_traits::random_label;
use rsa::{pkcs1::DecodeRsaPublicKey, pkcs8::AssociatedOid};
use security_framework::{
certificate::SecCertificate,
identity::SecIdentity,
item::{add_item, AddRef, ItemAddOptions, ItemClass, Reference},
key::SecKey,
os::macos::identity::SecIdentityExt,
};
use security_framework_sys::base::errSecItemNotFound;
use x509_cert::{
der::{
asn1::{GeneralizedTime, Ia5String, OctetString},
oid::ObjectIdentifier,
Decode,
Encode,
},
ext::{
pkix::{
name::GeneralName,
AuthorityKeyIdentifier,
BasicConstraints,
ExtendedKeyUsage,
KeyUsage,
KeyUsages,
SubjectAltName,
SubjectKeyIdentifier,
},
Extension,
},
name::{Name, RdnSequence},
serial_number::SerialNumber,
spki::{der::asn1::BitString, EncodePublicKey, SubjectPublicKeyInfo},
time::Validity,
Certificate,
TbsCertificate,
};
use crate::{
key::{Algorithm, YubikeyPivPublicKey},
keychain,
Result,
};
pub struct YubikeyPivCertificate {
pub label: String,
pub identity: SecIdentity,
pub public_key: YubikeyPivPublicKey,
certificate_der: Vec<u8>,
}
impl YubikeyPivCertificate {
pub fn new(identity: impl Into<SecIdentity>) -> Result<Self> {
let identity: SecIdentity = identity.into();
let label = identity.certificate().unwrap().subject_summary();
let pk = identity.certificate()?.public_key()?;
Ok(Self {
certificate_der: identity.certificate()?.to_der(),
label: label.clone(),
identity,
public_key: YubikeyPivPublicKey::new(pk, label)?,
})
}
}
impl std::fmt::Debug for YubikeyPivCertificate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KeychainCertificate")
.field("label", &self.label)
.field("identity", &self.identity)
.finish()
}
}
impl native_pkcs11_traits::Certificate for YubikeyPivCertificate {
fn label(&self) -> String {
self.label.to_string()
}
fn public_key(&self) -> &dyn native_pkcs11_traits::PublicKey {
&self.public_key
}
fn to_der(&self) -> Vec<u8> {
self.certificate_der.clone()
}
fn delete(self: Box<Self>) {
let _ = self.identity.delete();
}
}
pub fn import_certificate(der: &[u8]) -> Result<SecCertificate> {
let cert = SecCertificate::from_der(der)?;
let add_params = ItemAddOptions::new(security_framework::item::ItemAddValue::Ref(
AddRef::Certificate(cert.clone()),
))
.set_location(keychain::location()?)
.set_label(cert.subject_summary())
.to_dictionary();
add_item(add_params)?;
Ok(cert)
}
pub fn find_certificate(pub_key_hash: &[u8]) -> Result<Option<SecIdentity>> {
let results = crate::piv::keychain::item_search_options()?
.load_refs(true)
.class(ItemClass::certificate())
.pub_key_hash(pub_key_hash)
.search()?;
if results.is_empty() {
return Ok(None);
}
let cert = match results.into_iter().next().ok_or("certificate not found")? {
security_framework::item::SearchResult::Ref(Reference::Certificate(certificate)) => {
certificate
}
_ => return Err("no key ref")?,
};
Ok(Some(SecIdentity::with_certificate(&[], &cert)?))
}
pub fn find_all_certificates() -> Result<Vec<SecIdentity>> {
let results = crate::piv::keychain::item_search_options()?
.load_refs(true)
.class(ItemClass::identity())
.limit(99)
.search();
if let Err(e) = results {
if e.code() == errSecItemNotFound {
return Ok(vec![]);
}
}
let loaded_identites = results?
.into_iter()
.filter_map(|result| match result {
security_framework::item::SearchResult::Ref(Reference::Identity(identity)) => {
Some(identity)
}
_ => None,
})
.collect();
Ok(loaded_identites)
}
// NOTE(kcking): After some empirical tests, it appears SecIdentity is really
// just a SecCertificate that happens to have an associated SecKey private key
// in the keychain. Both `SecItemAdd` and `SecItemDelete` treat a SecIdentity
// like it is the underlying SecCertificate. Further reading:
// https://stackoverflow.com/a/13041370.
//
// For example, if we import a SecCertificate, then convert it to a SecIdentity
// with SecIdentity::with_certificate, trying to import the resulting
// SecIdentity will error with "already exists". Keychain is treating this
// scenario as trying to import the same certificate twice.
//
// An official Apple source also _hints_ at this behavior by saying "working
// with identities as keychain items is very much like working with
// certificates"
// https://developer.apple.com/documentation/security/certificate_key_and_trust_services/identities/storing_an_identity_in_the_keychain?language=objc.
//
// Overall, this means storing SecIdentities isn't any more useful to us than
// storing SecCertificates. The main use case is using
// `SecIdentity::with_certificate` to search for the private key corresponding
// to a certificate.
pub fn import_identity(certificate: &SecCertificate) -> Result<SecIdentity> {
let keychain = keychain::keychain_or_default()?;
let identity = SecIdentity::with_certificate(&[keychain], certificate)?;
let add_params = ItemAddOptions::new(security_framework::item::ItemAddValue::Ref(
AddRef::Identity(identity.clone()),
))
.set_location(keychain::location()?)
.set_label(certificate.subject_summary())
.to_dictionary();
match add_item(add_params) {
Ok(_) => Ok(identity),
Err(e)
if e.message() == Some("The specified item already exists in the keychain.".into()) =>
{
Ok(identity)
}
Err(e) => Err(e.into()),
}
}
pub fn random_serial_number() -> [u8; 16] {
use rand::Rng;
rand::thread_rng().gen::<u128>().to_be_bytes()
}
const EXTENDED_KEY_USAGE_SERVER_AUTHENTICATION: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.1");
const EXTENDED_KEY_USAGE_CLIENT_AUTHENTICATION: ObjectIdentifier =
ObjectIdentifier::new_unwrap("1.3.6.1.5.5.7.3.2");
/// Demonstrate signing a certificate
pub fn self_signed_certificate(key_algorithm: Algorithm, private_key: &SecKey) -> Result<Vec<u8>> {
let public_key = private_key
.public_key()
.ok_or("no public key")?
.external_representation()
.ok_or("no external representation")?
.to_vec();
let public_key = match key_algorithm {
Algorithm::RSA => rsa::RsaPublicKey::from_pkcs1_der(&public_key)?
.to_public_key_der()?
.as_bytes()
.to_owned(),
Algorithm::ECC => p256::PublicKey::from_sec1_bytes(public_key.as_slice())?
.to_public_key_der()?
.as_bytes()
.to_owned(),
};
let spki = SubjectPublicKeyInfo::try_from(public_key.as_slice())?;
let subject_name =
RdnSequence::from_str(&format!("cn=Test Cert {}", random_label()))?.to_der()?;
let issuer_name = RdnSequence::from_str("cn=GShoe LLC")?.to_der()?;
let serial_number = random_serial_number();
let san = GeneralName::DnsName(Ia5String::new("localhost")?);
let san = SubjectAltName(vec![san]).to_der()?;
let key_usage = KeyUsage(
KeyUsages::DigitalSignature | KeyUsages::KeyEncipherment | KeyUsages::KeyAgreement,
)
.to_der()?;
let extended_key_usage = ExtendedKeyUsage(vec![
EXTENDED_KEY_USAGE_CLIENT_AUTHENTICATION,
EXTENDED_KEY_USAGE_SERVER_AUTHENTICATION,
])
.to_der()?;
let basic_constraints = BasicConstraints {
ca: false,
path_len_constraint: None,
}
.to_der()?;
let sk_and_ak_id = random_serial_number();
let sk_id = SubjectKeyIdentifier(OctetString::new(sk_and_ak_id)?).to_der()?;
let ak_id = AuthorityKeyIdentifier {
key_identifier: Some(OctetString::new(sk_and_ak_id)?),
authority_cert_issuer: None,
authority_cert_serial_number: None,
}
.to_der()?;
let tbs_certificate = TbsCertificate {
version: x509_cert::Version::V3,
// NOTE: can't be empty
serial_number: SerialNumber::new(&serial_number)?,
signature: spki.algorithm.clone(),
issuer: Name::from_der(&issuer_name)?,
validity: Validity {
not_before: x509_cert::time::Time::GeneralTime(GeneralizedTime::from_system_time(
SystemTime::now() - Duration::from_secs(60 * 60 * 24),
)?),
not_after: x509_cert::time::Time::GeneralTime(GeneralizedTime::from_system_time(
SystemTime::now() + Duration::from_secs(60 * 60 * 24),
)?),
},
subject: Name::from_der(&subject_name)?,
subject_public_key_info: spki.clone(),
// webpki appears to not support these fields:
// https://github.com/briansmith/webpki/blob/17d9189981a618120fd8217a913828e7418e2484/src/cert.rs#L78
issuer_unique_id: None,
subject_unique_id: None,
extensions: Some(vec![
Extension {
extn_id: BasicConstraints::OID,
critical: true,
extn_value: OctetString::new(basic_constraints)?,
},
Extension {
extn_id: SubjectAltName::OID,
critical: false,
extn_value: OctetString::new(san)?,
},
Extension {
extn_id: KeyUsage::OID,
critical: true,
extn_value: OctetString::new(key_usage)?,
},
Extension {
extn_id: ExtendedKeyUsage::OID,
critical: false,
extn_value: OctetString::new(extended_key_usage)?,
},
Extension {
extn_id: SubjectKeyIdentifier::OID,
critical: false,
extn_value: OctetString::new(sk_id)?,
},
Extension {
extn_id: AuthorityKeyIdentifier::OID,
critical: false,
extn_value: OctetString::new(ak_id)?,
},
]),
};
let payload = tbs_certificate.to_der()?;
let signature = private_key.create_signature(
match key_algorithm {
Algorithm::RSA => security_framework_sys::key::Algorithm::RSASignatureMessagePSSSHA256,
Algorithm::ECC => {
security_framework_sys::key::Algorithm::ECDSASignatureMessageX962SHA256
}
},
&payload,
)?;
let cert = Certificate {
tbs_certificate,
signature_algorithm: spki.algorithm,
signature: BitString::from_bytes(signature.as_slice())?,
};
Ok(cert.to_der()?)
}
#[cfg(test)]
mod test {
use native_pkcs11_traits::random_label;
use serial_test::serial;
use super::*;
#[test]
#[serial]
#[ignore = "https://github.com/google/native-pkcs11/issues/302"]
fn test_self_signed_certificate() -> Result<()> {
use security_framework::item::{ItemClass, Limit};
use crate::key::generate_key;
let label = random_label();
let key = generate_key(Algorithm::RSA, &label, Some(keychain::location()?))?;
let cert = self_signed_certificate(Algorithm::RSA, &key)?;
let cert = import_certificate(&cert)?;
// NOTE(kcking): Importing a certificate that has a private key already
// stored in the keychain will treat that certificate as an identity, even
// without calling import_identity.
// let identity = import_identity(&cert)?;
// HACK(kcking): The macOS keychain takes some time to flush all of the updates
// such that they are visible to the next search query.
std::thread::sleep(std::time::Duration::from_secs(1));
assert!(
crate::piv::keychain::item_search_options()?
.class(ItemClass::identity())
.limit(Limit::All)
.load_refs(true)
.search()?
.iter()
.any(|result| match result {
security_framework::item::SearchResult::Ref(
security_framework::item::Reference::Identity(id),
) => id.certificate().unwrap().subject() == cert.subject(),
_ => false,
})
);
// Clean up
cert.delete()?;
// NOTE(kcking): Deleting the certificate also deletes the identity since
// they are the same underlying object, so identity.delete() is not needed.
// identity.delete()?;
key.public_key().ok_or("no public key")?.delete()?;
key.delete()?;
Ok(())
}
}

View File

@@ -0,0 +1,565 @@
// 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::fmt::Debug;
use core_foundation::base::ToVoid;
use native_pkcs11_traits::{KeyAlgorithm, PrivateKey, PublicKey, SignatureAlgorithm};
use security_framework::{
item::{ItemClass, KeyClass, Limit, Location, Reference},
key::{GenerateKeyOptions, KeyType, SecKey},
};
// TODO(bweeks,kcking): remove dependency on security-framework-sys crate.
use security_framework_sys::item::{
kSecAttrKeyType,
kSecAttrKeyTypeEC,
kSecAttrKeyTypeRSA,
kSecAttrTokenID,
};
use tracing::instrument;
use crate::Result;
#[derive(Debug)]
pub enum Algorithm {
RSA,
ECC,
}
fn sigalg_to_seckeyalg(
signature_algorithm: &SignatureAlgorithm,
) -> Result<security_framework_sys::key::Algorithm> {
use security_framework_sys::key::Algorithm::*;
let alg = match signature_algorithm {
native_pkcs11_traits::SignatureAlgorithm::Ecdsa => ECDSASignatureRFC4754,
native_pkcs11_traits::SignatureAlgorithm::RsaRaw => RSASignatureRaw,
native_pkcs11_traits::SignatureAlgorithm::RsaPkcs1v15Raw => RSASignatureDigestPKCS1v15Raw,
native_pkcs11_traits::SignatureAlgorithm::RsaPkcs1v15Sha1 => {
RSASignatureMessagePKCS1v15SHA1
}
native_pkcs11_traits::SignatureAlgorithm::RsaPkcs1v15Sha384 => {
RSASignatureMessagePKCS1v15SHA384
}
native_pkcs11_traits::SignatureAlgorithm::RsaPkcs1v15Sha256 => {
RSASignatureMessagePKCS1v15SHA256
}
native_pkcs11_traits::SignatureAlgorithm::RsaPkcs1v15Sha512 => {
RSASignatureMessagePKCS1v15SHA512
}
native_pkcs11_traits::SignatureAlgorithm::RsaPss {
digest,
mask_generation_function,
salt_length,
} => {
// SecurityFramework only supports digest == mgf, salt_length == len(digest).
if digest != mask_generation_function || digest.digest_len() != *salt_length as usize {
return Err(crate::ErrorKind::UnsupportedSignatureAlgorithm(
signature_algorithm.clone(),
)
.into());
}
match mask_generation_function {
native_pkcs11_traits::DigestType::Sha1 => RSASignatureDigestPSSSHA1,
native_pkcs11_traits::DigestType::Sha224 => RSASignatureDigestPSSSHA224,
native_pkcs11_traits::DigestType::Sha256 => RSASignatureDigestPSSSHA256,
native_pkcs11_traits::DigestType::Sha384 => RSASignatureDigestPSSSHA384,
native_pkcs11_traits::DigestType::Sha512 => RSASignatureDigestPSSSHA512,
}
}
};
Ok(alg)
}
#[derive(Debug)]
pub struct YubikeyPivPrivateKey {
sec_key: SecKey,
label: String,
public_key_hash: Vec<u8>,
algorithm: KeyAlgorithm,
pub_key: Option<YubikeyPivPublicKey>,
}
impl YubikeyPivPrivateKey {
#[instrument]
pub fn new(
sec_key: SecKey,
label: impl Into<String> + Debug,
pub_key: Option<YubikeyPivPublicKey>,
) -> Result<Self> {
let label = label.into();
let public_key_hash = sec_key.application_label().ok_or("no application_label")?;
Ok(Self {
algorithm: sec_key_algorithm(&sec_key)?,
sec_key,
label,
public_key_hash,
pub_key,
})
}
}
impl PrivateKey for YubikeyPivPrivateKey {
#[instrument]
fn public_key_hash(&self) -> Vec<u8> {
self.public_key_hash.clone()
}
#[instrument]
fn label(&self) -> String {
self.label.clone()
}
#[instrument]
fn sign(
&self,
algorithm: &native_pkcs11_traits::SignatureAlgorithm,
data: &[u8],
) -> native_pkcs11_traits::Result<Vec<u8>> {
let algorithm = sigalg_to_seckeyalg(algorithm)?;
Ok(self.sec_key.create_signature(algorithm, data.as_ref())?)
}
#[instrument]
fn delete(&self) {
let _ = self.sec_key.delete();
}
#[instrument]
fn algorithm(&self) -> KeyAlgorithm {
self.algorithm
}
fn find_public_key(
&self,
_backend: &dyn native_pkcs11_traits::Backend,
) -> native_pkcs11_traits::Result<Option<Box<dyn PublicKey>>> {
let sec_copy = self
.sec_key
.public_key()
.map(|sec_key| YubikeyPivPublicKey::new(sec_key, self.label()))
.transpose()
.ok()
.flatten()
.map(|key| Box::new(key) as _);
if sec_copy.is_some() {
return Ok(sec_copy);
}
Ok(self.pub_key.clone().map(|key| Box::new(key) as _))
}
}
fn sec_key_algorithm(sec_key: &SecKey) -> Result<KeyAlgorithm> {
let attributes = sec_key.attributes();
if attributes
.find(unsafe { kSecAttrTokenID }.to_void())
.is_some()
{
// The only possible kSecAttrtokenID is kSecAttrTokenIDSecureEnclave.
//
// SecureEnclave keys do not have kSecAttrKeyType populated, but we can
// assume they are Ecc.
return Ok(KeyAlgorithm::Ecc);
}
let key_ty = sec_key
.attributes()
.find(unsafe { kSecAttrKeyType }.to_void())
.and_then(|key_type| match *key_type as *const _ {
ty if ty == unsafe { kSecAttrKeyTypeRSA } => Some(KeyAlgorithm::Rsa),
ty if ty == unsafe { kSecAttrKeyTypeEC } => Some(KeyAlgorithm::Ecc),
_ => None,
})
.ok_or("no key type")?;
Ok(key_ty)
}
#[derive(Debug, Clone)]
pub struct YubikeyPivPublicKey {
pub sec_key: SecKey,
pub label: String,
der: Vec<u8>,
public_key_hash: Vec<u8>,
algorithm: KeyAlgorithm,
}
impl YubikeyPivPublicKey {
#[instrument]
pub fn new(sec_key: SecKey, label: impl Into<String> + Debug) -> Result<Self> {
let der = sec_key
.external_representation()
.ok_or("no external representation")?;
let key_ty = sec_key_algorithm(&sec_key)?;
Ok(Self {
public_key_hash: sec_key.application_label().ok_or("no application_label")?,
sec_key,
label: label.into(),
der: der.to_vec(),
algorithm: key_ty,
})
}
}
impl PublicKey for YubikeyPivPublicKey {
#[instrument]
fn public_key_hash(&self) -> Vec<u8> {
self.public_key_hash.clone()
}
#[instrument]
fn label(&self) -> String {
self.label.clone()
}
#[instrument]
fn to_der(&self) -> Vec<u8> {
self.der.clone()
}
#[instrument]
fn verify(
&self,
algorithm: &native_pkcs11_traits::SignatureAlgorithm,
data: &[u8],
signature: &[u8],
) -> native_pkcs11_traits::Result<()> {
let algorithm = sigalg_to_seckeyalg(algorithm)?;
let result = self.sec_key.verify_signature(algorithm, data, signature)?;
if !result {
return Err("verify failed")?;
}
Ok(())
}
fn delete(self: Box<Self>) {
let _ = self.sec_key.delete();
}
fn algorithm(&self) -> KeyAlgorithm {
self.algorithm
}
}
#[instrument(skip(location))]
pub fn generate_key(
algorithm: Algorithm,
label: &str,
location: Option<Location>,
) -> Result<SecKey> {
let (ty, size) = match algorithm {
Algorithm::RSA => (KeyType::rsa(), 2048),
Algorithm::ECC => (KeyType::ec(), 256),
};
let opts = GenerateKeyOptions {
key_type: Some(ty),
size_in_bits: Some(size),
label: Some(label.into()),
token: Some(security_framework::key::Token::Software),
location,
access_control: None,
}
.to_dictionary();
Ok(SecKey::generate(opts).map_err(|e| e.to_string())?)
}
pub fn find_key(class: KeyClass, label: &str) -> Result<SecKey> {
let results = crate::keychain::item_search_options()?
.load_refs(true)
.label(label)
.class(ItemClass::key())
.key_class(class)
.limit(1)
.search();
let loaded_key = match results?.into_iter().next().ok_or("key not found")? {
security_framework::item::SearchResult::Ref(Reference::Key(key)) => key,
_ => return Err("no key ref")?,
};
Ok(loaded_key)
}
#[instrument]
pub fn find_key2(class: KeyClass, label: &[u8]) -> Result<Option<SecKey>> {
let results = crate::keychain::item_search_options()?
.load_refs(true)
.class(ItemClass::key())
.key_class(class)
.application_label(label)
.limit(1)
.search();
let results = match results {
Err(e) if e.code() == -25300 => return Ok(None),
Err(e) => return Err(e)?,
Ok(results) => results,
};
let loaded_key = results
.into_iter()
.next()
.map(|key| match key {
security_framework::item::SearchResult::Ref(Reference::Key(key)) => Ok::<_, &str>(key),
_ => Err("no key ref")?,
})
.transpose()?;
Ok(loaded_key)
}
#[instrument]
pub fn find_all_keys(key_class: KeyClass) -> Result<Vec<SecKey>> {
let results = crate::keychain::item_search_options()?
.load_refs(true)
.class(ItemClass::key())
.key_class(key_class)
.limit(Limit::All)
.search();
let results = match results {
Err(e) if e.code() == -25300 => return Ok(vec![]),
Err(e) => return Err(e)?,
Ok(results) => results,
};
let keys = results
.into_iter()
.filter_map(|res| match res {
security_framework::item::SearchResult::Ref(Reference::Key(key)) => Some(key),
_ => None,
})
.collect();
Ok(keys)
}
#[cfg(test)]
mod test {
use core_foundation::base::{TCFType, ToVoid};
use native_pkcs11_traits::{random_label, Backend};
use security_framework::item::{add_item, AddRef, ItemAddOptions, Limit};
use security_framework_sys::item::{kSecAttrLabel, kSecValueRef};
use serial_test::serial;
use super::*;
use crate::{keychain, KeychainBackend};
#[test]
#[serial]
fn key_label() -> crate::Result<()> {
let label = random_label();
let key = generate_key(Algorithm::RSA, &label, Some(keychain::location()?))?;
let mut found = false;
for res in crate::keychain::item_search_options()?
.key_class(KeyClass::private())
.limit(Limit::Max(1))
.load_attributes(true)
.load_refs(true)
.label(&label)
.search()?
{
found = true;
let (found_key, found_label) = match res {
security_framework::item::SearchResult::Ref(_) => panic!(),
security_framework::item::SearchResult::Dict(d) => {
let key = unsafe {
SecKey::wrap_under_get_rule(d.get(kSecValueRef.to_void()).cast_mut().cast())
};
let label = unsafe {
core_foundation::string::CFString::wrap_under_get_rule(
d.get(kSecAttrLabel.to_void()).cast_mut().cast(),
)
};
(key, label.to_string())
}
security_framework::item::SearchResult::Data(_) => panic!(),
security_framework::item::SearchResult::Other => panic!(),
};
assert_eq!(
found_key.external_representation().unwrap().to_vec(),
key.external_representation().unwrap().to_vec()
);
assert_eq!(found_label, label);
}
key.public_key().unwrap().delete()?;
key.delete()?;
assert!(found);
Ok(())
}
#[test]
#[serial]
fn key_lifecycle() -> Result<()> {
for (key_alg, sig_alg) in [
(
Algorithm::ECC,
security_framework_sys::key::Algorithm::ECDSASignatureDigestX962,
),
(
Algorithm::RSA,
security_framework_sys::key::Algorithm::RSASignatureDigestPKCS1v15Raw,
),
] {
let label = &random_label();
let key = generate_key(key_alg, label, Some(keychain::location()?))?;
let first_pubkey = key
.public_key()
.ok_or("no pubkey")?
.external_representation()
.ok_or("no external_representation")?
.to_vec();
std::mem::drop(key);
let loaded_key = find_key(KeyClass::private(), label)?;
let payload = vec![0u8; 32];
let signature = loaded_key.create_signature(sig_alg, &payload)?;
let loaded_pubkey = loaded_key.public_key().ok_or("no pubkey")?;
let sig_valid = loaded_pubkey.verify_signature(sig_alg, &payload, &signature)?;
assert!(sig_valid);
assert_eq!(
loaded_pubkey.external_representation().unwrap().to_vec(),
first_pubkey
);
loaded_key.public_key().ok_or("no pubkey")?.delete()?;
loaded_key.delete()?;
}
Ok(())
}
#[test]
#[ignore]
fn stress_test_keygen() {
let try_gen_key = || -> bool {
let label = random_label();
match generate_key(Algorithm::RSA, &label, Some(keychain::location().unwrap())) {
Ok(key) => {
let _ = key.delete();
true
}
Err(e) => {
eprintln!("{:?}", e);
false
}
}
};
let mut handles = vec![];
for _ in 0..20 {
handles.push(std::thread::spawn(try_gen_key));
}
assert!(
handles
.into_iter()
.map(|h| h.join().unwrap())
// fold so we don't early exit other threads
.all(|b| b)
);
}
#[test]
#[ignore = "https://github.com/google/native-pkcs11/issues/302"]
fn keychain_pubkey_hash_find() -> Result<()> {
let key1 = generate_key(Algorithm::ECC, &random_label(), Some(keychain::location()?))?;
let key2 = generate_key(Algorithm::ECC, &random_label(), Some(keychain::location()?))?;
assert_ne!(key1.application_label(), key2.application_label());
for keyclass in [KeyClass::public(), KeyClass::private()] {
for key in [&key1, &key2] {
assert_eq!(
find_key2(keyclass, &key.application_label().unwrap())?
.unwrap()
.application_label()
.unwrap(),
key.application_label().unwrap()
);
}
}
for key in [&key1, &key2] {
key.public_key().as_ref().map(SecKey::delete);
let _ = key.delete();
}
Ok(())
}
#[test]
#[ignore = "demonstrate bug"]
fn unpersisted_public_key() -> Result<()> {
// NOTE(kcking):
// 1) Manually-imported keys are super scuffed.
// Manually imported key can be searched by label (if imported with
// that label), but cannot be searched by application_label (aka public
// key hash). Perhaps we are supposed to set this value at import time.
//
// 2) Manually-imported private keys do not return a corresponding
// public key from SecKeyCopyPublicKey (`.public_key()` in rust).
let label = random_label();
let key1 = SecKey::generate(
GenerateKeyOptions::default()
.set_key_type(KeyType::ec())
.set_label(&label)
.to_dictionary(),
)?;
let pubkey_hash = key1.public_key().unwrap().application_label().unwrap();
add_item(
ItemAddOptions::new(security_framework::item::ItemAddValue::Ref(AddRef::Key(
key1,
)))
.set_label(&label)
.to_dictionary(),
)?;
// NOTE(kcking): this fails to find the generated key, most likely
// because application_label is not automatically populated by
// SecurityFramework when importing a SecKey
//
// let found_key =
// KeychainBackend::find_private_key(native_pkcs11_traits::KeySearchOptions::PublicKeyHash(
// pubkey_hash
// .as_slice()
// .try_into()
// .map_err(|_| "into array")?,
// ))
// .map_err(|e| {
// dbg!(e);
// "find"
// })?
// .unwrap();
let found_key = KeychainBackend
.find_private_key(native_pkcs11_traits::KeySearchOptions::Label(label))
.map_err(|e| {
dbg!(e);
"find"
})?
.unwrap();
assert_eq!(pubkey_hash, found_key.public_key_hash());
Ok(())
}
}

View File

@@ -0,0 +1,49 @@
// 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 security_framework::{
item::{ItemSearchOptions, Location},
os::macos::{item::ItemSearchOptionsExt, keychain::SecKeychain},
};
use crate::Result;
fn keychain() -> Result<Option<SecKeychain>> {
match std::env::var("NATIVE_PKCS11_KEYCHAIN_PATH") {
Ok(path) => Ok(Some(SecKeychain::open(path)?)),
Err(_) => Ok(None),
}
}
pub(crate) fn keychain_or_default() -> Result<SecKeychain> {
match keychain()? {
Some(keychain) => Ok(keychain),
None => Ok(SecKeychain::default()?),
}
}
pub(crate) fn location() -> Result<Location> {
match keychain()? {
Some(keychain) => Ok(Location::FileKeychain(keychain)),
None => Ok(Location::DefaultFileKeychain),
}
}
pub fn item_search_options() -> Result<ItemSearchOptions> {
let mut opts = ItemSearchOptions::new();
if let Some(keychain) = keychain()? {
opts.keychains(&[keychain]);
}
Ok(opts)
}

View File

@@ -0,0 +1,100 @@
// 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::fmt::Debug;
pub use backend::YubikeyPivBackend;
use core_foundation::error::CFError;
use native_pkcs11_traits::SignatureAlgorithm;
use thiserror::Error;
use tracing_error::SpanTrace;
mod backend;
pub mod certificate;
pub mod key;
pub mod keychain;
pub type Result<T> = std::result::Result<T, Error>;
pub struct Error {
error: ErrorKind,
context: SpanTrace,
}
impl Debug for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{:?}", self.error)?;
self.context.fmt(f)
}
}
impl std::error::Error for Error {}
impl<E: Into<ErrorKind>> From<E> for Error {
fn from(e: E) -> Self {
Error {
error: e.into(),
context: SpanTrace::capture(),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "{}", self.error)?;
std::fmt::Display::fmt(&self.context, f)
}
}
#[derive(Error, Debug)]
pub enum ErrorKind {
#[error("GenericError {0}")]
Generic(String),
#[error("{0}")]
Der(#[from] x509_cert::der::Error),
#[error("{0}")]
SecurityFramework(#[from] security_framework::base::Error),
#[error("{0}")]
Spki(#[from] x509_cert::spki::Error),
#[error("{0}")]
P256(#[from] p256::elliptic_curve::Error),
#[error("{0}")]
Pkcs1(#[from] rsa::pkcs1::Error),
#[error("{0:?}")]
UnsupportedSignatureAlgorithm(SignatureAlgorithm),
}
impl From<CFError> for ErrorKind {
fn from(e: CFError) -> Self {
ErrorKind::SecurityFramework(security_framework::base::Error::from_code(e.code() as i32))
}
}
impl From<&str> for ErrorKind {
fn from(s: &str) -> Self {
ErrorKind::Generic(s.to_string())
}
}
impl From<String> for ErrorKind {
fn from(s: String) -> Self {
ErrorKind::Generic(s)
}
}

View File

@@ -0,0 +1,26 @@
#!/bin/bash
# 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.
set -e
# https://stackoverflow.com/questions/59895/how-do-i-get-the-directory-where-a-bash-script-is-located-from-within-the-script
cd $(dirname -- "$( readlink -f -- "$0"; )")
cargo build --bin signedtest
./codesigning-testing/codesign.sh $PWD/../target/debug/signedtest
(../target/debug/signedtest && echo SUCCESS) || (echo FAIL && exit 1)

View File

@@ -0,0 +1,14 @@
[package]
name = "native-pkcs11-traits"
version = "0.2.18"
description = "Traits for implementing and interactive with native-pkcs11 module backends."
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
repository.workspace = true
license.workspace = true
[dependencies]
once_cell = "1.19.0"
rand = "0.8.5"
x509-cert = { version = "0.2.5", default-features = false }

View 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.

View File

@@ -0,0 +1,221 @@
// 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::{
any::Any,
hash::Hash,
sync::{Arc, RwLock},
};
pub use once_cell;
use once_cell::sync::Lazy;
use x509_cert::der::Decode;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
pub type Digest = [u8; 20];
// The Backend is first staged so it can be stored in a Box<dyn Backend>. This
// allows the Backend to be reference with `&'static`.
static STAGED_BACKEND: RwLock<Option<Box<dyn Backend>>> = RwLock::new(None);
static BACKEND: Lazy<Box<dyn Backend>> =
Lazy::new(|| STAGED_BACKEND.write().unwrap().take().unwrap());
/// Stores a backend to later be returned by all calls `crate::backend()`.
pub fn register_backend(backend: Box<dyn Backend>) {
*STAGED_BACKEND.write().unwrap() = Some(backend);
}
pub fn backend() -> &'static dyn Backend {
BACKEND.as_ref()
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum DigestType {
Sha1,
Sha224,
Sha256,
Sha384,
Sha512,
}
impl DigestType {
pub fn digest_len(&self) -> usize {
match self {
DigestType::Sha1 => 20,
DigestType::Sha224 => 28,
DigestType::Sha256 => 32,
DigestType::Sha384 => 48,
DigestType::Sha512 => 64,
}
}
}
#[derive(Debug, Clone)]
pub enum SignatureAlgorithm {
Ecdsa,
RsaRaw,
RsaPkcs1v15Raw,
RsaPkcs1v15Sha1,
RsaPkcs1v15Sha384,
RsaPkcs1v15Sha256,
RsaPkcs1v15Sha512,
RsaPss {
digest: DigestType,
mask_generation_function: DigestType,
salt_length: u64,
},
}
pub trait PrivateKey: Send + Sync {
fn public_key_hash(&self) -> Vec<u8>;
fn label(&self) -> String;
fn sign(&self, algorithm: &SignatureAlgorithm, data: &[u8]) -> Result<Vec<u8>>;
fn delete(&self);
fn algorithm(&self) -> KeyAlgorithm;
fn find_public_key(&self, backend: &dyn Backend) -> Result<Option<Box<dyn PublicKey>>> {
let pubkey_hash: Digest = self.public_key_hash().as_slice().try_into()?;
backend.find_public_key(KeySearchOptions::PublicKeyHash(pubkey_hash))
}
}
impl std::fmt::Debug for dyn PrivateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("PrivateKey")
.field("label", &self.label())
.finish_non_exhaustive()
}
}
impl PartialEq for dyn PrivateKey {
fn eq(&self, other: &Self) -> bool {
self.public_key_hash() == other.public_key_hash() && self.label() == other.label()
}
}
impl Eq for dyn PrivateKey {}
impl Hash for dyn PrivateKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.type_id().hash(state);
self.public_key_hash().hash(state);
self.label().hash(state);
}
}
pub trait PublicKey: Send + Sync + std::fmt::Debug {
fn public_key_hash(&self) -> Vec<u8>;
fn label(&self) -> String;
fn to_der(&self) -> Vec<u8>;
fn verify(&self, algorithm: &SignatureAlgorithm, data: &[u8], signature: &[u8]) -> Result<()>;
fn delete(self: Box<Self>);
fn algorithm(&self) -> KeyAlgorithm;
}
impl PartialEq for dyn PublicKey {
fn eq(&self, other: &Self) -> bool {
self.public_key_hash() == other.public_key_hash() && self.label() == other.label()
}
}
impl Eq for dyn PublicKey {}
impl Hash for dyn PublicKey {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.type_id().hash(state);
self.public_key_hash().hash(state);
self.label().hash(state);
}
}
pub trait Certificate: Send + Sync + std::fmt::Debug {
fn label(&self) -> String;
fn to_der(&self) -> Vec<u8>;
fn public_key(&self) -> &dyn PublicKey;
fn delete(self: Box<Self>);
fn algorithm(&self) -> KeyAlgorithm {
self.public_key().algorithm()
}
}
impl PartialEq for dyn Certificate {
fn eq(&self, other: &Self) -> bool {
self.to_der() == other.to_der() && self.label() == other.label()
}
}
impl Eq for dyn Certificate {}
impl Hash for dyn Certificate {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self.type_id().hash(state);
self.to_der().hash(state);
self.label().hash(state);
}
}
pub trait CertificateExt: Certificate {
fn issuer(&self) -> Vec<u8> {
let der = self.to_der();
let c = x509_cert::Certificate::from_der(&der).unwrap();
x509_cert::der::Encode::to_der(&c.tbs_certificate.issuer).unwrap()
}
fn serial_number(&self) -> Vec<u8> {
let der = self.to_der();
let c = x509_cert::Certificate::from_der(&der).unwrap();
x509_cert::der::Encode::to_der(&c.tbs_certificate.serial_number).unwrap()
}
fn subject(&self) -> Vec<u8> {
let der = self.to_der();
let c = x509_cert::Certificate::from_der(&der).unwrap();
x509_cert::der::Encode::to_der(&c.tbs_certificate.subject).unwrap()
}
}
impl<T: Certificate + ?Sized> CertificateExt for T {}
#[derive(Debug)]
pub enum KeySearchOptions {
// TODO(kcking): search keys by _both_ label and public key hash as that is how
// they are de-duped and referenced.
Label(String),
PublicKeyHash(Digest),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyAlgorithm {
Rsa,
Ecc,
}
pub trait Backend: Send + Sync {
fn name(&self) -> String;
fn find_all_certificates(&self) -> Result<Vec<Box<dyn Certificate>>>;
fn find_private_key(&self, query: KeySearchOptions) -> Result<Option<Arc<dyn PrivateKey>>>;
fn find_public_key(&self, query: KeySearchOptions) -> Result<Option<Box<dyn PublicKey>>>;
fn find_all_private_keys(&self) -> Result<Vec<Arc<dyn PrivateKey>>>;
fn find_all_public_keys(&self) -> Result<Vec<Arc<dyn PublicKey>>>;
fn generate_key(
&self,
algorithm: KeyAlgorithm,
label: Option<&str>,
) -> Result<Arc<dyn PrivateKey>>;
}
pub fn random_label() -> String {
use rand::{distributions::Alphanumeric, Rng};
String::from("bumpkey ")
+ &rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(32)
.map(char::from)
.collect::<String>()
}

37
native-pkcs11/Cargo.toml Normal file
View File

@@ -0,0 +1,37 @@
[package]
name = "native-pkcs11"
version = "0.2.18"
description = "Cross-platform PKCS#11 module written in rust. Can be extended with custom credential backends."
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
repository.workspace = true
license.workspace = true
[features]
custom-function-list = []
[dependencies]
cached = { version = "0.51.4", 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" }
once_cell = "1.19.0"
pkcs11-sys = { version = "0.2.0", path = "../pkcs11-sys" }
thiserror = "1.0.61"
tracing = "0.1.40"
tracing-error = "0.2.0"
tracing-journald = "0.3"
tracing-subscriber = { version = "0.3.18", features = ["env-filter"] }
native-pkcs11-piv = { version = "0.2.0", path = "../native-pkcs11-piv" }
[lib]
name = "yubikey_piv_pkcs11"
crate-type = ["lib", "cdylib"]
[dev-dependencies]
serial_test = { version = "3.1.1", default-features = false }
tracing = { version = "0.1.40", default-features = false }
tracing-subscriber = { version = "0.3.18", default-features = false, features = [
"env-filter",
] }

1601
native-pkcs11/src/lib.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,252 @@
// 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::HashMap;
use cached::{Cached, TimedCache};
use native_pkcs11_core::{
attribute::{Attribute, AttributeType, Attributes},
Result,
};
use native_pkcs11_traits::{backend, KeySearchOptions};
use pkcs11_sys::{
CKO_CERTIFICATE,
CKO_PRIVATE_KEY,
CKO_PUBLIC_KEY,
CKO_SECRET_KEY,
CKP_BASELINE_PROVIDER,
CK_OBJECT_HANDLE,
};
use tracing::{instrument, warn};
use crate::{object::Object, Error};
#[derive(Debug)]
pub struct ObjectStore {
objects: HashMap<CK_OBJECT_HANDLE, Object>,
handles_by_object: HashMap<Object, CK_OBJECT_HANDLE>,
next_object_handle: CK_OBJECT_HANDLE,
query_cache: TimedCache<Attributes, Vec<CK_OBJECT_HANDLE>>,
}
impl ObjectStore {
#[instrument(skip(self))]
pub fn insert(&mut self, object: Object) -> CK_OBJECT_HANDLE {
if let Some(existing_handle) = self.handles_by_object.get(&object) {
return *existing_handle;
}
let handle = self.next_object_handle + 1;
self.next_object_handle += 1;
self.objects.insert(handle, object.clone());
self.handles_by_object.insert(object, handle);
handle
}
#[instrument(skip(self))]
pub fn get(&self, handle: &CK_OBJECT_HANDLE) -> Option<&Object> {
self.objects.get(handle)
}
#[instrument(skip(self))]
pub fn find(&mut self, template: Attributes) -> Result<Vec<CK_OBJECT_HANDLE>> {
// Cache certificates.
//
// Firefox + NSS query certificates for every TLS connection in order to
// evaluate server trust. Cache the results for 3 seconds.
if let Some(c) = self.query_cache.cache_get(&template) {
Ok(c.to_vec())
} else {
let output = self.find_impl(&template)?;
self.query_cache.cache_set(template, output.clone());
Ok(output)
}
}
#[instrument(skip(self))]
fn find_impl(&mut self, template: &Attributes) -> Result<Vec<CK_OBJECT_HANDLE>> {
self.find_with_backend(template)?;
if template.is_empty() {
Ok(self.find_all())
} else {
Ok(self.find_store(template))
}
}
#[instrument(skip(self))]
fn find_all(&self) -> Vec<CK_OBJECT_HANDLE> {
self.objects.keys().copied().collect()
}
#[instrument(skip(self))]
fn find_store(&self, template: &Attributes) -> Vec<CK_OBJECT_HANDLE> {
self.objects
.iter()
.filter(|(_, object)| object.matches(template))
.map(|(handle, _)| *handle)
.collect()
}
#[instrument(skip(self))]
fn find_with_backend(&mut self, template: &Attributes) -> Result<()> {
if template.is_empty() {
self.find_with_backend_all_certificates()?;
self.find_with_backend_all_public_keys()?;
self.find_with_backend_all_private_keys()?;
return Ok(());
}
let class = match template.get(AttributeType::Class) {
Some(Attribute::Class(class)) => class,
None => {
return Err(Error::Todo("no class attribute".to_string()));
}
class => {
return Err(Error::Todo(format!("class {:?} not implemented", class)));
}
};
match *class {
CKO_CERTIFICATE => {
if template.len() > 1 {
warn!("ignoring attributes for certificate search");
}
self.find_with_backend_all_certificates()?;
}
// CKO_NSS_TRUST | CKO_NETSCAPE_BUILTIN_ROOT_LIST
3461563219 | 3461563220 => (),
CKO_SECRET_KEY => (),
CKO_PUBLIC_KEY | CKO_PRIVATE_KEY => {
let opts = if let Some(Attribute::Id(id)) = template.get(AttributeType::Id) {
KeySearchOptions::PublicKeyHash(id.as_slice().try_into()?)
} else if let Some(Attribute::Label(label)) = template.get(AttributeType::Label) {
KeySearchOptions::Label(label.into())
} else {
match *class {
CKO_PRIVATE_KEY => self.find_with_backend_all_private_keys()?,
CKO_PUBLIC_KEY => self.find_with_backend_all_public_keys()?,
_ => unreachable!(),
}
return Ok(());
};
match *class {
CKO_PRIVATE_KEY => backend().find_private_key(opts)?.map(|key| {
self.insert(Object::PrivateKey(key));
}),
CKO_PUBLIC_KEY => backend().find_public_key(opts)?.map(|key| {
self.insert(Object::PublicKey(key.into()));
}),
_ => unreachable!(),
};
}
_ => {
return Err(Error::AttributeTypeInvalid(*class));
}
}
Ok(())
}
fn find_with_backend_all_certificates(&mut self) -> Result<()> {
for cert in backend().find_all_certificates()? {
let private_key = backend().find_private_key(KeySearchOptions::PublicKeyHash(
cert.public_key().public_key_hash().as_slice().try_into()?,
))?;
// Check if certificate has an associated PrivateKey.
match private_key {
Some(key) => key,
None => continue,
};
self.insert(Object::Certificate(cert.into()));
}
Ok(())
}
fn find_with_backend_all_public_keys(&mut self) -> Result<()> {
for private_key in backend().find_all_private_keys()? {
self.insert(Object::PrivateKey(private_key));
}
Ok(())
}
fn find_with_backend_all_private_keys(&mut self) -> Result<()> {
for private_key in backend().find_all_private_keys()? {
self.insert(Object::PrivateKey(private_key));
}
Ok(())
}
}
impl Default for ObjectStore {
fn default() -> Self {
Self {
objects: HashMap::from([(1, Object::Profile(CKP_BASELINE_PROVIDER))]),
handles_by_object: HashMap::from([(Object::Profile(CKP_BASELINE_PROVIDER), 1)]),
next_object_handle: 2,
query_cache: TimedCache::with_lifespan(10),
}
}
}
#[cfg(test)]
mod tests {
use std::vec;
use native_pkcs11_traits::{backend, random_label, KeyAlgorithm};
use pkcs11_sys::CKO_PRIVATE_KEY;
use serial_test::serial;
use super::*;
use crate::tests::test_init;
#[test]
#[serial]
fn test_object_store() {
test_init();
let label = &format!("objectstore test {}", random_label());
let key = backend()
.generate_key(native_pkcs11_traits::KeyAlgorithm::Rsa, Some(label))
.unwrap();
let mut store = ObjectStore::default();
let template = Attributes::from(vec![
Attribute::Class(CKO_PRIVATE_KEY),
Attribute::Label(label.into()),
]);
let private_key_handle = store.find(template.clone()).unwrap()[0];
// find again
assert_eq!(store.find(template).unwrap()[0], private_key_handle);
key.find_public_key(backend()).unwrap().unwrap().delete();
key.delete();
}
#[test]
#[serial]
fn key_alg() -> Result<()> {
test_init();
let ec = backend().generate_key(KeyAlgorithm::Ecc, Some(&random_label()))?;
let rsa = backend().generate_key(KeyAlgorithm::Rsa, Some(&random_label()))?;
assert_eq!(ec.algorithm(), KeyAlgorithm::Ecc);
assert_eq!(rsa.algorithm(), KeyAlgorithm::Rsa);
for key in [ec, rsa] {
key.find_public_key(backend()).unwrap().unwrap().delete();
key.delete();
}
Ok(())
}
}

View File

@@ -0,0 +1,131 @@
// 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::HashMap,
sync::{self, atomic::Ordering, Arc},
};
use native_pkcs11_traits::{PrivateKey, SignatureAlgorithm};
use once_cell::sync::Lazy;
use pkcs11_sys::{CK_BYTE_PTR, CK_FLAGS, CK_OBJECT_HANDLE, CK_SESSION_HANDLE, CK_ULONG_PTR};
use crate::{object_store::ObjectStore, Error, Result};
// "Valid session handles in Cryptoki always have nonzero values."
#[cfg(not(target_os = "windows"))]
static NEXT_SESSION_HANDLE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
#[cfg(target_os = "windows")]
static NEXT_SESSION_HANDLE: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
type SessionMap = HashMap<CK_SESSION_HANDLE, Session>;
static SESSIONS: Lazy<sync::Mutex<SessionMap>> = Lazy::new(Default::default);
pub static OBJECT_STORE: Lazy<sync::Mutex<ObjectStore>> = Lazy::new(Default::default);
#[derive(Debug)]
pub struct FindContext {
pub objects: Vec<CK_OBJECT_HANDLE>,
}
#[derive(Debug)]
pub struct SignContext {
pub algorithm: SignatureAlgorithm,
pub private_key: Arc<dyn PrivateKey>,
/// Payload stored for multipart C_SignUpdate operations.
pub payload: Option<Vec<u8>>,
}
impl Session {
/// Sign the provided data, or stored payload if data is not provided.
pub unsafe fn sign(
&mut self,
data: Option<&[u8]>,
pSignature: CK_BYTE_PTR,
pulSignatureLen: CK_ULONG_PTR,
) -> Result {
let sign_ctx = match self.sign_ctx.as_mut() {
Some(sign_ctx) => sign_ctx,
None => return Err(Error::OperationNotInitialized),
};
let data = data
.or(sign_ctx.payload.as_deref())
.ok_or(Error::OperationNotInitialized)?;
let signature = match sign_ctx.private_key.sign(&sign_ctx.algorithm, data) {
Ok(sig) => sig,
Err(e) => {
tracing::error!("signature failed: {e:?}");
return Err(Error::ArgumentsBad);
}
};
if !pSignature.is_null() {
// TODO(bweeks): This will cause a second sign call when this function is
// called again with an appropriately-sized buffer. Do we really need to
// sign twice for ECDSA? Consider storing the signature in the ctx for the next
// call.
if (unsafe { *pulSignatureLen } as usize) < signature.len() {
return Err(Error::BufferTooSmall);
}
unsafe { std::slice::from_raw_parts_mut(pSignature, signature.len()) }
.copy_from_slice(&signature);
self.sign_ctx = None;
}
unsafe { *pulSignatureLen = signature.len().try_into().unwrap() };
Ok(())
}
}
#[derive(Default)]
pub struct Session {
flags: CK_FLAGS,
pub find_ctx: Option<FindContext>,
pub sign_ctx: Option<SignContext>,
}
pub fn create(flags: CK_FLAGS) -> CK_SESSION_HANDLE {
let handle = NEXT_SESSION_HANDLE.fetch_add(1, Ordering::SeqCst);
SESSIONS.lock().unwrap().insert(
handle,
Session {
flags,
..Default::default()
},
);
handle
}
pub fn exists(handle: CK_SESSION_HANDLE) -> bool {
SESSIONS.lock().unwrap().contains_key(&handle)
}
pub fn flags(handle: CK_SESSION_HANDLE) -> CK_FLAGS {
SESSIONS.lock().unwrap().get(&handle).unwrap().flags
}
pub fn session<F>(h: CK_SESSION_HANDLE, callback: F) -> crate::Result
where
F: FnOnce(&mut Session) -> crate::Result,
{
let mut session_map = SESSIONS.lock().unwrap();
let session = &mut session_map.get_mut(&h).unwrap();
callback(session)
}
pub fn close(handle: CK_SESSION_HANDLE) -> bool {
SESSIONS.lock().unwrap().remove(&handle).is_some()
}
pub fn close_all() {
SESSIONS.lock().unwrap().clear()
}

View File

@@ -0,0 +1,45 @@
// 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::io::Write;
pub fn right_pad_string_to_array<const N: usize>(s: impl Into<String>) -> [u8; N] {
let mut s: String = s.into();
let new_len = (0..=N)
.rev()
.find(|idx| s.is_char_boundary(*idx))
.unwrap_or(0);
s.truncate(new_len);
let mut out = [b' '; N];
let _ = out.as_mut_slice().write_all(s.as_bytes());
out
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn string_padding() {
assert_eq!(right_pad_string_to_array::<4>("asd"), *b"asd ");
assert_eq!(right_pad_string_to_array::<3>("asd"), *b"asd");
assert_eq!(right_pad_string_to_array::<2>("asd"), *b"as");
assert_eq!(
right_pad_string_to_array::<5>("🧑‍🔬"),
// Utf-8 encoding of "person" followed by a space.
[0xF0, 0x9F, 0xA7, 0x91, b' ']
);
}
}

1
pkcs11-sys/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

12
pkcs11-sys/Cargo.toml Normal file
View File

@@ -0,0 +1,12 @@
[package]
name = "pkcs11-sys"
version = "0.2.18"
description = "Generated bindings for pkcs11.h. Useful for building PKCS#11 modules in rust."
authors.workspace = true
edition.workspace = true
rust-version.workspace = true
repository.workspace = true
license.workspace = true
[build-dependencies]
bindgen = { version = "0.69.4", optional = true }

201
pkcs11-sys/LICENSE Normal file
View 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.

188
pkcs11-sys/build.rs Normal file
View File

@@ -0,0 +1,188 @@
// 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.
#[cfg(feature = "bindgen")]
mod generate {
use bindgen::callbacks;
const LICENSE_HEADER: &str = r###"// 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."###;
#[derive(Debug)]
pub struct CargoCallbacks;
impl callbacks::ParseCallbacks for CargoCallbacks {
// https://github.com/rust-lang/rust-bindgen/issues/1594
fn int_macro(&self, name: &str, _: i64) -> Option<callbacks::IntKind> {
if ["CK_TRUE", "CK_FALSE"].contains(&name) {
Some(callbacks::IntKind::Custom {
name: "CK_BBOOL",
is_signed: false,
})
} else if name.starts_with("CK_") {
Some(callbacks::IntKind::Custom {
name: "CK_ULONG",
is_signed: false,
})
} else if name.starts_with("CKA_") {
Some(callbacks::IntKind::Custom {
name: "CK_ATTRIBUTE_TYPE",
is_signed: false,
})
} else if name.starts_with("CKC_") {
Some(callbacks::IntKind::Custom {
name: "CK_CERTIFICATE_TYPE",
is_signed: false,
})
} else if name.starts_with("CKD_") {
Some(callbacks::IntKind::Custom {
name: "CK_EC_KDF_TYPE",
is_signed: false,
})
} else if name.starts_with("CKF_") {
Some(callbacks::IntKind::Custom {
name: "CK_FLAGS",
is_signed: false,
})
} else if name.starts_with("CKG_MGF1_") {
Some(callbacks::IntKind::Custom {
name: "CK_RSA_PKCS_MGF_TYPE",
is_signed: false,
})
} else if name.starts_with("CKG_") {
Some(callbacks::IntKind::Custom {
name: "CK_GENERATOR_FUNCTION",
is_signed: false,
})
} else if name.starts_with("CKH_") {
Some(callbacks::IntKind::Custom {
name: "CK_HW_FEATURE_TYPE",
is_signed: false,
})
} else if name.starts_with("CKK_") {
Some(callbacks::IntKind::Custom {
name: "CK_KEY_TYPE",
is_signed: false,
})
} else if name.starts_with("CKM_") {
Some(callbacks::IntKind::Custom {
name: "CK_MECHANISM_TYPE",
is_signed: false,
})
} else if name.starts_with("CKN_") {
Some(callbacks::IntKind::Custom {
name: "CK_NOTIFICATION",
is_signed: false,
})
} else if name.starts_with("CKO_") {
Some(callbacks::IntKind::Custom {
name: "CK_OBJECT_CLASS",
is_signed: false,
})
} else if name.starts_with("CKP_") {
Some(callbacks::IntKind::Custom {
name: "CK_PROFILE_ID",
is_signed: false,
})
} else if name.starts_with("CKR_") {
Some(callbacks::IntKind::Custom {
name: "CK_RV",
is_signed: false,
})
} else if name.starts_with("CKS_") {
Some(callbacks::IntKind::Custom {
name: "CK_STATE",
is_signed: false,
})
} else if name.starts_with("CKU_") {
Some(callbacks::IntKind::Custom {
name: "CK_USER_TYPE",
is_signed: false,
})
} else if name.starts_with("CKZ_") {
Some(callbacks::IntKind::Custom {
name: "CK_RSA_PKCS_OAEP_SOURCE_TYPE",
is_signed: false,
})
} else if name.starts_with("CRYPTOKI_VERSION_") {
Some(callbacks::IntKind::Custom {
name: "CK_BYTE",
is_signed: false,
})
} else {
None
}
}
fn include_file(&self, filename: &str) {
println!("cargo:rerun-if-changed={filename}");
}
fn will_parse_macro(&self, name: &str) -> callbacks::MacroParsingBehavior {
if name.starts_with('_') {
callbacks::MacroParsingBehavior::Ignore
} else {
callbacks::MacroParsingBehavior::Default
}
}
}
#[allow(unused)]
fn windows_modifications(builder: bindgen::Builder) -> bindgen::Builder {
builder.blocklist_item("CK_UNAVAILABLE_INFORMATION")
}
fn target_specific_output_path() -> String {
format!("src/pkcs11_{}.rs", std::env::consts::FAMILY)
}
pub fn generate_main() {
println!("cargo:rerun-if-changed=pkcs11.h");
let bindings = bindgen::Builder::default()
.header("pkcs11.h")
.derive_default(true)
.parse_callbacks(Box::new(CargoCallbacks))
.raw_line(LICENSE_HEADER);
#[cfg(target_os = "windows")]
let bindings = windows_modifications(bindings);
let bindings = bindings.generate().expect("failed to generate bindings");
bindings
.write_to_file(target_specific_output_path())
.expect("failed to write bindings");
}
}
#[cfg(not(feature = "bindgen"))]
fn main() {}
#[cfg(feature = "bindgen")]
fn main() {
generate::generate_main();
}

43
pkcs11-sys/pkcs11.h Normal file
View File

@@ -0,0 +1,43 @@
// 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
//
// https://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.
// This header file incorporates WIN32-specific advice from
// https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/cs01/include/pkcs11-v3.1/pkcs11.h.
#if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32)
#define CK_DECLARE_FUNCTION(returnType, name) returnType __declspec(dllexport) name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType __declspec(dllimport)(*name)
/* There is a matching pop below. */
#pragma pack(push, cryptoki, 1)
#else
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType(*name)
#endif
#define CK_PTR *
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_CALLBACK_FUNCTION(returnType, name) returnType(*name)
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32)
#endif
#include "third_party/pkcs11/pkcs11.h"
#if defined(_WIN32) || defined(CRYPTOKI_FORCE_WIN32)
#pragma pack(pop, cryptoki)
#endif

29
pkcs11-sys/src/lib.rs Normal file
View File

@@ -0,0 +1,29 @@
// 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.
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#[cfg(target_os = "windows")]
mod pkcs11_windows;
#[cfg(target_os = "windows")]
pub use pkcs11_windows::*;
#[cfg(target_os = "windows")]
pub const CK_UNAVAILABLE_INFORMATION: u32 = u32::MAX;
#[cfg(not(target_os = "windows"))]
mod pkcs11_unix;
#[cfg(not(target_os = "windows"))]
pub use pkcs11_unix::*;

11723
pkcs11-sys/src/pkcs11_unix.rs Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1
pkcs11-sys/third_party Symbolic link
View File

@@ -0,0 +1 @@
../third_party

20
third_party/pkcs11/LICENSE vendored Normal file
View File

@@ -0,0 +1,20 @@
Copyright © OASIS Open 2022. All Rights Reserved.
All capitalized terms in the following text have the meanings assigned to them in the OASIS Intellectual Property Rights Policy (the "OASIS IPR Policy"). The full Policy may be found at the OASIS website: [https://www.oasis-open.org/policies-guidelines/ipr/].
This document and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published, and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this section are included on all such copies and derivative works. However, this document itself may not be modified in any way, including by removing the copyright notice or references to OASIS, except as needed for the purpose of developing any document or deliverable produced by an OASIS Technical Committee (in which case the rules applicable to copyrights, as set forth in the OASIS IPR Policy, must be followed) or as required to translate it into languages other than English.
The limited permissions granted above are perpetual and will not be revoked by OASIS or its successors or assigns.
This document and the information contained herein is provided on an "AS IS" basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. OASIS AND ITS MEMBERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THIS DOCUMENT OR ANY PART THEREOF.
As stated in the OASIS IPR Policy, the following three paragraphs in brackets apply to OASIS Standards Final Deliverable documents (Committee Specifications, OASIS Standards, or Approved Errata).
[OASIS requests that any OASIS Party or any other party that believes it has patent claims that would necessarily be infringed by implementations of this OASIS Standards Final Deliverable, to notify OASIS TC Administrator and provide an indication of its willingness to grant patent licenses to such patent claims in a manner consistent with the IPR Mode of the OASIS Technical Committee that produced this deliverable.]
[OASIS invites any party to contact the OASIS TC Administrator if it is aware of a claim of ownership of any patent claims that would necessarily be infringed by implementations of this OASIS Standards Final Deliverable by a patent holder that is not willing to provide a license to such patent claims in a manner consistent with the IPR Mode of the OASIS Technical Committee that produced this OASIS Standards Final Deliverable. OASIS may include such claims on its website, but disclaims any obligation to do so.]
[OASIS takes no position regarding the validity or scope of any intellectual property or other rights that might be claimed to pertain to the implementation or use of the technology described in this OASIS Standards Final Deliverable or the extent to which any license under such rights might or might not be available; neither does it represent that it has made any effort to identify any such rights. Information on OASIS' procedures with respect to rights in any document or deliverable produced by an OASIS Technical Committee can be found on the OASIS website. Copies of claims of rights made available for publication and any assurances of licenses to be made available, or the result of an attempt made to obtain a general license or permission for the use of such proprietary rights by implementers or users of this OASIS Standards Final Deliverable, can be obtained from the OASIS TC Administrator. OASIS makes no representation that any information or list of intellectual property rights will at any time be complete, or that any claims in such list are, in fact, Essential Claims.]
The name "OASIS" is a trademark of OASIS, the owner and developer of this document, and should be used only to refer to the organization and its official outputs. OASIS welcomes reference to, and implementation and use of, documents, while reserving the right to enforce its marks against misleading uses. Please see https://www.oasis-open.org/policies-guidelines/trademark/ for above guidance.

246
third_party/pkcs11/pkcs11.h vendored Executable file
View File

@@ -0,0 +1,246 @@
/*
* PKCS #11 Specification Version 3.1
* Committee Specification 01
* 11 August 2022
* Copyright (c) OASIS Open 2022. All Rights Reserved.
* Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/cs01/include/pkcs11-v3.1/
* Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
* TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
*/
#ifndef _PKCS11_H_
#define _PKCS11_H_ 1
#ifdef __cplusplus
extern "C" {
#endif
/* Before including this file (pkcs11.h) (or pkcs11t.h by
* itself), 5 platform-specific macros must be defined. These
* macros are described below, and typical definitions for them
* are also given. Be advised that these definitions can depend
* on both the platform and the compiler used (and possibly also
* on whether a Cryptoki library is linked statically or
* dynamically).
*
* In addition to defining these 5 macros, the packing convention
* for Cryptoki structures should be set. The Cryptoki
* convention on packing is that structures should be 1-byte
* aligned.
*
* If you're using Windows this might be done by using the following
* preprocessor directive before including pkcs11.h or pkcs11t.h:
*
* #pragma pack(push, cryptoki, 1)
*
* and using the following preprocessor directive after including
* pkcs11.h or pkcs11t.h:
*
* #pragma pack(pop, cryptoki)
*
* In a UNIX environment, you're on your own for this. You might
* not need to do (or be able to do!) anything.
*
*
* Now for the macros:
*
*
* 1. CK_PTR: The indirection string for making a pointer to an
* object. It can be used like this:
*
* typedef CK_BYTE CK_PTR CK_BYTE_PTR;
*
* If you're using Windows, it might be defined by:
*
* #define CK_PTR *
*
* In a typical UNIX environment, it might be defined by:
*
* #define CK_PTR *
*
*
* 2. CK_DECLARE_FUNCTION(returnType, name): A macro which makes
* an importable Cryptoki library function declaration out of a
* return type and a function name. It should be used in the
* following fashion:
*
* extern CK_DECLARE_FUNCTION(CK_RV, C_Initialize)(
* CK_VOID_PTR pReserved
* );
*
* If you're using Windows to declare a function in a Win32 Cryptoki .dll,
* it might be defined by:
*
* #define CK_DECLARE_FUNCTION(returnType, name) \
* returnType __declspec(dllimport) name
*
* In a UNIX environment, it might be defined by:
*
* #define CK_DECLARE_FUNCTION(returnType, name) \
* returnType name
*
*
* 3. CK_DECLARE_FUNCTION_POINTER(returnType, name): A macro
* which makes a Cryptoki API function pointer declaration or
* function pointer type declaration out of a return type and a
* function name. It should be used in the following fashion:
*
* // Define funcPtr to be a pointer to a Cryptoki API function
* // taking arguments args and returning CK_RV.
* CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtr)(args);
*
* or
*
* // Define funcPtrType to be the type of a pointer to a
* // Cryptoki API function taking arguments args and returning
* // CK_RV, and then define funcPtr to be a variable of type
* // funcPtrType.
* typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, funcPtrType)(args);
* funcPtrType funcPtr;
*
* If you're using Windows to access
* functions in a Win32 Cryptoki .dll, in might be defined by:
*
* #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
* returnType __declspec(dllimport) (* name)
*
* In a UNIX environment, it might be defined by:
*
* #define CK_DECLARE_FUNCTION_POINTER(returnType, name) \
* returnType (* name)
*
*
* 4. CK_CALLBACK_FUNCTION(returnType, name): A macro which makes
* a function pointer type for an application callback out of
* a return type for the callback and a name for the callback.
* It should be used in the following fashion:
*
* CK_CALLBACK_FUNCTION(CK_RV, myCallback)(args);
*
* to declare a function pointer, myCallback, to a callback
* which takes arguments args and returns a CK_RV. It can also
* be used like this:
*
* typedef CK_CALLBACK_FUNCTION(CK_RV, myCallbackType)(args);
* myCallbackType myCallback;
*
* If you're using Windows, it might be defined by:
*
* #define CK_CALLBACK_FUNCTION(returnType, name) \
* returnType (* name)
*
* In a UNIX environment, it might be defined by:
*
* #define CK_CALLBACK_FUNCTION(returnType, name) \
* returnType (* name)
*
*
* 5. NULL_PTR: This macro is the value of a NULL pointer.
*
* In any ANSI/ISO C environment (and in many others as well),
* this should best be defined by
*
* #ifndef NULL_PTR
* #define NULL_PTR 0
* #endif
*/
/* All the various Cryptoki types and #define'd values are in the
* file pkcs11t.h.
*/
#include "pkcs11t.h"
#define __PASTE(x,y) x##y
/* ==============================================================
* Define the "extern" form of all the entry points.
* ==============================================================
*/
#define CK_NEED_ARG_LIST 1
#define CK_PKCS11_FUNCTION_INFO(name) \
extern CK_DECLARE_FUNCTION(CK_RV, name)
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes.
*/
#include "pkcs11f.h"
#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO
/* ==============================================================
* Define the typedef form of all the entry points. That is, for
* each Cryptoki function C_XXX, define a type CK_C_XXX which is
* a pointer to that kind of function.
* ==============================================================
*/
#define CK_NEED_ARG_LIST 1
#define CK_PKCS11_FUNCTION_INFO(name) \
typedef CK_DECLARE_FUNCTION_POINTER(CK_RV, __PASTE(CK_,name))
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes.
*/
#include "pkcs11f.h"
#undef CK_NEED_ARG_LIST
#undef CK_PKCS11_FUNCTION_INFO
/* ==============================================================
* Define structed vector of entry points. A CK_FUNCTION_LIST
* contains a CK_VERSION indicating a library's Cryptoki version
* and then a whole slew of function pointers to the routines in
* the library. This type was declared, but not defined, in
* pkcs11t.h.
* ==============================================================
*/
#define CK_PKCS11_FUNCTION_INFO(name) \
__PASTE(CK_,name) name;
/* Create the 3.0 Function list */
struct CK_FUNCTION_LIST_3_0 {
CK_VERSION version; /* Cryptoki version */
/* Pile all the function pointers into the CK_FUNCTION_LIST. */
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes.
*/
#include "pkcs11f.h"
};
#define CK_PKCS11_2_0_ONLY 1
/* Continue to define the old CK_FUNCTION_LIST */
struct CK_FUNCTION_LIST {
CK_VERSION version; /* Cryptoki version */
/* Pile all the function pointers into the CK_FUNCTION_LIST. */
/* pkcs11f.h has all the information about the Cryptoki
* function prototypes.
*/
#include "pkcs11f.h"
};
#undef CK_PKCS11_FUNCTION_INFO
#undef CK_PKCS11_2_0_ONLY
#undef __PASTE
#ifdef __cplusplus
}
#endif
#endif /* _PKCS11_H_ */

1195
third_party/pkcs11/pkcs11f.h vendored Executable file

File diff suppressed because it is too large Load Diff

2523
third_party/pkcs11/pkcs11t.h vendored Executable file

File diff suppressed because it is too large Load Diff