1use core::fmt;
4use std::error::Error;
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError, RwLock};
8
9use cryptoki::context::{CInitializeArgs, CInitializeFlags, Pkcs11};
10use cryptoki::error::{Error as CryptokiError, RvError};
11use cryptoki::mechanism::eddsa::{EddsaParams, EddsaSignatureScheme};
12use cryptoki::mechanism::rsa::{PkcsMgfType, PkcsPssParams};
13use cryptoki::mechanism::{Mechanism, MechanismType};
14use cryptoki::object::{Attribute, AttributeType, KeyType as CkKeyType, ObjectClass, ObjectHandle};
15use cryptoki::session::{Session, UserType};
16use cryptoki::slot::Slot;
17use cryptoki::types::AuthPin;
18use sha2::{Digest as _, Sha256};
19
20use super::{KeyId, KeySpec, KeyStore, KeyStoreCapabilities, KeyStoreError};
21use crate::jose::{Jwk, JwsAlgorithm, KeyType, normalize_ecdsa_signature};
22
23const P256_PARAMS: &[u8] = &[0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07];
25const SECP256K1_PARAMS: &[u8] = &[0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x0a];
27const ED25519_PARAMS: &[u8] = &[0x06, 0x03, 0x2b, 0x65, 0x70];
30const ED25519_NAME_PARAMS: &[u8] = b"\x13\x0cedwards25519";
33pub const STAGING_LABEL_PREFIX: &str = "identity-kit-staging-";
35const RSA_PUBLIC_EXPONENT: &[u8] = &[0x01, 0x00, 0x01];
37const SHA256_DIGEST_INFO_PREFIX: &[u8] = &[
40 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05,
41 0x00, 0x04, 0x20,
42];
43
44#[derive(Debug, Clone, PartialEq, Eq, Hash)]
57#[non_exhaustive]
58pub enum Pkcs11Token {
59 Label(String),
62 Slot(u64),
66}
67
68impl From<&str> for Pkcs11Token {
69 fn from(label: &str) -> Self {
70 Self::Label(label.to_owned())
71 }
72}
73
74impl From<String> for Pkcs11Token {
75 fn from(label: String) -> Self {
76 Self::Label(label)
77 }
78}
79
80impl From<u64> for Pkcs11Token {
81 fn from(slot: u64) -> Self {
82 Self::Slot(slot)
83 }
84}
85
86impl fmt::Display for Pkcs11Token {
87 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88 match self {
89 Self::Label(label) => write!(f, "token `{label}`"),
90 Self::Slot(slot) => write!(f, "slot {slot}"),
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
115#[non_exhaustive]
116pub struct Pkcs11KeyStoreOptions {
117 pub sessions: usize,
122 pub rsa_algorithm: JwsAlgorithm,
130 pub algorithms: Option<Vec<JwsAlgorithm>>,
137}
138
139impl Default for Pkcs11KeyStoreOptions {
140 fn default() -> Self {
141 Self {
142 sessions: 4,
143 rsa_algorithm: JwsAlgorithm::RS256,
144 algorithms: None,
145 }
146 }
147}
148
149impl Pkcs11KeyStoreOptions {
150 pub fn new() -> Self {
152 Self::default()
153 }
154
155 #[must_use]
157 pub fn sessions(mut self, sessions: usize) -> Self {
158 self.sessions = sessions;
159 self
160 }
161
162 #[must_use]
164 pub fn rsa_algorithm(mut self, alg: JwsAlgorithm) -> Self {
165 self.rsa_algorithm = alg;
166 self
167 }
168
169 #[must_use]
171 pub fn algorithms(mut self, algorithms: impl IntoIterator<Item = JwsAlgorithm>) -> Self {
172 self.algorithms = Some(algorithms.into_iter().collect());
173 self
174 }
175}
176
177#[derive(Debug, thiserror::Error)]
179#[non_exhaustive]
180pub enum Pkcs11Error {
181 #[error("PKCS#11 module `{}`: {source}", module.display())]
183 Module {
184 module: PathBuf,
186 #[source]
188 source: CryptokiError,
189 },
190 #[error("PKCS#11 module has no {0}")]
192 TokenNotFound(Pkcs11Token),
193 #[error("PKCS#11 key store options: {0}")]
195 InvalidOptions(String),
196 #[error("PKCS#11 {function} failed: {source}")]
198 Call {
199 function: &'static str,
201 #[source]
203 source: CryptokiError,
204 },
205 #[error("PKCS#11 module returned a {actual}-byte signature for {alg}, expected {expected}")]
207 SignatureLength {
208 alg: JwsAlgorithm,
210 expected: usize,
212 actual: usize,
214 },
215}
216
217impl Pkcs11Error {
218 fn call(function: &'static str) -> impl FnOnce(CryptokiError) -> KeyStoreError {
220 move |source| KeyStoreError::backend(Self::Call { function, source })
221 }
222
223 fn closes_session(&self) -> bool {
225 matches!(
226 self,
227 Self::Call {
228 source: CryptokiError::Pkcs11(
229 RvError::SessionHandleInvalid
230 | RvError::SessionClosed
231 | RvError::DeviceRemoved
232 | RvError::DeviceError
233 | RvError::TokenNotPresent,
234 _
235 ),
236 ..
237 }
238 )
239 }
240}
241
242#[derive(Clone)]
292pub struct Pkcs11KeyStore {
293 inner: Arc<Inner>,
294}
295
296struct Inner {
298 module: PathBuf,
299 context: Pkcs11,
300 slot: Slot,
301 token_label: String,
302 pin: Option<AuthPin>,
303 options: Pkcs11KeyStoreOptions,
304 algorithms: Vec<JwsAlgorithm>,
306 key_pair_generation: Vec<MechanismType>,
308 write_protected: bool,
309 pool: Pool,
310 writes: Arc<RwLock<()>>,
313}
314
315struct Pool {
317 state: Mutex<PoolState>,
318 available: Condvar,
320 max: usize,
322}
323
324#[derive(Default)]
325struct PoolState {
326 idle: Vec<Session>,
327 open: usize,
329}
330
331impl Pkcs11KeyStore {
332 pub fn open(
348 module: impl AsRef<Path>,
349 token: impl Into<Pkcs11Token>,
350 pin: Option<&str>,
351 ) -> Result<Self, KeyStoreError> {
352 Self::open_with(module, token, pin, Pkcs11KeyStoreOptions::default())
353 }
354
355 pub fn open_with(
361 module: impl AsRef<Path>,
362 token: impl Into<Pkcs11Token>,
363 pin: Option<&str>,
364 options: Pkcs11KeyStoreOptions,
365 ) -> Result<Self, KeyStoreError> {
366 let module = module.as_ref().to_path_buf();
367 let token = token.into();
368 if options.sessions == 0 {
369 return Err(invalid_options("`sessions` must be at least 1"));
370 }
371 if !matches!(
372 options.rsa_algorithm,
373 JwsAlgorithm::RS256 | JwsAlgorithm::PS256
374 ) {
375 return Err(invalid_options(format!(
376 "`rsa_algorithm` must be RS256 or PS256, not {}",
377 options.rsa_algorithm
378 )));
379 }
380
381 let context = load_module(&module)?;
382
383 let (slot, token_label, write_protected) = find_token(&context, &token)?;
384 let mechanisms = context
385 .get_mechanism_list(slot)
386 .map_err(Pkcs11Error::call("C_GetMechanismList"))?;
387 let mut algorithms = Vec::new();
388 if mechanisms.contains(&MechanismType::EDDSA) {
389 algorithms.push(JwsAlgorithm::EdDSA);
390 }
391 if mechanisms.contains(&MechanismType::ECDSA) {
392 algorithms.push(JwsAlgorithm::ES256);
393 #[cfg(feature = "secp256k1")]
394 algorithms.push(JwsAlgorithm::ES256K);
395 }
396 let rsa_mechanism = match options.rsa_algorithm {
397 JwsAlgorithm::PS256 => MechanismType::RSA_PKCS_PSS,
398 _ => MechanismType::RSA_PKCS,
399 };
400 if mechanisms.contains(&rsa_mechanism) {
401 algorithms.push(options.rsa_algorithm);
402 }
403 if let Some(wanted) = &options.algorithms {
404 algorithms.retain(|alg| wanted.contains(alg));
405 }
406 let key_pair_generation = [
407 MechanismType::ECC_EDWARDS_KEY_PAIR_GEN,
408 MechanismType::ECC_KEY_PAIR_GEN,
409 MechanismType::RSA_PKCS_KEY_PAIR_GEN,
410 ]
411 .into_iter()
412 .filter(|mechanism| mechanisms.contains(mechanism))
413 .collect();
414
415 let writes = token_writes(&module, slot.id());
416 let inner = Inner {
417 writes,
418 module,
419 context,
420 slot,
421 token_label,
422 pin: pin.map(|pin| AuthPin::from(pin.to_owned())),
423 pool: Pool {
424 state: Mutex::new(PoolState::default()),
425 available: Condvar::new(),
426 max: options.sessions,
427 },
428 options,
429 algorithms,
430 key_pair_generation,
431 write_protected,
432 };
433 let session = inner.open_session()?;
435 inner.pool.release(session);
436 Ok(Self {
437 inner: Arc::new(inner),
438 })
439 }
440
441 pub fn module(&self) -> &Path {
443 &self.inner.module
444 }
445
446 pub fn slot(&self) -> u64 {
448 self.inner.slot.id()
449 }
450
451 pub fn token_label(&self) -> &str {
453 &self.inner.token_label
454 }
455
456 pub fn options(&self) -> &Pkcs11KeyStoreOptions {
458 &self.inner.options
459 }
460
461 async fn blocking<T, F>(&self, f: F) -> Result<T, KeyStoreError>
463 where
464 T: Send + 'static,
465 F: FnOnce(&Inner) -> Result<T, KeyStoreError> + Send + 'static,
466 {
467 let inner = Arc::clone(&self.inner);
468 match tokio::task::spawn_blocking(move || f(&inner)).await {
469 Ok(result) => result,
470 Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
471 Err(e) => Err(KeyStoreError::backend(e)),
472 }
473 }
474}
475
476impl fmt::Debug for Pkcs11KeyStore {
477 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478 f.debug_struct("Pkcs11KeyStore")
479 .field("module", &self.inner.module)
480 .field("slot", &self.inner.slot.id())
481 .field("token_label", &self.inner.token_label)
482 .field("algorithms", &self.inner.algorithms)
483 .field("options", &self.inner.options)
484 .finish_non_exhaustive()
485 }
486}
487
488#[async_trait::async_trait]
489impl KeyStore for Pkcs11KeyStore {
490 fn capabilities(&self) -> KeyStoreCapabilities {
491 let capabilities =
492 KeyStoreCapabilities::new(self.inner.algorithms.iter().copied()).remote();
493 if self.inner.write_protected {
494 capabilities
495 } else {
496 capabilities.with_generate().with_delete()
497 }
498 }
499
500 async fn public_jwk(&self, key: &KeyId) -> Result<Jwk, KeyStoreError> {
501 let key = key.clone();
502 self.blocking(move |inner| inner.reading(|session| inner.public_jwk(session, &key)))
503 .await
504 }
505
506 async fn sign(
507 &self,
508 key: &KeyId,
509 alg: JwsAlgorithm,
510 data: &[u8],
511 ) -> Result<Vec<u8>, KeyStoreError> {
512 let key = key.clone();
513 let data = data.to_vec();
514 self.blocking(move |inner| inner.reading(|session| inner.sign(session, &key, alg, &data)))
515 .await
516 }
517
518 async fn exists(&self, key: &KeyId) -> Result<bool, KeyStoreError> {
519 let key = key.clone();
520 self.blocking(move |inner| {
521 inner
522 .reading(|session| Ok(find_key(session, ObjectClass::PRIVATE_KEY, &key)?.is_some()))
523 })
524 .await
525 }
526
527 async fn generate(&self, spec: KeySpec) -> Result<KeyId, KeyStoreError> {
528 if self.inner.write_protected {
529 return Err(KeyStoreError::Unsupported("generate"));
530 }
531 self.blocking(move |inner| inner.writing(|session| inner.generate(session, &spec)))
532 .await
533 }
534
535 async fn delete(&self, key: &KeyId) -> Result<(), KeyStoreError> {
536 if self.inner.write_protected {
537 return Err(KeyStoreError::Unsupported("delete"));
538 }
539 let key = key.clone();
540 self.blocking(move |inner| inner.writing(|session| delete(session, &key)))
541 .await
542 }
543}
544
545impl Inner {
546 fn open_session(&self) -> Result<Session, KeyStoreError> {
551 let session = if self.write_protected {
552 self.context.open_ro_session(self.slot)
553 } else {
554 self.context.open_rw_session(self.slot)
555 }
556 .map_err(Pkcs11Error::call("C_OpenSession"))?;
557 if let Some(pin) = &self.pin {
558 match session.login(UserType::User, Some(pin)) {
559 Ok(()) | Err(CryptokiError::Pkcs11(RvError::UserAlreadyLoggedIn, _)) => {}
562 Err(source) => return Err(Pkcs11Error::call("C_Login")(source)),
563 }
564 }
565 Ok(session)
566 }
567
568 fn reading<T>(
572 &self,
573 f: impl FnOnce(&Session) -> Result<T, KeyStoreError>,
574 ) -> Result<T, KeyStoreError> {
575 self.with_session(|session| {
576 let _reading = self.writes.read().unwrap_or_else(PoisonError::into_inner);
577 f(session)
578 })
579 }
580
581 fn writing<T>(
583 &self,
584 f: impl FnOnce(&Session) -> Result<T, KeyStoreError>,
585 ) -> Result<T, KeyStoreError> {
586 self.with_session(|session| {
587 let _writing = self.writes.write().unwrap_or_else(PoisonError::into_inner);
588 f(session)
589 })
590 }
591
592 fn with_session<T>(
596 &self,
597 f: impl FnOnce(&Session) -> Result<T, KeyStoreError>,
598 ) -> Result<T, KeyStoreError> {
599 let session = self.pool.acquire(|| self.open_session())?;
600 let result = f(&session);
601 let dead = matches!(
602 &result,
603 Err(KeyStoreError::Backend(e))
604 if e.downcast_ref::<Pkcs11Error>().is_some_and(Pkcs11Error::closes_session)
605 );
606 if dead {
607 self.pool.discard(session);
608 } else {
609 self.pool.release(session);
610 }
611 result
612 }
613
614 fn algorithm_of(&self, kind: KeyKind) -> JwsAlgorithm {
616 match kind {
617 KeyKind::Ed25519 => JwsAlgorithm::EdDSA,
618 KeyKind::P256 => JwsAlgorithm::ES256,
619 KeyKind::Secp256k1 => JwsAlgorithm::ES256K,
620 KeyKind::Rsa => self.options.rsa_algorithm,
621 }
622 }
623
624 fn public_jwk(&self, session: &Session, key: &KeyId) -> Result<Jwk, KeyStoreError> {
626 let Some(public) = find_key(session, ObjectClass::PUBLIC_KEY, key)? else {
627 return Err(
628 if find_key(session, ObjectClass::PRIVATE_KEY, key)?.is_some() {
629 KeyStoreError::invalid_key(
630 key.clone(),
631 "the token has no public key object with this label",
632 )
633 } else {
634 KeyStoreError::NotFound(key.clone())
635 },
636 );
637 };
638 self.public_jwk_of(session, key, public)
639 }
640
641 fn public_jwk_of(
643 &self,
644 session: &Session,
645 key: &KeyId,
646 public: ObjectHandle,
647 ) -> Result<Jwk, KeyStoreError> {
648 let kind = key_kind(session, key, public)?;
649 let invalid = |reason: &str| KeyStoreError::invalid_key(key.clone(), reason);
650 let not_a_jwk = |error: crate::jose::JwkError| KeyStoreError::InvalidKey {
651 key: key.clone(),
652 reason: "the public key does not convert to a JWK".to_owned(),
653 source: Some(Box::new(error)),
654 };
655 let jwk = match kind {
656 KeyKind::Rsa => {
657 let attributes = session
658 .get_attributes(
659 public,
660 &[AttributeType::Modulus, AttributeType::PublicExponent],
661 )
662 .map_err(Pkcs11Error::call("C_GetAttributeValue"))?;
663 let mut modulus = None;
664 let mut exponent = None;
665 for attribute in attributes {
666 match attribute {
667 Attribute::Modulus(n) => modulus = Some(n),
668 Attribute::PublicExponent(e) => exponent = Some(e),
669 _ => {}
670 }
671 }
672 let (Some(n), Some(e)) = (modulus, exponent) else {
673 return Err(invalid(
674 "the public key object has no modulus or public exponent",
675 ));
676 };
677 Jwk::from_rsa_public(&n, &e).map_err(not_a_jwk)?
678 }
679 KeyKind::Ed25519 | KeyKind::P256 | KeyKind::Secp256k1 => {
680 let point = ec_point(session, key, public, kind)?;
681 match kind {
682 KeyKind::Ed25519 => Jwk::from_ed25519_public(&point).map_err(not_a_jwk)?,
683 KeyKind::P256 => Jwk::from_p256_public(&point).map_err(not_a_jwk)?,
684 #[cfg(feature = "secp256k1")]
685 KeyKind::Secp256k1 => Jwk::from_secp256k1_public(&point).map_err(not_a_jwk)?,
686 #[cfg(not(feature = "secp256k1"))]
687 KeyKind::Secp256k1 => {
688 return Err(invalid("secp256k1 keys need the `secp256k1` feature"));
689 }
690 KeyKind::Rsa => unreachable!("matched above"),
691 }
692 }
693 };
694 Ok(jwk
695 .with_kid(key.as_str())
696 .with_alg(self.algorithm_of(kind).as_str()))
697 }
698
699 fn sign(
701 &self,
702 session: &Session,
703 key: &KeyId,
704 alg: JwsAlgorithm,
705 data: &[u8],
706 ) -> Result<Vec<u8>, KeyStoreError> {
707 let private = find_key(session, ObjectClass::PRIVATE_KEY, key)?
708 .ok_or_else(|| KeyStoreError::NotFound(key.clone()))?;
709 let kind = key_kind(session, key, private)?;
710 let key_alg = self.algorithm_of(kind);
711 if alg != key_alg {
712 return Err(KeyStoreError::AlgorithmMismatch {
713 key: key.clone(),
714 key_alg,
715 requested: alg,
716 });
717 }
718 if !self.algorithms.contains(&alg) {
719 return Err(KeyStoreError::UnsupportedAlgorithm(alg));
720 }
721 let signature = match kind {
722 KeyKind::Ed25519 => session
723 .sign(
724 &Mechanism::Eddsa(EddsaParams::new(EddsaSignatureScheme::Pure)),
725 private,
726 data,
727 )
728 .map_err(Pkcs11Error::call("C_Sign"))?,
729 KeyKind::P256 => session
730 .sign(&Mechanism::Ecdsa, private, &Sha256::digest(data))
731 .map_err(Pkcs11Error::call("C_Sign"))?,
732 KeyKind::Secp256k1 => {
733 let signature = session
734 .sign(&Mechanism::Ecdsa, private, &Sha256::digest(data))
735 .map_err(Pkcs11Error::call("C_Sign"))?;
736 normalize_ecdsa_signature(alg, &signature).unwrap_or(signature)
740 }
741 KeyKind::Rsa if alg == JwsAlgorithm::PS256 => {
742 let params = PkcsPssParams {
743 hash_alg: MechanismType::SHA256,
744 mgf: PkcsMgfType::MGF1_SHA256,
745 s_len: 32.into(),
746 };
747 session
748 .sign(
749 &Mechanism::RsaPkcsPss(params),
750 private,
751 &Sha256::digest(data),
752 )
753 .map_err(Pkcs11Error::call("C_Sign"))?
754 }
755 KeyKind::Rsa => {
756 let mut digest_info = SHA256_DIGEST_INFO_PREFIX.to_vec();
757 digest_info.extend_from_slice(&Sha256::digest(data));
758 session
759 .sign(&Mechanism::RsaPkcs, private, &digest_info)
760 .map_err(Pkcs11Error::call("C_Sign"))?
761 }
762 };
763 if let Some(expected) = match kind {
764 KeyKind::Ed25519 | KeyKind::P256 | KeyKind::Secp256k1 => Some(64),
765 KeyKind::Rsa => None,
766 } && signature.len() != expected
767 {
768 return Err(KeyStoreError::backend(Pkcs11Error::SignatureLength {
769 alg,
770 expected,
771 actual: signature.len(),
772 }));
773 }
774 Ok(signature)
775 }
776
777 #[expect(
779 clippy::too_many_lines,
780 reason = "one template per key type, kept side by side to compare"
781 )]
782 fn generate(&self, session: &Session, spec: &KeySpec) -> Result<KeyId, KeyStoreError> {
783 spec.validate()?;
784 if !self.algorithms.contains(&spec.alg) {
785 return Err(KeyStoreError::UnsupportedAlgorithm(spec.alg));
786 }
787 let (mechanism, generation, mut public_template) = match spec.key_type {
788 KeyType::Ed25519 => (
789 Mechanism::EccEdwardsKeyPairGen,
790 MechanismType::ECC_EDWARDS_KEY_PAIR_GEN,
791 vec![
792 Attribute::KeyType(CkKeyType::EC_EDWARDS),
793 Attribute::EcParams(ED25519_PARAMS.to_vec()),
794 ],
795 ),
796 KeyType::P256 => (
797 Mechanism::EccKeyPairGen,
798 MechanismType::ECC_KEY_PAIR_GEN,
799 vec![
800 Attribute::KeyType(CkKeyType::EC),
801 Attribute::EcParams(P256_PARAMS.to_vec()),
802 ],
803 ),
804 KeyType::Secp256k1 => (
805 Mechanism::EccKeyPairGen,
806 MechanismType::ECC_KEY_PAIR_GEN,
807 vec![
808 Attribute::KeyType(CkKeyType::EC),
809 Attribute::EcParams(SECP256K1_PARAMS.to_vec()),
810 ],
811 ),
812 KeyType::Rsa2048 | KeyType::Rsa4096 => {
813 let bits: cryptoki::types::Ulong = match spec.key_type {
814 KeyType::Rsa4096 => 4096.into(),
815 _ => 2048.into(),
816 };
817 (
818 Mechanism::RsaPkcsKeyPairGen,
819 MechanismType::RSA_PKCS_KEY_PAIR_GEN,
820 vec![
821 Attribute::KeyType(CkKeyType::RSA),
822 Attribute::ModulusBits(bits),
823 Attribute::PublicExponent(RSA_PUBLIC_EXPONENT.to_vec()),
824 ],
825 )
826 }
827 };
828 if !self.key_pair_generation.contains(&generation) {
829 return Err(KeyStoreError::UnsupportedKeyType(spec.key_type));
830 }
831 public_template.extend([
832 Attribute::Token(true),
833 Attribute::Private(false),
834 Attribute::Verify(true),
835 ]);
836 let mut private_template = vec![
837 Attribute::Token(true),
838 Attribute::Private(true),
839 Attribute::Sensitive(true),
840 Attribute::Extractable(false),
841 Attribute::Sign(true),
842 ];
843 if let Some(label) = &spec.label {
844 let id = KeyId::new(label.as_str());
845 if find_key(session, ObjectClass::PRIVATE_KEY, &id)?.is_some()
846 || find_key(session, ObjectClass::PUBLIC_KEY, &id)?.is_some()
847 {
848 return Err(KeyStoreError::AlreadyExists(id));
849 }
850 public_template.extend(label_attributes(label));
851 private_template.extend(label_attributes(label));
852 } else {
853 let staging = staging_label();
857 public_template.extend(label_attributes(&staging));
858 private_template.extend(label_attributes(&staging));
859 }
860
861 let (public, private) = session
862 .generate_key_pair(&mechanism, &public_template, &private_template)
863 .map_err(Pkcs11Error::call("C_GenerateKeyPair"))?;
864 if let Some(label) = &spec.label {
865 return Ok(KeyId::new(label.as_str()));
866 }
867 let labelled = self
870 .public_jwk_of(session, &KeyId::new(""), public)
871 .and_then(|jwk| {
872 jwk.thumbprint_sha256()
873 .map_err(|e| KeyStoreError::InvalidKey {
874 key: KeyId::new(""),
875 reason: "no RFC 7638 thumbprint".to_owned(),
876 source: Some(Box::new(e)),
877 })
878 })
879 .and_then(|thumbprint| {
880 let attributes = label_attributes(&thumbprint);
881 session
882 .update_attributes(public, &attributes)
883 .and_then(|()| session.update_attributes(private, &attributes))
884 .map_err(Pkcs11Error::call("C_SetAttributeValue"))?;
885 Ok(KeyId::new(thumbprint))
886 });
887 if labelled.is_err() {
888 let _ = session.destroy_object(private);
890 let _ = session.destroy_object(public);
891 }
892 labelled
893 }
894}
895
896impl Pool {
897 fn acquire(
900 &self,
901 open: impl FnOnce() -> Result<Session, KeyStoreError>,
902 ) -> Result<Session, KeyStoreError> {
903 let mut state = self.lock();
904 loop {
905 if let Some(session) = state.idle.pop() {
906 return Ok(session);
907 }
908 if state.open < self.max {
909 state.open += 1;
910 drop(state);
911 return open().inspect_err(|_| {
912 self.lock().open -= 1;
913 self.available.notify_one();
914 });
915 }
916 state = self
917 .available
918 .wait(state)
919 .unwrap_or_else(PoisonError::into_inner);
920 }
921 }
922
923 fn release(&self, session: Session) {
925 self.lock().idle.push(session);
926 self.available.notify_one();
927 }
928
929 fn discard(&self, session: Session) {
931 drop(session);
932 self.lock().open -= 1;
933 self.available.notify_one();
934 }
935
936 fn lock(&self) -> MutexGuard<'_, PoolState> {
938 self.state.lock().unwrap_or_else(PoisonError::into_inner)
939 }
940}
941
942static MODULES: Mutex<Vec<(PathBuf, Pkcs11)>> = Mutex::new(Vec::new());
948
949static TOKEN_WRITES: Mutex<Vec<TokenWriteLock>> = Mutex::new(Vec::new());
961
962type TokenWriteLock = ((PathBuf, u64), Arc<RwLock<()>>);
964
965fn token_writes(module: &Path, slot: u64) -> Arc<RwLock<()>> {
967 let key = (
968 std::fs::canonicalize(module).unwrap_or_else(|_| module.to_path_buf()),
969 slot,
970 );
971 let mut locks = TOKEN_WRITES.lock().unwrap_or_else(PoisonError::into_inner);
972 if let Some((_, lock)) = locks.iter().find(|(k, _)| *k == key) {
973 return Arc::clone(lock);
974 }
975 let lock = Arc::new(RwLock::new(()));
976 locks.push((key, Arc::clone(&lock)));
977 lock
978}
979
980fn load_module(module: &Path) -> Result<Pkcs11, KeyStoreError> {
982 let key = std::fs::canonicalize(module).unwrap_or_else(|_| module.to_path_buf());
983 let mut modules = MODULES.lock().unwrap_or_else(PoisonError::into_inner);
984 if let Some((_, context)) = modules.iter().find(|(path, _)| *path == key) {
985 return Ok(context.clone());
986 }
987 let failed = |source| {
988 KeyStoreError::backend(Pkcs11Error::Module {
989 module: module.to_path_buf(),
990 source,
991 })
992 };
993 let context = Pkcs11::new(module).map_err(failed)?;
994 match context.initialize(CInitializeArgs::new(CInitializeFlags::OS_LOCKING_OK)) {
996 Ok(()) | Err(CryptokiError::Pkcs11(RvError::CryptokiAlreadyInitialized, _)) => {}
997 Err(source) => return Err(failed(source)),
998 }
999 modules.push((key, context.clone()));
1000 Ok(context)
1001}
1002
1003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1005enum KeyKind {
1006 Ed25519,
1007 P256,
1008 Secp256k1,
1009 Rsa,
1010}
1011
1012fn find_token(
1014 context: &Pkcs11,
1015 token: &Pkcs11Token,
1016) -> Result<(Slot, String, bool), KeyStoreError> {
1017 let not_found = || KeyStoreError::backend(Pkcs11Error::TokenNotFound(token.clone()));
1018 let slots = context
1019 .get_slots_with_token()
1020 .map_err(Pkcs11Error::call("C_GetSlotList"))?;
1021 for slot in slots {
1022 let matches = match token {
1023 Pkcs11Token::Slot(id) => slot.id() == *id,
1024 Pkcs11Token::Label(_) => true,
1025 };
1026 if !matches {
1027 continue;
1028 }
1029 let info = context
1030 .get_token_info(slot)
1031 .map_err(Pkcs11Error::call("C_GetTokenInfo"))?;
1032 let label = info.label().trim_end().to_owned();
1033 if let Pkcs11Token::Label(wanted) = token
1034 && label != wanted.trim_end()
1035 {
1036 continue;
1037 }
1038 return Ok((slot, label, info.write_protected()));
1039 }
1040 Err(not_found())
1041}
1042
1043fn find_key(
1045 session: &Session,
1046 class: ObjectClass,
1047 key: &KeyId,
1048) -> Result<Option<ObjectHandle>, KeyStoreError> {
1049 let template = [
1050 Attribute::Class(class),
1051 Attribute::Label(key.as_str().as_bytes().to_vec()),
1052 ];
1053 let objects = session
1054 .find_objects(&template)
1055 .map_err(Pkcs11Error::call("C_FindObjects"))?;
1056 match objects.as_slice() {
1057 [] => Ok(None),
1058 [object] => Ok(Some(*object)),
1059 several => Err(KeyStoreError::invalid_key(
1060 key.clone(),
1061 format!(
1062 "the label names {} objects of the same class",
1063 several.len()
1064 ),
1065 )),
1066 }
1067}
1068
1069fn delete(session: &Session, key: &KeyId) -> Result<(), KeyStoreError> {
1074 let private = find_key(session, ObjectClass::PRIVATE_KEY, key)?;
1075 let public = find_key(session, ObjectClass::PUBLIC_KEY, key)?;
1076 if private.is_none() && public.is_none() {
1077 return Err(KeyStoreError::NotFound(key.clone()));
1078 }
1079 let mut destroyed = Ok(());
1080 for object in [private, public].into_iter().flatten() {
1081 destroyed = destroyed.and(session.destroy_object(object));
1082 }
1083 destroyed.map_err(Pkcs11Error::call("C_DestroyObject"))
1084}
1085
1086#[expect(
1089 clippy::cast_possible_truncation,
1090 reason = "the low 64 bits of the time are plenty to keep labels apart"
1091)]
1092fn staging_label() -> String {
1093 static COUNTER: AtomicU64 = AtomicU64::new(0);
1094 let nanos = std::time::SystemTime::now()
1095 .duration_since(std::time::UNIX_EPOCH)
1096 .map_or(0, |since| since.as_nanos() as u64);
1097 format!(
1098 "{STAGING_LABEL_PREFIX}{nanos:016x}-{:x}",
1099 COUNTER.fetch_add(1, Ordering::Relaxed)
1100 )
1101}
1102
1103fn label_attributes(label: &str) -> [Attribute; 2] {
1106 [
1107 Attribute::Label(label.as_bytes().to_vec()),
1108 Attribute::Id(label.as_bytes().to_vec()),
1109 ]
1110}
1111
1112fn key_kind(
1114 session: &Session,
1115 key: &KeyId,
1116 object: ObjectHandle,
1117) -> Result<KeyKind, KeyStoreError> {
1118 let attributes = session
1119 .get_attributes(object, &[AttributeType::KeyType, AttributeType::EcParams])
1120 .map_err(Pkcs11Error::call("C_GetAttributeValue"))?;
1121 let mut key_type = None;
1122 let mut params = None;
1123 for attribute in attributes {
1124 match attribute {
1125 Attribute::KeyType(t) => key_type = Some(t),
1126 Attribute::EcParams(p) => params = Some(p),
1127 _ => {}
1128 }
1129 }
1130 let invalid = |reason: &str| KeyStoreError::invalid_key(key.clone(), reason);
1131 match key_type {
1132 Some(CkKeyType::RSA) => Ok(KeyKind::Rsa),
1133 Some(CkKeyType::EC) => match params.as_deref() {
1134 Some(P256_PARAMS) => Ok(KeyKind::P256),
1135 Some(SECP256K1_PARAMS) => Ok(KeyKind::Secp256k1),
1136 Some(_) => Err(invalid("the curve is not P-256 or secp256k1")),
1137 None => Err(invalid("the EC key has no CKA_EC_PARAMS")),
1138 },
1139 Some(CkKeyType::EC_EDWARDS) => match params.as_deref() {
1140 Some(ED25519_PARAMS | ED25519_NAME_PARAMS) => Ok(KeyKind::Ed25519),
1141 Some(_) => Err(invalid("the Edwards curve is not Ed25519")),
1142 None => Err(invalid("the Edwards key has no CKA_EC_PARAMS")),
1143 },
1144 Some(_) => Err(invalid("the key type is not RSA, EC or EC_EDWARDS")),
1145 None => Err(invalid("the object has no CKA_KEY_TYPE")),
1146 }
1147}
1148
1149fn ec_point(
1153 session: &Session,
1154 key: &KeyId,
1155 object: ObjectHandle,
1156 kind: KeyKind,
1157) -> Result<Vec<u8>, KeyStoreError> {
1158 let attributes = session
1159 .get_attributes(object, &[AttributeType::EcPoint])
1160 .map_err(Pkcs11Error::call("C_GetAttributeValue"))?;
1161 let invalid = |reason: &str| KeyStoreError::invalid_key(key.clone(), reason);
1162 let Some(Attribute::EcPoint(encoded)) = attributes.into_iter().next() else {
1163 return Err(invalid("the public key object has no CKA_EC_POINT"));
1164 };
1165 ec_point_bytes(&encoded, kind)
1166 .map(<[u8]>::to_vec)
1167 .ok_or_else(|| invalid("CKA_EC_POINT is neither a DER OCTET STRING nor a bare point"))
1168}
1169
1170fn ec_point_bytes(encoded: &[u8], kind: KeyKind) -> Option<&[u8]> {
1176 let fits = |point: &[u8]| match kind {
1177 KeyKind::Ed25519 => point.len() == 32,
1178 KeyKind::P256 | KeyKind::Secp256k1 => point.len() == 65 && point[0] == 0x04,
1179 KeyKind::Rsa => false,
1180 };
1181 match der_octet_string(encoded) {
1182 Some(content) if fits(content) => Some(content),
1183 _ if fits(encoded) => Some(encoded),
1184 other => other,
1185 }
1186}
1187
1188fn der_octet_string(der: &[u8]) -> Option<&[u8]> {
1190 let (&0x04, rest) = der.split_first()? else {
1191 return None;
1192 };
1193 let (&first, rest) = rest.split_first()?;
1194 let (length, content) = if first < 0x80 {
1195 (usize::from(first), rest)
1196 } else {
1197 let length_bytes = usize::from(first & 0x7f);
1198 if length_bytes == 0 || length_bytes > 2 || rest.len() < length_bytes {
1199 return None;
1200 }
1201 let (length, content) = rest.split_at(length_bytes);
1202 let length = length
1203 .iter()
1204 .fold(0usize, |n, &b| (n << 8) | usize::from(b));
1205 if length < 0x80 {
1207 return None;
1208 }
1209 (length, content)
1210 };
1211 (content.len() == length).then_some(content)
1212}
1213
1214fn invalid_options(reason: impl Into<String>) -> KeyStoreError {
1216 KeyStoreError::backend(Pkcs11Error::InvalidOptions(reason.into()))
1217}
1218
1219const _: () = {
1221 const fn assert_send_sync<T: Send + Sync + Error + 'static>() {}
1222 assert_send_sync::<Pkcs11Error>();
1223};
1224
1225#[cfg(test)]
1226mod tests {
1227 use super::*;
1228
1229 #[test]
1230 fn der_octet_strings_decode() {
1231 assert_eq!(
1233 der_octet_string(&[0x04, 0x02, 0xaa, 0xbb]),
1234 Some(&[0xaa, 0xbb][..])
1235 );
1236 assert_eq!(der_octet_string(&[0x04, 0x00]), Some(&[][..]));
1237 let mut long = vec![0x04, 0x81, 0x80];
1239 long.extend(std::iter::repeat_n(7u8, 128));
1240 assert_eq!(der_octet_string(&long), Some(&long[3..]));
1241 let mut longer = vec![0x04, 0x82, 0x01, 0x00];
1242 longer.extend(std::iter::repeat_n(7u8, 256));
1243 assert_eq!(der_octet_string(&longer), Some(&longer[4..]));
1244
1245 assert_eq!(der_octet_string(&[0x03, 0x01, 0xaa]), None);
1247 assert_eq!(der_octet_string(&[0x04]), None);
1248 assert_eq!(der_octet_string(&[0x04, 0x03, 0xaa, 0xbb]), None);
1249 assert_eq!(der_octet_string(&[0x04, 0x01, 0xaa, 0xbb]), None);
1250 assert_eq!(der_octet_string(&[0x04, 0x81, 0x01, 0xaa]), None);
1251 assert_eq!(der_octet_string(&[0x04, 0x80]), None);
1252 assert_eq!(
1253 der_octet_string(&[0x04, 0x83, 0x00, 0x00, 0x01, 0xaa]),
1254 None
1255 );
1256 assert_eq!(der_octet_string(&[]), None);
1257 }
1258
1259 #[test]
1260 fn ec_points_are_read_wrapped_or_bare() {
1261 let ed25519 = [7u8; 32];
1262 let mut wrapped = vec![0x04, 0x20];
1263 wrapped.extend_from_slice(&ed25519);
1264 assert_eq!(
1265 ec_point_bytes(&wrapped, KeyKind::Ed25519),
1266 Some(&ed25519[..])
1267 );
1268 assert_eq!(
1269 ec_point_bytes(&ed25519, KeyKind::Ed25519),
1270 Some(&ed25519[..])
1271 );
1272 let mut tricky = vec![0x04, 0x1e];
1275 tricky.extend_from_slice(&[9u8; 30]);
1276 assert_eq!(ec_point_bytes(&tricky, KeyKind::Ed25519), Some(&tricky[..]));
1277
1278 let mut sec1 = vec![0x04];
1279 sec1.extend_from_slice(&[1u8; 64]);
1280 let mut wrapped = vec![0x04, 0x41];
1281 wrapped.extend_from_slice(&sec1);
1282 for kind in [KeyKind::P256, KeyKind::Secp256k1] {
1283 assert_eq!(ec_point_bytes(&wrapped, kind), Some(&sec1[..]));
1284 assert_eq!(ec_point_bytes(&sec1, kind), Some(&sec1[..]));
1285 assert_eq!(ec_point_bytes(&[0x04, 0x01, 0xaa], kind), Some(&[0xaa][..]));
1288 }
1289 let mut compressed = vec![0x02];
1291 compressed.extend_from_slice(&[1u8; 64]);
1292 assert_eq!(ec_point_bytes(&compressed, KeyKind::P256), None);
1293 assert_eq!(ec_point_bytes(&[0x05, 0x01, 0xaa], KeyKind::P256), None);
1294 assert_eq!(ec_point_bytes(&ed25519, KeyKind::Rsa), None);
1295 }
1296
1297 #[test]
1298 fn staging_labels_are_distinct() {
1299 let a = staging_label();
1300 let b = staging_label();
1301 assert!(a.starts_with(STAGING_LABEL_PREFIX) && b.starts_with(STAGING_LABEL_PREFIX));
1302 assert_ne!(a, b);
1303 assert!(a.len() <= 64, "fits the usual label limits: {a}");
1304 }
1305
1306 #[test]
1307 fn the_digest_info_prefix_is_the_one_of_rfc_8017() {
1308 let mut digest_info = SHA256_DIGEST_INFO_PREFIX.to_vec();
1310 digest_info.extend_from_slice(&[0u8; 32]);
1311 assert_eq!(digest_info.len(), 51);
1312 assert_eq!(digest_info[1], 0x31, "SEQUENCE length covers the rest");
1313 assert_eq!(
1314 &digest_info[4..13],
1315 &[0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04]
1316 );
1317 assert_eq!(&digest_info[13..15], &[0x02, 0x01], "id-sha256");
1318 assert_eq!(
1319 &digest_info[17..19],
1320 &[0x04, 0x20],
1321 "OCTET STRING of 32 bytes"
1322 );
1323 }
1324
1325 #[test]
1326 fn tokens_convert_and_display() {
1327 assert_eq!(Pkcs11Token::from("a"), Pkcs11Token::Label("a".to_owned()));
1328 assert_eq!(
1329 Pkcs11Token::from("a".to_owned()),
1330 Pkcs11Token::Label("a".to_owned())
1331 );
1332 assert_eq!(Pkcs11Token::from(7), Pkcs11Token::Slot(7));
1333 assert_eq!(Pkcs11Token::from("a").to_string(), "token `a`");
1334 assert_eq!(Pkcs11Token::from(7).to_string(), "slot 7");
1335 }
1336
1337 #[test]
1338 fn options_default_and_build() {
1339 let options = Pkcs11KeyStoreOptions::new();
1340 assert_eq!(options, Pkcs11KeyStoreOptions::default());
1341 assert_eq!(options.sessions, 4);
1342 assert_eq!(options.rsa_algorithm, JwsAlgorithm::RS256);
1343 assert_eq!(options.algorithms, None);
1344 let options = options
1345 .sessions(1)
1346 .rsa_algorithm(JwsAlgorithm::PS256)
1347 .algorithms([JwsAlgorithm::EdDSA]);
1348 assert_eq!(options.sessions, 1);
1349 assert_eq!(options.rsa_algorithm, JwsAlgorithm::PS256);
1350 assert_eq!(options.algorithms, Some(vec![JwsAlgorithm::EdDSA]));
1351 }
1352
1353 #[test]
1354 fn bad_options_are_refused_before_the_module_loads() {
1355 let no_sessions = Pkcs11KeyStore::open_with(
1356 "/nonexistent/module.so",
1357 "token",
1358 None,
1359 Pkcs11KeyStoreOptions::new().sessions(0),
1360 )
1361 .unwrap_err();
1362 assert_eq!(
1363 no_sessions.to_string(),
1364 "key store backend error: PKCS#11 key store options: `sessions` must be at least 1"
1365 );
1366 let wrong_rsa = Pkcs11KeyStore::open_with(
1367 "/nonexistent/module.so",
1368 "token",
1369 None,
1370 Pkcs11KeyStoreOptions::new().rsa_algorithm(JwsAlgorithm::ES256),
1371 )
1372 .unwrap_err();
1373 assert_eq!(
1374 wrong_rsa.to_string(),
1375 "key store backend error: PKCS#11 key store options: `rsa_algorithm` must be RS256 or PS256, not ES256"
1376 );
1377 }
1378
1379 #[test]
1380 fn a_missing_module_is_reported_with_its_path() {
1381 let error = Pkcs11KeyStore::open("/nonexistent/module.so", "token", None).unwrap_err();
1382 let KeyStoreError::Backend(source) = &error else {
1383 panic!("expected Backend, got {error:?}");
1384 };
1385 let pkcs11 = source.downcast_ref::<Pkcs11Error>().expect("a Pkcs11Error");
1386 assert!(
1387 matches!(pkcs11, Pkcs11Error::Module { module, .. } if module == Path::new("/nonexistent/module.so"))
1388 );
1389 assert!(
1390 error
1391 .to_string()
1392 .starts_with("key store backend error: PKCS#11 module `/nonexistent/module.so`: "),
1393 "{error}"
1394 );
1395 assert!(pkcs11.source().is_some());
1396 }
1397
1398 #[test]
1399 fn errors_that_close_a_session_are_known() {
1400 let call = |rv| Pkcs11Error::Call {
1401 function: "C_Sign",
1402 source: CryptokiError::Pkcs11(rv, cryptoki::context::Function::Sign),
1403 };
1404 assert!(call(RvError::SessionHandleInvalid).closes_session());
1405 assert!(call(RvError::DeviceRemoved).closes_session());
1406 assert!(!call(RvError::KeyHandleInvalid).closes_session());
1407 assert!(!Pkcs11Error::TokenNotFound(Pkcs11Token::Slot(1)).closes_session());
1408 assert_eq!(
1409 Pkcs11Error::SignatureLength {
1410 alg: JwsAlgorithm::ES256,
1411 expected: 64,
1412 actual: 70
1413 }
1414 .to_string(),
1415 "PKCS#11 module returned a 70-byte signature for ES256, expected 64"
1416 );
1417 }
1418}