1use std::borrow::Cow;
2use std::collections::BTreeMap;
3use std::path::Path;
4use std::path::PathBuf;
5use std::sync::Arc;
6use std::sync::Mutex;
7use std::sync::Weak;
8use std::sync::atomic::AtomicBool;
9
10use anyhow::Context as _;
11
12use cryptoki::object::Attribute;
13use cryptoki::object::AttributeType;
14use cryptoki::object::KeyType;
15use cryptoki::object::ObjectClass;
16use cryptoki::object::ObjectHandle;
17use cryptoki::session::Session;
18use cryptoki::session::UserType;
19use cryptoki::slot::Slot;
20use cryptoki::slot::TokenInfo;
21use cryptoki::types::AuthPin;
22
23use sequoia_openpgp as openpgp;
24use openpgp::Fingerprint;
25use openpgp::packet::key::PublicParts;
26use openpgp::packet::key::UnspecifiedRole;
27use openpgp::packet;
28
29use crate::Context;
30use crate::Result;
31use crate::KeySelector;
32use crate::TokenSelector;
33
34const TRACE: bool = false;
35
36struct Pkcs11 {
37 inner: Option<cryptoki::context::Pkcs11>,
38}
39
40impl std::fmt::Debug for Pkcs11 {
41 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
42 {
43 if let Some(pkcs11) = self.inner.as_ref() {
44 write!(f, "{:?}", pkcs11)
45 } else {
46 write!(f, "<finalized PKCS11 context>")
47 }
48 }
49}
50
51impl Drop for Pkcs11 {
52 fn drop(&mut self) {
53 if let Some(pkcs11) = self.inner.take() {
54 if let Err(err) = pkcs11.finalize() {
55 eprintln!("Finalizing PKCS11 context: {}", err);
56 }
57 }
58 }
59}
60
61impl std::ops::Deref for Pkcs11 {
62 type Target = cryptoki::context::Pkcs11;
63
64 fn deref(&self) -> &Self::Target {
65 self.inner.as_ref().expect("not finalized")
67 }
68}
69
70impl From<cryptoki::context::Pkcs11> for Pkcs11 {
71 fn from(pkcs11: cryptoki::context::Pkcs11) -> Self {
72 Self {
73 inner: Some(pkcs11),
74 }
75 }
76}
77
78#[derive(Clone, Debug)]
85pub struct Backend {
86 lib: PathBuf,
87 pub(crate) lib_str: String,
89 context: Arc<Pkcs11>,
90}
91
92impl Backend {
93 pub fn context(&self) -> &cryptoki::context::Pkcs11 {
95 &self.context
96 }
97
98 pub fn lib(&self) -> &Path {
100 &self.lib
101 }
102
103 pub fn lib_short(&self) -> &str {
113 let lib = &self.lib_str[..];
114
115 if let Some(i) = lib.rfind('/') {
116 if i < lib.len() - 1 {
118 let file_name = &lib[i + 1 ..];
119
120 if let Some(dot) = file_name.find('.') {
122 let prefix = &file_name[..dot];
123 if let Some(inner) = prefix.strip_prefix("lib") {
125 return inner;
126 } else {
127 return prefix;
128 }
129 }
130 return file_name;
131 }
132 }
133
134 &lib[..]
135 }
136
137 pub fn is_lib(&self, query: &str) -> bool {
147 tracer!(false, "is_lib");
148 t!("Checking if {} matches {}", query, self.lib.display());
149
150 if query.as_bytes() == self.lib.as_os_str().as_encoded_bytes() {
151 t!("Exact match");
153 return true;
154 } else if query.contains(&['/', '\\']) {
155 t!("Not an exact match, and name contains a path separator. Giving up.");
158 return false;
159 };
160
161 let path = PathBuf::from(&self.lib);
162 if let Some(file_name) = path.file_name() {
163 t!("Considering {}",
164 String::from_utf8_lossy(file_name.as_encoded_bytes()));
165 if file_name == query {
166 t!("Match");
168 return true;
169 }
170
171 let query = query.as_bytes();
172 let file_name = file_name.as_encoded_bytes();
173
174 let mut first = true;
175 for (i, c) in file_name.iter().enumerate() {
176 if *c == b'.' {
177 let prefix = &file_name[..i];
178
179 t!("Considering {}",
180 String::from_utf8_lossy(prefix));
181
182 if prefix == query {
183 t!("Match");
184 return true;
185 }
186
187 if first {
188 if prefix.starts_with(b"lib") {
189 let middle = &prefix[3..];
190
191 t!("Considering {}",
192 String::from_utf8_lossy(middle));
193 if middle == query {
194 t!("Match");
195 return true;
196 }
197 }
198 }
199 first = false;
200 }
201 }
202 }
203
204 t!("Not a match");
205 false
206 }
207}
208
209#[derive(Clone, Debug)]
218pub struct Token {
219 backend: Backend,
220 slot: Slot,
221 info: TokenInfo,
222}
223
224impl Token {
225 pub fn backend(&self) -> &Backend {
227 &self.backend
228 }
229
230 pub fn slot(&self) -> &Slot {
232 &self.slot
233 }
234
235 pub fn info(&self) -> &TokenInfo {
241 &self.info
242 }
243
244 pub fn open_ro_session(&self)
254 -> Result<cryptoki::session::Session>
255 {
256 let session = self.backend().context.clone()
257 .open_ro_session(self.slot().clone())?;
258 Ok(session)
259 }
260
261 pub fn open_ro_user_session<P>(&self, pin: P)
266 -> Result<cryptoki::session::Session>
267 where
268 P: Into<AuthPin>
269 {
270 let session = self.open_ro_session()?;
271 session.login(UserType::User, Some(&pin.into()))?;
272 Ok(session)
273 }
274
275 pub fn open_rw_session(&self)
285 -> Result<cryptoki::session::Session>
286 {
287 let session = self.backend().context.clone()
288 .open_rw_session(self.slot().clone())?;
289 Ok(session)
290 }
291
292 pub fn open_rw_user_session<P>(&self, pin: P)
297 -> Result<cryptoki::session::Session>
298 where
299 P: Into<AuthPin>
300 {
301 let session = self.backend().context.clone()
302 .open_rw_session(self.slot().clone())?;
303 session.login(UserType::User, Some(&pin.into()))?;
304 Ok(session)
305 }
306
307 pub fn same_as(&self, other: &Self) -> bool {
310 self.info().serial_number() == other.info().serial_number()
311 }
312}
313
314impl std::fmt::Display for Token {
315 fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
316 -> std::result::Result<(), std::fmt::Error>
317 {
318 let mut label = self.info().label();
319 if label.is_empty() {
320 label = "<no label>";
321 }
322 let manufacturer_id = self.info().manufacturer_id();
323 let model = self.info().model();
324 let serial_number = self.info().serial_number();
325
326 let product = match (manufacturer_id.is_empty(), model.is_empty()) {
327 (true, true) => Cow::Borrowed("Unknown product"),
328 (true, false) => manufacturer_id.into(),
329 (false, true) => model.into(),
330 (false, false) => {
331 if model.contains(manufacturer_id) {
332 model.into()
333 } else {
334 format!("{} {}", manufacturer_id, model).into()
335 }
336 }
337 };
338
339 let mut id = if serial_number.is_empty() {
340 format!("{} ({})", label, product)
341 } else {
342 format!("{} ({}, serial number: {})", label, product, serial_number)
343 };
344
345 if id.chars().any(|c| c.is_control()) {
346 id = format!("{:?}", id);
348 } else {
349 id = id.replace("\n", "-");
351 id = id.replace("\r", "-");
352 }
353
354 write!(f, "{}", id)
355 }
356}
357
358#[derive(Debug)]
415pub struct Key {
416 token: Token,
417
418 composite_key: Option<Box<Key>>,
423
424 object_class: Option<ObjectClass>,
426 key_type: KeyType,
427 key_unique_id: Option<Vec<u8>>,
428 key_label: Option<Vec<u8>>,
429 key_id: Option<Vec<u8>>,
430 key_url: Option<Vec<u8>>,
431 pub(crate) openpgp_key: Mutex<Option<packet::Key<PublicParts, UnspecifiedRole>>>,
432
433 pub(crate) got_capabilities: AtomicBool,
434 pub(crate) signing_capable: AtomicBool,
435 pub(crate) decryption_capable: AtomicBool,
436}
437
438impl Clone for Key {
439 fn clone(&self) -> Self {
440 Self {
441 token: self.token.clone(),
442 composite_key: self.composite_key.clone(),
443 object_class: self.object_class.clone(),
444 key_type: self.key_type.clone(),
445 key_unique_id: self.key_unique_id.clone(),
446 key_label: self.key_label.clone(),
447 key_id: self.key_id.clone(),
448 key_url: self.key_url.clone(),
449 openpgp_key: Mutex::new(
450 self.openpgp_key.lock().unwrap().as_ref().map(|k| k.clone())),
451
452 got_capabilities: false.into(),
453 signing_capable: false.into(),
454 decryption_capable: false.into(),
455 }
456 }
457}
458
459impl Key {
460 pub(crate) fn composite_key(&self) -> Option<&Key> {
465 self.composite_key.as_deref()
466 }
467
468 pub(crate) fn combine_with(&mut self, mut key: Key) {
474 assert!(self.composite_key.is_none());
475 assert!(key.composite_key.is_none());
476
477 assert!((self.is_secondary() && ! key.is_secondary())
478 || (! self.is_secondary() && key.is_secondary()));
479
480 if self.is_secondary() {
481 std::mem::swap(self, &mut key);
482 }
483
484 self.composite_key = Some(Box::new(key));
485 }
486
487 pub fn backend(&self) -> &Backend {
489 self.token.backend()
490 }
491
492 pub fn token(&self) -> &Token {
494 &self.token
495 }
496
497 pub fn slot(&self) -> &Slot {
499 self.token.slot()
500 }
501
502 pub fn info(&self) -> &TokenInfo {
508 self.token.info()
509 }
510
511 pub fn composite_token(&self) -> Option<&Token> {
513 self.composite_key()
514 .map(|k| k.token())
515 }
516
517 pub fn object_class(&self) -> Option<ObjectClass> {
523 self.object_class.clone()
524 }
525
526 pub fn key_type(&self) -> KeyType {
528 self.key_type
529 }
530
531 pub(crate) fn is_secondary(&self) -> bool {
537 match self.key_type() {
538 KeyType::ML_KEM => true,
539 KeyType::ML_DSA => true,
540 _ => false,
541 }
542 }
543
544 pub fn key_unique_id(&self) -> Option<&[u8]> {
546 self.key_unique_id.as_deref()
547 }
548
549 pub fn key_unique_id_hex(&self) -> Option<String> {
551 self.key_unique_id()
552 .map(|id| {
553 id.iter()
554 .map(|x| format!("{:02x}", x))
555 .collect::<Vec<String>>()
556 .join("")
557 })
558 }
559
560 pub fn key_label(&self) -> Option<&[u8]> {
562 self.key_label.as_deref()
563 }
564
565 pub fn key_id(&self) -> Option<&[u8]> {
567 self.key_id.as_deref()
568 }
569
570 pub fn key_url(&self) -> Option<&[u8]> {
572 self.key_url.as_deref()
573 }
574
575 pub fn open_ro_session(&self)
578 -> Result<(Session, ObjectHandle)>
579 {
580 let session
581 = self.backend().context().open_ro_session(self.slot().clone())?;
582
583 let mut attrs = Vec::with_capacity(5);
584 if let Some(object_class) = self.object_class {
585 attrs.push(Attribute::Class(object_class));
586 }
587 if let Some(unique_id) = self.key_unique_id() {
588 attrs.push(Attribute::UniqueId(unique_id.to_vec()));
589 }
590 if let Some(label) = self.key_label() {
591 attrs.push(Attribute::Label(label.to_vec()));
592 }
593 if let Some(id) = self.key_id() {
594 attrs.push(Attribute::Id(id.to_vec()));
595 }
596 if let Some(url) = self.key_url() {
597 attrs.push(Attribute::Url(url.to_vec()));
598 }
599
600 let mut objects = session.iter_objects(&attrs)
601 .with_context(|| {
602 format!("Listing {}'s objects",
603 self.backend().lib().display())
604 })?;
605
606 let first = objects.next();
607 let second = objects.next();
608 let object = match (first, second) {
609 (Some(object), None) => object.context("Getting private key")?,
610 (Some(_), Some(_)) => {
611 return Err(anyhow::anyhow!(
612 "Multiple keys correspond to the key descriptor, \
613 cowardly refusing to continue."));
614 }
615 (None, _) => {
616 return Err(anyhow::anyhow!("Key object disappeared"));
617 }
618 };
619 drop(objects);
620
621 Ok((session, object))
622 }
623
624 pub fn from_object(token: Token, session: &Session, object: ObjectHandle)
630 -> Result<Self>
631 {
632 let mut object_class = None;
634 let mut key_type = None;
635 let mut key_unique_id = None;
636 let mut key_label = None;
637 let mut key_id = None;
638 let mut key_url = None;
639
640 let attributes = session.get_attributes(
643 object,
644 &[
645 AttributeType::Class,
646 AttributeType::KeyType,
647 AttributeType::UniqueId,
648 AttributeType::Label,
649 AttributeType::Id,
650 AttributeType::Url,
651 ])?;
652 for attribute in attributes {
653 if let Attribute::Class(value) = attribute {
654 object_class = Some(value);
655 } else if let Attribute::KeyType(value) = attribute {
656 key_type = Some(value);
657 } else if let Attribute::UniqueId(value) = attribute {
658 key_unique_id = Some(value);
659 } else if let Attribute::Label(value) = attribute {
660 key_label = Some(value);
661 } else if let Attribute::Id(value) = attribute {
662 key_id = Some(value);
663 } else if let Attribute::Url(value) = attribute {
664 key_url = Some(value);
665 } else {
666 unreachable!("get_attributes only returns \
667 requested attributes");
668 }
669 }
670
671 let Some(key_type) = key_type else {
672 return Err(anyhow::anyhow!(
673 "Invalid object: missing key type attribute"));
674 };
675
676 Ok(Self {
677 token,
678 composite_key: None,
679 object_class,
680 key_type,
681 key_unique_id,
682 key_label,
683 key_id,
684 key_url,
685 openpgp_key: Mutex::new(None),
686
687 got_capabilities: false.into(),
688 signing_capable: false.into(),
689 decryption_capable: false.into(),
690 })
691 }
692
693 pub fn fingerprint(&self) -> Option<Fingerprint> {
697 self.to_openpgp_key().ok().map(|key| key.fingerprint())
698 }
699}
700
701#[derive(Debug)]
704enum KeyOrToken {
705 Key(Key),
706 Token(Token),
707}
708
709impl KeyOrToken {
710 fn is_key(&self) -> bool {
711 self.key().is_some()
712 }
713
714 fn key(&self) -> Option<&Key> {
715 match self {
716 KeyOrToken::Key(key) => Some(key),
717 KeyOrToken::Token(_) => None,
718 }
719 }
720
721 fn key_unwrap(&self) -> &Key {
722 self.key().expect(
723 "Internal error: looked up a key, got a token")
724 }
725
726 fn key_mut(&mut self) -> Option<&mut Key> {
727 match self {
728 KeyOrToken::Key(key) => Some(key),
729 KeyOrToken::Token(_) => None,
730 }
731 }
732
733 fn key_mut_unwrap(&mut self) -> &mut Key {
734 self.key_mut().expect(
735 "Internal error: looked up a key, got a token")
736 }
737
738 fn into_key_unwrap(self) -> Key {
739 match self {
740 KeyOrToken::Key(key) => key,
741 KeyOrToken::Token(_) =>
742 panic!("Internal error: looked up a token, got a key"),
743 }
744 }
745
746 fn into_token_unwrap(self) -> Token {
747 match self {
748 KeyOrToken::Key(_) =>
749 panic!("Internal error: looked up a token, got a key"),
750 KeyOrToken::Token(token) => token,
751 }
752 }
753
754}
755
756#[derive(Debug, Clone, Eq, PartialEq)]
760enum AllowedMatches {
761 None,
762 One,
763 Any,
764}
765
766#[derive(Debug, Clone, Eq, PartialEq)]
771pub enum SelectorScope {
772 All,
773 PublicKeys,
774 PrivateKeys,
775}
776
777static BACKENDS: Mutex<BTreeMap<PathBuf, Weak<Pkcs11>>>
780 = Mutex::new(BTreeMap::new());
781
782impl Context {
783 pub fn backends(&self) -> Result<&[Backend]> {
789 tracer!(TRACE, "Context::backends");
790
791 if let Some(backends) = self.backends.get() {
792 return Ok(backends);
793 }
794
795 let modules = self.config.modules();
796 let mut backends = Vec::with_capacity(modules.len());
797 let mut load_err = None;
798 let mut init_err = None;
799 for lib in modules {
800 t!("Loading {}", lib.display());
801
802 let mut backend = BACKENDS.lock().unwrap();
804 if let Some(context) = backend.get(lib) {
805 if let Some(context) = context.upgrade() {
806 t!("Loaded {} (cached)", lib.display());
807
808 backends.push(Backend {
809 lib: lib.clone(),
810 lib_str: lib.display().to_string(),
811 context,
812 });
813
814 continue;
815 }
816 }
817
818 let context = match cryptoki::context::Pkcs11::new(lib) {
819 Ok(context) => context,
820 Err(err) => {
821 log::debug!("{}: Error loading {}: {}",
822 func!(), lib.display(), err);
823 if load_err.is_none() {
824 load_err = Some(err);
825 }
826 continue;
827 }
828 };
829
830 match context.initialize(
832 cryptoki::context::CInitializeArgs::new(
833 cryptoki::context::CInitializeFlags::OS_LOCKING_OK))
834 {
835 Ok(context) => context,
836 Err(err) => {
837 log::debug!("{}: Error initializing {}: {}",
838 func!(), lib.display(), err);
839 if init_err.is_none() {
840 init_err = Some(err);
841 }
842 continue;
843 }
844 };
845 t!("Loaded {}", lib.display());
846
847 let context = Arc::new(context.into());
848
849 backend.insert(lib.clone(), Arc::downgrade(&context));
851
852 backends.push(Backend {
853 lib: lib.clone(),
854 lib_str: lib.display().to_string(),
855 context,
856 });
857 }
858
859 if let Some(err) = init_err {
860 return Err(err.into());
861 }
862 if let Some(err) = load_err {
863 return Err(err.into());
864 }
865
866 let _ = self.backends.set(backends);
867 let backends = self.backends.get().expect("just set");
868 Ok(backends)
869 }
870
871 fn select_internal(&self, selector: &KeySelector, key: bool,
880 allowed_matches: AllowedMatches,
881 scope: SelectorScope,
882 get_constituent: bool)
883 -> Result<Vec<KeyOrToken>>
884 {
885 tracer!(TRACE, "Context::select_internal");
886
887 let mut all: Vec<KeyOrToken> = Vec::new();
890 let mut matches: Vec<KeyOrToken> = Vec::new();
891
892 let mut backend_matched = false;
895 let mut backend_names = Vec::new();
896
897 for backend in self.backends()? {
898 backend_names.push(backend.lib_short());
899 if ! selector.backend_matches(&backend) {
900 continue;
901 } else {
902 backend_matched = true;
903 }
904
905 let slots = match backend.context().get_all_slots() {
906 Ok(slots) => slots,
907 Err(err) => {
908 log::debug!("{}: Failed to enumerate slots for {}: {}",
909 func!(), backend.lib().display(), err);
910 continue;
911 }
912 };
913 t!("{} has {} slots", backend.lib().display(), slots.len());
914 'slot_loop: for slot in slots.into_iter() {
915 let info = match backend.context().get_token_info(slot.clone()) {
916 Ok(info) => info,
917 Err(err) => {
918 t!("Failed to get token info for slot {}: {}",
919 slot.id(), err);
920 continue 'slot_loop;
921 }
922 };
923
924 let matches_token =
925 selector.slot_matches(slot.id())
926 && selector.token_label_matches(info.label())
927 && selector.token_serial_number_matches(
928 info.serial_number());
929
930 if ! key {
931 let token = Token {
933 backend: backend.clone(),
934 slot: slot,
935 info: info.clone(),
936 };
937
938 if matches_token {
939 matches.push(KeyOrToken::Token(token));
940 } else {
941 all.push(KeyOrToken::Token(token));
942 }
943 } else {
944 let session = match backend.context().open_ro_session(slot) {
946 Ok(session) => session,
947 Err(err) => {
948 log::debug!(
949 "{}: Warning: {}'s slot {} is unusable: {}",
950 func!(),
951 backend.lib().display(), slot.id(),
952 err);
953 continue 'slot_loop;
954 }
955 };
956
957 let attrs = match scope {
959 SelectorScope::All => &[][..],
960 SelectorScope::PublicKeys => {
961 &[ Attribute::Class(ObjectClass::PUBLIC_KEY) ]
962 }
963 SelectorScope::PrivateKeys => {
964 &[ Attribute::Class(ObjectClass::PRIVATE_KEY) ]
965 }
966 };
967 let objects = match session.iter_objects(attrs) {
968 Ok(objects) => objects,
969 Err(err) => {
970 log::debug!(
971 "{}: Error listing {}'s objects: {}",
972 func!(),
973 backend.lib().display(),
974 err);
975 continue 'slot_loop;
976 }
977 };
978
979 'obj_loop: for (i, object) in objects.enumerate() {
980 let object = match object {
981 Ok(object) => object,
982 Err(err) => {
983 log::debug!(
984 "{}: Error reading object #{}: {}",
985 func!(), i + 1, err);
986 continue 'obj_loop;
987 }
988 };
989
990 let token = Token {
992 backend: backend.clone(),
993 slot: slot,
994 info: info.clone(),
995 };
996 let key = match Key::from_object(
997 token, &session, object)
998 {
999 Ok(key) => key,
1000 Err(err) => {
1001 t!("Reading object #{}'s attributes: {}",
1002 i + i, err);
1003 continue 'obj_loop;
1004 }
1005 };
1006 let matches_key_unique_id
1007 = selector.key_unique_id_matches(key.key_unique_id());
1008
1009 let matches_key_label = if let Some(l) = selector.key_label() {
1010 Some(l.as_bytes()) == key.key_label()
1012 } else {
1013 true
1015 };
1016
1017 let matches_key_id = selector.key_id_matches(key.key_id());
1018 let matches_key_url = selector.key_url_matches(key.key_url());
1019
1020 if matches_token
1021 && matches_key_unique_id && matches_key_label
1022 && matches_key_id && matches_key_url
1023 {
1024 matches.push(KeyOrToken::Key(key));
1025 } else {
1026 all.push(KeyOrToken::Key(key));
1027 }
1028 }
1029 }
1030 }
1031 }
1032
1033 if key && get_constituent {
1035 'next_match: for i in 0..matches.len() {
1036 if i >= matches.len() {
1037 break;
1039 }
1040
1041 let m = &matches[i];
1046 let key = m.key_unwrap();
1047 let key_id = if let Some(key_id) = key.key_id() {
1048 match String::from_utf8(key_id.to_vec()) {
1049 Ok(key_id) => key_id,
1050 Err(_err) => {
1051 continue;
1053 }
1054 }
1055 } else {
1056 continue;
1057 };
1058
1059 let map = &[
1062 ("pgp:v6t:", "pgp:v6pq:"),
1063 ("pgp:v4t:", "pgp:v4pq:"),
1064 ];
1065
1066 let mut other_key_id = None;
1067 for (one, other) in map.into_iter().map(|(a, b)| (*a, *b))
1068 .chain(map.into_iter().map(|(a, b)| (*b, *a)))
1070 {
1071 if let Some(suffix) = key_id.strip_prefix(one) {
1072 other_key_id = Some(format!("{}{}", other, suffix));
1073 break;
1074 }
1075 }
1076
1077 let other_key_id = if let Some(other_key_id) = other_key_id {
1078 other_key_id
1079 } else {
1080 continue;
1082 };
1083
1084 if i + 1 < matches.len() {
1089 for j in i + 1..matches.len() {
1090 let other = matches[j].key_unwrap();
1091 if other.key_id() == Some(other_key_id.as_bytes()) {
1092 let other = matches.remove(j).into_key_unwrap();
1094 matches[i].key_mut_unwrap().combine_with(other);
1095 continue 'next_match;
1096 }
1097 }
1098 }
1099
1100 let other = self.select_internal(
1104 &KeySelector::from_key_id(other_key_id),
1105 true, AllowedMatches::One,
1107 SelectorScope::PublicKeys,
1108 false, );
1110 match other {
1111 Ok(results) => {
1112 assert_eq!(results.len(), 1);
1113 let other = results.into_iter().next().unwrap();
1114 let other = other.into_key_unwrap();
1115 matches[i].key_mut_unwrap().combine_with(other);
1116 }
1117 Err(err) => {
1118 log::debug!(
1119 "{}: Warning: {} is a composite key, \
1120 but half the key is missing: {}",
1121 func!(), key_id, err);
1122 }
1123 }
1124 }
1125 }
1126
1127 let obj = if key { "key" } else { "token" };
1128 let objs = if key { "keys" } else { "tokens" };
1129
1130 if allowed_matches == AllowedMatches::None {
1131 if matches.len() == 0 {
1133 Ok(vec![])
1134 } else {
1135 log::debug!("{}: The {} selector {} matches existing {}:",
1136 func!(), obj, selector.args(), objs);
1137 Self::list_matches(matches);
1138
1139 if key {
1140 Err(anyhow::anyhow!(
1141 "The {} selector matches existing {}, choose a \
1142 different label or use --ambiguous-key-label, \
1143 or --random-key-label",
1144 obj, objs))
1145 } else {
1146 Err(anyhow::anyhow!(
1147 "The {} selector matches existing {}", obj, objs))
1148 }
1149 }
1150 } else if allowed_matches == AllowedMatches::One && matches.len() == 0 {
1151 if let (Some(backend), false)
1153 = (selector.backend(), backend_matched)
1154 {
1155 Err(anyhow::anyhow!(
1156 "The specified backend ({}) wasn't loaded (try: {})",
1157 backend, backend_names.join(", ")))
1158 } else {
1159 log::debug!("{}: The {} selector {} does not match any of \
1160 the {}. Known {}:",
1161 func!(), obj, selector.args(), objs, objs);
1162 Self::list_matches(all);
1163
1164 Err(anyhow::anyhow!(
1165 "The specified selector ({}) doesn't match any of the {}",
1166 selector.args(), objs))
1167 }
1168 } else if allowed_matches == AllowedMatches::One && matches.len() > 1 {
1169 log::debug!("{}: The {} selector {} matches multiple {}:",
1171 func!(), obj, selector.args(), objs);
1172 Self::list_matches(matches);
1173
1174 Err(anyhow::anyhow!(
1175 "Multiple {} match {}, try being more specific.",
1176 objs, selector.args()))
1177 } else {
1178 Ok(matches)
1179 }
1180 }
1181
1182 fn list_matches(items: Vec<KeyOrToken>) {
1184 let is_key = items.iter().next()
1185 .map(|o| o.is_key())
1186 .unwrap_or(false);
1187
1188 let list_token = |t: &Token| -> String {
1189 format!("--backend {} --slot {} --token-label {:?} \
1190 --token-serial-number {}",
1191 t.backend().lib_short(), t.slot().id(), t.info().label(),
1192 t.info().serial_number())
1193 };
1194
1195 for obj in items.into_iter() {
1196 match obj {
1197 KeyOrToken::Key(key) => {
1198 assert!(is_key);
1199 let mut bits: Vec<Cow<str>> = Vec::new();
1200 bits.push(list_token(&key.token()).into());
1201 if let Some(key_unique_id) = key.key_unique_id() {
1202 bits.push(Cow::Borrowed("--key-unique-id"));
1203 bits.push(format!(
1204 "{:?}", String::from_utf8_lossy(key_unique_id)).into());
1205 }
1206 if let Some(key_label) = key.key_label() {
1207 bits.push(Cow::Borrowed("--key-label"));
1208 bits.push(format!(
1209 "{:?}", String::from_utf8_lossy(key_label)).into());
1210 }
1211 if let Some(key_id) = key.key_id() {
1212 bits.push(Cow::Borrowed("--key-id"));
1213 bits.push(format!(
1214 "{:?}", String::from_utf8_lossy(key_id)).into());
1215 }
1216 if let Some(key_url) = key.key_url() {
1217 bits.push(Cow::Borrowed("--key-url"));
1218 bits.push(format!(
1219 "{:?}", String::from_utf8_lossy(key_url)).into());
1220 }
1221 eprintln!(" - {}", bits.join(" "));
1222 }
1223 KeyOrToken::Token(token) => {
1224 assert!(! is_key);
1225 eprintln!(" - {}", list_token(&token));
1226 }
1227 }
1228 }
1229 }
1230
1231 pub fn tokens(&self) -> Result<impl Iterator<Item=Token>> {
1233 let matches = self.select_internal(
1234 &KeySelector::unconstrained(), false,
1235 AllowedMatches::Any, SelectorScope::PublicKeys,
1236 false)?;
1238
1239 Ok(matches
1240 .into_iter()
1241 .map(|obj| obj.into_token_unwrap()))
1242 }
1243
1244 pub fn select_one_token(&self, selector: &TokenSelector)
1249 -> Result<Token>
1250 {
1251 let key_selector
1252 = KeySelector::from_token_selector(selector.clone());
1253 let matches = self.select_internal(&key_selector, false,
1254 AllowedMatches::One,
1255 SelectorScope::All,
1256 false)?;
1257
1258 assert_eq!(matches.len(), 1);
1259
1260 let token = matches.into_iter().next().unwrap().into_token_unwrap();
1261
1262 Ok(token)
1263 }
1264
1265 pub fn keys(&self) -> Result<impl Iterator<Item=Key>> {
1267 let matches = self.select_internal(
1268 &KeySelector::unconstrained(), true,
1269 AllowedMatches::Any, SelectorScope::PublicKeys,
1270 true)?;
1272
1273 Ok(matches
1274 .into_iter()
1275 .map(|obj| obj.into_key_unwrap()))
1276 }
1277
1278 pub fn select_one_key(&self, selector: &KeySelector, scope: SelectorScope)
1283 -> Result<Key>
1284 {
1285 let matches = self.select_internal(
1286 &selector, true, AllowedMatches::One, scope,
1287 true)?;
1289
1290 assert_eq!(matches.len(), 1);
1291
1292 let key = matches.into_iter().next().unwrap().into_key_unwrap();
1293
1294 Ok(key)
1295 }
1296
1297 pub fn select_keys(&self, selector: &KeySelector, scope: SelectorScope)
1302 -> Result<Vec<Key>>
1303 {
1304 let matches = self.select_internal(
1305 &selector, true, AllowedMatches::Any, scope,
1306 true)?;
1308
1309 let keys = matches
1310 .into_iter()
1311 .map(|obj| obj.into_key_unwrap())
1312 .collect::<Vec<Key>>();
1313
1314 Ok(keys)
1315 }
1316
1317 pub fn check_no_keys_have_label(&self, label: &str)
1319 -> Result<()>
1320 {
1321 tracer!(TRACE, "config::check_no_keys_have_label");
1322 t!("Checking that the key label {} is unique", label);
1323
1324 let selector = KeySelector::from_key_label(label);
1325 self.select_internal(&selector, true,
1326 AllowedMatches::None,
1327 SelectorScope::All,
1328 false)?;
1330
1331 Ok(())
1332 }
1333
1334 pub fn check_no_keys_have_id(&self, id: &str)
1336 -> Result<()>
1337 {
1338 tracer!(TRACE, "config::check_no_keys_have_id");
1339 t!("Checking that the key ID {} is unique", id);
1340
1341 let selector = KeySelector::from_key_id(id);
1342 self.select_internal(&selector, true,
1343 AllowedMatches::None,
1344 SelectorScope::All,
1345 false)?;
1347
1348 Ok(())
1349 }
1350}