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

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' ']
);
}
}