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