Skip to main content

sequoia_cryptoki/
objects.rs

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::ObjectClass;
15use cryptoki::object::ObjectHandle;
16use cryptoki::session::Session;
17use cryptoki::session::UserType;
18use cryptoki::slot::Slot;
19use cryptoki::slot::TokenInfo;
20use cryptoki::types::AuthPin;
21
22use sequoia_openpgp as openpgp;
23use openpgp::Fingerprint;
24use openpgp::packet::key::PublicParts;
25use openpgp::packet::key::UnspecifiedRole;
26use openpgp::packet;
27
28use crate::Context;
29use crate::Result;
30use crate::KeySelector;
31use crate::TokenSelector;
32
33const TRACE: bool = false;
34
35struct Pkcs11 {
36    inner: Option<cryptoki::context::Pkcs11>,
37}
38
39impl std::fmt::Debug for Pkcs11 {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
41    {
42        if let Some(pkcs11) = self.inner.as_ref() {
43            write!(f, "{:?}", pkcs11)
44        } else {
45            write!(f, "<finalized PKCS11 context>")
46        }
47    }
48}
49
50impl Drop for Pkcs11 {
51    fn drop(&mut self) {
52        if let Some(pkcs11) = self.inner.take() {
53            if let Err(err) = pkcs11.finalize() {
54                eprintln!("Finalizing PKCS11 context: {}", err);
55            }
56        }
57    }
58}
59
60impl std::ops::Deref for Pkcs11 {
61    type Target = cryptoki::context::Pkcs11;
62
63    fn deref(&self) -> &Self::Target {
64        // `self.inner` is only `None` if `self` has been dropped.
65        self.inner.as_ref().expect("not finalized")
66    }
67}
68
69impl From<cryptoki::context::Pkcs11> for Pkcs11 {
70    fn from(pkcs11: cryptoki::context::Pkcs11) -> Self {
71        Self {
72            inner: Some(pkcs11),
73        }
74    }
75}
76
77/// A PKCS#11 backend.
78///
79/// A backend corresponds to a PKCS#11 library.
80///
81/// A [`Backend`] provides access to one or more slots, which may or
82/// may not contain a token.  Each token holds one or more [`Key`]s.
83#[derive(Clone, Debug)]
84pub struct Backend {
85    lib: PathBuf,
86    // `lib`, but encoded with String::from_utf8_lossy.
87    pub(crate) lib_str: String,
88    context: Arc<Pkcs11>,
89}
90
91impl Backend {
92    /// Returns the low-level context.
93    pub fn context(&self) -> &cryptoki::context::Pkcs11 {
94        &self.context
95    }
96
97    /// Returns the location of the library.
98    pub fn lib(&self) -> &Path {
99        &self.lib
100    }
101
102    /// Returns a short name for the library.
103    ///
104    /// The short name is the file name with all extensions and any
105    /// leading lib stripped.  Any invalid UTF-8 sequences are
106    /// replaced with `U+FFFD REPLACEMENT CHARACTER`.
107    ///
108    /// Consider the library
109    /// `/usr/lib/x86_64-linux-gnu/libykcs11.so.2`.  The short name is
110    /// `ykcs11`.
111    pub fn lib_short(&self) -> &str {
112        let lib = &self.lib_str[..];
113
114        if let Some(i) = lib.rfind('/') {
115            // Don't return an empty string.
116            if i < lib.len() - 1 {
117                let file_name = &lib[i + 1 ..];
118
119                // Strip any extensions.
120                if let Some(dot) = file_name.find('.') {
121                    let prefix = &file_name[..dot];
122                    // Strip a leading lib.
123                    if let Some(inner) = prefix.strip_prefix("lib") {
124                        return inner;
125                    } else {
126                        return prefix;
127                    }
128                }
129                return file_name;
130            }
131        }
132
133        &lib[..]
134    }
135
136    /// Returns whether `query` matches the backend.
137    ///
138    /// Consider the library
139    /// `/usr/lib/x86_64-linux-gnu/libykcs11.so.2`.  This matches on
140    /// the full path, on the filename (`libykcs11.so.2`), the
141    /// filename with each trailing component stripped
142    /// (`libykcs11.so`, and `libykcs11`), and the filename with any
143    /// initial `lib` prefix and all trailing components striped
144    /// (`ykcs11`).
145    pub fn is_lib(&self, query: &str) -> bool {
146        tracer!(false, "is_lib");
147        t!("Checking if {} matches {}", query, self.lib.display());
148
149        if query.as_bytes() == self.lib.as_os_str().as_encoded_bytes() {
150            // Exact match.
151            t!("Exact match");
152            return true;
153        } else if query.contains(&['/', '\\']) {
154            // `query` contains a path separator so only an exact match
155            // is possible.
156            t!("Not an exact match, and name contains a path separator.  Giving up.");
157            return false;
158        };
159
160        let path = PathBuf::from(&self.lib);
161        if let Some(file_name) = path.file_name() {
162            t!("Considering {}",
163               String::from_utf8_lossy(file_name.as_encoded_bytes()));
164            if file_name == query {
165                // Matches on the filename.
166                t!("Match");
167                return true;
168            }
169
170            let query = query.as_bytes();
171            let file_name = file_name.as_encoded_bytes();
172
173            let mut first = true;
174            for (i, c) in file_name.iter().enumerate() {
175                if *c == b'.' {
176                    let prefix = &file_name[..i];
177
178                    t!("Considering {}",
179                       String::from_utf8_lossy(prefix));
180
181                    if prefix == query {
182                        t!("Match");
183                        return true;
184                    }
185
186                    if first {
187                        if prefix.starts_with(b"lib") {
188                            let middle = &prefix[3..];
189
190                            t!("Considering {}",
191                               String::from_utf8_lossy(middle));
192                            if middle == query {
193                                t!("Match");
194                                return true;
195                            }
196                        }
197                    }
198                    first = false;
199                }
200            }
201        }
202
203        t!("Not a match");
204        false
205    }
206}
207
208/// Encapsulates a token.
209///
210/// A [`Backend`] provides access to one or more slots, which may or
211/// may not contain a token.  Each token holds one or more [`Key`]s.
212/// Before a token has been initialize its slot ID is the only way to
213/// identify it.  Afterwards, the token's unique ID (which not all
214/// backends support) or the token's label (which is not guaranteed to
215/// be unique, but is by convention) should be used.
216#[derive(Clone, Debug)]
217pub struct Token {
218    backend: Backend,
219    slot: Slot,
220    info: TokenInfo,
221}
222
223impl Token {
224    /// Returns the backend.
225    pub fn backend(&self) -> &Backend {
226        &self.backend
227    }
228
229    /// Returns the slot.
230    pub fn slot(&self) -> &Slot {
231        &self.slot
232    }
233
234    /// Returns information about the token.
235    ///
236    /// See [`cryptoki::TokenInfo`] for more details.
237    ///
238    ///   [`cryptoki::TokenInfo`]: https://docs.rs/cryptoki/latest/cryptoki/slot/struct.TokenInfo.html
239    pub fn info(&self) -> &TokenInfo {
240        &self.info
241    }
242
243    /// Opens a read-only session to the token.
244    ///
245    /// This is needed to sign or decrypt a message, for instance.
246    ///
247    /// A user is not logged into the session.  You should either use
248    /// [`Token::open_ro_user_session`], or follow up by calling the
249    /// low-level `Session`'s [`login`] method.
250    ///
251    ///   [`login`]: https://docs.rs/cryptoki/latest/cryptoki/session/struct.Session.html#method.login
252    pub fn open_ro_session(&self)
253        -> Result<cryptoki::session::Session>
254    {
255        let session = self.backend().context.clone()
256            .open_ro_session(self.slot().clone())?;
257        Ok(session)
258    }
259
260    /// Opens a read-only session to the token, and logs in as the
261    /// user.
262    ///
263    /// This is needed to sign or decrypt a message, for instance.
264    pub fn open_ro_user_session<P>(&self, pin: P)
265        -> Result<cryptoki::session::Session>
266    where
267        P: Into<AuthPin>
268    {
269        let session = self.open_ro_session()?;
270        session.login(UserType::User, Some(&pin.into()))?;
271        Ok(session)
272    }
273
274    /// Opens a read-write session to the token.
275    ///
276    /// This is needed to generate or import a key, for instance.
277    ///
278    /// A user is not logged into the session.  You should either use
279    /// [`Token::open_rw_user_session`], or follow up by calling the
280    /// low-level `Session`'s [`login`] method.
281    ///
282    ///   [`login`]: https://docs.rs/cryptoki/latest/cryptoki/session/struct.Session.html#method.login
283    pub fn open_rw_session(&self)
284        -> Result<cryptoki::session::Session>
285    {
286        let session = self.backend().context.clone()
287            .open_rw_session(self.slot().clone())?;
288        Ok(session)
289    }
290
291    /// Opens a read-write session to the token, and logs in as the
292    /// user.
293    ///
294    /// This is needed to generate or import a key, for instance.
295    pub fn open_rw_user_session<P>(&self, pin: P)
296        -> Result<cryptoki::session::Session>
297    where
298        P: Into<AuthPin>
299    {
300        let session = self.backend().context.clone()
301            .open_rw_session(self.slot().clone())?;
302        session.login(UserType::User, Some(&pin.into()))?;
303        Ok(session)
304    }
305}
306
307impl std::fmt::Display for Token {
308    fn fmt(&self, f: &mut std::fmt::Formatter<'_>)
309        -> std::result::Result<(), std::fmt::Error>
310    {
311        let mut label = self.info().label();
312        if label.is_empty() {
313            label = "<no label>";
314        }
315        let manufacturer_id = self.info().manufacturer_id();
316        let model = self.info().model();
317        let serial_number = self.info().serial_number();
318
319        let product = match (manufacturer_id.is_empty(), model.is_empty()) {
320            (true, true) => Cow::Borrowed("Unknown product"),
321            (true, false) => manufacturer_id.into(),
322            (false, true) => model.into(),
323            (false, false) => {
324                if model.contains(manufacturer_id) {
325                    model.into()
326                } else {
327                    format!("{} {}", manufacturer_id, model).into()
328                }
329            }
330        };
331
332        let mut id = if serial_number.is_empty() {
333            format!("{} ({})", label, product)
334        } else {
335            format!("{} ({}, serial number: {})", label, product, serial_number)
336        };
337
338        if id.chars().any(|c| c.is_control()) {
339            // Escape control characters.
340            id = format!("{:?}", id);
341        } else {
342            // Replace newlines with dashes.
343            id = id.replace("\n", "-");
344            id = id.replace("\r", "-");
345        }
346
347        write!(f, "{}", id)
348    }
349}
350
351/// Describes a key.
352///
353/// A [`Backend`] provides access to one or more slots, which may or
354/// may not contain a token.  Each token holds one or more [`Key`]s.
355///
356/// This data structure contains a reference to a PKCS#11 context, and
357/// everything needed to find a particular key.
358///
359/// We don't store a `Session` in this data structure for two reasons.
360/// First, an open session locks the token, which may interfere with
361/// other users of the token.  Second, `Session`s are not `Sync`,
362/// which means that `Key` would not be `Sync` without wrapping the
363/// `Session` in something like a `Mutex`.  Instead, we open a session
364/// on demand.
365///
366/// Because we don't have a session, we can't store an object handle,
367/// which is only meaningful for a particular session.  According to
368/// PKCS#11, v3.2, draft 13, Section 3.4:
369///
370/// > When an object is created or found on a token by an application,
371/// > Cryptoki assigns it an object handle for that application’s
372/// > sessions to use to access it. A particular object on a token
373/// > does not necessarily have a handle which is fixed for the
374/// > lifetime of the object; however, if a particular session can use
375/// > a particular handle to access a particular object, then that
376/// > session will continue to be able to use that handle to access
377/// > that object as long as the session continues to exist, the
378/// > object continues to exist, and the object continues to be
379/// > accessible to the session.
380///
381/// To workaround this, we cache what we can about a key so that we
382/// can *unambiguously* find it later.  In principle, the unique ID
383/// (`CKA_UNIQUE_ID`) attribute is enough.  From PKCS#11, v3.2, draft
384/// 13, Section 4.4.1:
385///
386/// > Any time a new object is created, a value for `CKA_UNIQUE_ID` MUST
387/// > be generated by the token and stored with the object. The
388/// > specific algorithm used to generate unique ID values for objects
389/// > is token-specific, but values generated MUST be unique across
390/// > all objects visible to any particular session, and SHOULD be
391/// > unique across all objects created by the token.
392///
393/// Unfortunately, this was only added in PKCS#11 v3.0, and we want to
394/// support older tokens.
395///
396/// So, in addition to opportunistically using the unique ID, we also
397/// use the following to distinguish keys, and hope for the best:
398///
399///   - `CKA_LABEL`: Set by the user.
400///
401///   - `CKA_ID`: Set at key generation time by the application.  By
402///   convention, this is the same for the public key, private key and
403///   certificate tuple.
404///
405///   - `CKA_URL`: Set at key generation time by the application.  By
406///   convention, this is used as a unique identifier.
407#[derive(Debug)]
408pub struct Key {
409    token: Token,
410
411    /// The other constituent of a composite key.
412    ///
413    /// Some OpenPGP algorithms combine two cryptographic algorithms
414    /// in one key, e.g. `PublicKeyAlgorithm::MLDSA65_Ed25519`.
415    composite_key: Option<Box<Key>>,
416
417    // Cached values that are normally static.
418    object_class: Option<ObjectClass>,
419    key_unique_id: Option<Vec<u8>>,
420    key_label: Option<Vec<u8>>,
421    key_id: Option<Vec<u8>>,
422    key_url: Option<Vec<u8>>,
423    pub(crate) openpgp_key: Mutex<Option<packet::Key<PublicParts, UnspecifiedRole>>>,
424
425    pub(crate) got_capabilities: AtomicBool,
426    pub(crate) signing_capable: AtomicBool,
427    pub(crate) decryption_capable: AtomicBool,
428}
429
430impl Clone for Key {
431    fn clone(&self) -> Self {
432        Self {
433            token: self.token.clone(),
434            composite_key: self.composite_key.clone(),
435            object_class: self.object_class.clone(),
436            key_unique_id: self.key_unique_id.clone(),
437            key_label: self.key_label.clone(),
438            key_id: self.key_id.clone(),
439            key_url: self.key_url.clone(),
440            openpgp_key: Mutex::new(
441                self.openpgp_key.lock().unwrap().as_ref().map(|k| k.clone())),
442
443            got_capabilities: false.into(),
444            signing_capable: false.into(),
445            decryption_capable: false.into(),
446        }
447    }
448}
449
450impl Key {
451    /// Returns the other constituent of a composite key.
452    ///
453    /// Some OpenPGP algorithms combine two cryptographic algorithms
454    /// in one key, e.g. [`PublicKeyAlgorithm::MLDSA65_Ed25519`].
455    pub(crate) fn composite_key(&self) -> Option<&Key> {
456        self.composite_key.as_deref()
457    }
458
459    /// Attaches a key to form a composite key.
460    pub(crate) fn combine_with(&mut self, key: Key) {
461        assert!(self.composite_key.is_none());
462        assert!(key.composite_key.is_none());
463        self.composite_key = Some(Box::new(key));
464    }
465
466    /// Returns the backend.
467    pub fn backend(&self) -> &Backend {
468        self.token.backend()
469    }
470
471    /// Returns the token.
472    pub fn token(&self) -> &Token {
473        &self.token
474    }
475
476    /// Returns the slot.
477    pub fn slot(&self) -> &Slot {
478        self.token.slot()
479    }
480
481    /// Returns information about the token.
482    ///
483    /// See [`cryptoki::TokenInfo`] for more details.
484    ///
485    ///   [`cryptoki::TokenInfo`]: https://docs.rs/cryptoki/latest/cryptoki/slot/struct.TokenInfo.html
486    pub fn info(&self) -> &TokenInfo {
487        self.token.info()
488    }
489
490    /// Returns the key's object class, if any.
491    ///
492    /// See [`cryptoki::ObjectClass`] for more details.
493    ///
494    ///   [`cryptoki::ObjectClass`]: https://docs.rs/cryptoki/latest/cryptoki/object/struct.ObjectClass.html
495    pub fn object_class(&self) -> Option<ObjectClass> {
496        self.object_class.clone()
497    }
498
499    /// Returns the key's unique ID, if any.
500    pub fn key_unique_id(&self) -> Option<&[u8]> {
501        self.key_unique_id.as_deref()
502    }
503
504    /// Returns the key's hex encoded unique ID, if any.
505    pub fn key_unique_id_hex(&self) -> Option<String> {
506        self.key_unique_id()
507            .map(|id| {
508                id.iter()
509                    .map(|x| format!("{:02x}", x))
510                    .collect::<Vec<String>>()
511                    .join("")
512            })
513    }
514
515    /// Returns the key's label, if any.
516    pub fn key_label(&self) -> Option<&[u8]> {
517        self.key_label.as_deref()
518    }
519
520    /// Returns the key's key ID, if any.
521    pub fn key_id(&self) -> Option<&[u8]> {
522        self.key_id.as_deref()
523    }
524
525    /// Returns the key's URL, if any.
526    pub fn key_url(&self) -> Option<&[u8]> {
527        self.key_url.as_deref()
528    }
529
530    /// Returns a new session and an object handle to the object
531    /// designated by the key descriptor.
532    pub fn open_ro_session(&self)
533        -> Result<(Session, ObjectHandle)>
534    {
535        let session
536            = self.backend().context().open_ro_session(self.slot().clone())?;
537
538        let mut attrs = Vec::with_capacity(5);
539        if let Some(object_class) = self.object_class {
540            attrs.push(Attribute::Class(object_class));
541        }
542        if let Some(unique_id) = self.key_unique_id() {
543            attrs.push(Attribute::UniqueId(unique_id.to_vec()));
544        }
545        if let Some(label) = self.key_label() {
546            attrs.push(Attribute::Label(label.to_vec()));
547        }
548        if let Some(id) = self.key_id() {
549            attrs.push(Attribute::Id(id.to_vec()));
550        }
551        if let Some(url) = self.key_url() {
552            attrs.push(Attribute::Url(url.to_vec()));
553        }
554
555        let mut objects = session.iter_objects(&attrs)
556            .with_context(|| {
557                format!("Listing {}'s objects",
558                        self.backend().lib().display())
559            })?;
560
561        let first = objects.next();
562        let second = objects.next();
563        let object = match (first, second) {
564            (Some(object), None) => object.context("Getting private key")?,
565            (Some(_), Some(_)) => {
566                return Err(anyhow::anyhow!(
567                    "Multiple keys correspond to the key descriptor, \
568                     cowardly refusing to continue."));
569            }
570            (None, _) => {
571                return Err(anyhow::anyhow!("Key object disappeared"));
572            }
573        };
574        drop(objects);
575
576        Ok((session, object))
577    }
578
579    /// Wraps an object handle designating a key.
580    ///
581    /// This function does not cache the session or the object.  But
582    /// you can use `Self::open_ro_session` to get a new session and a
583    /// new object handle.
584    pub fn from_object(token: Token, session: &Session, object: ObjectHandle)
585        -> Result<Self>
586    {
587        // Get the label and the id, etc.
588        let mut object_class = None;
589        let mut key_unique_id = None;
590        let mut key_label = None;
591        let mut key_id = None;
592        let mut key_url = None;
593
594        // We need to be careful: unknown attributes
595        // are skipped.
596        let attributes = session.get_attributes(
597            object,
598            &[
599                AttributeType::Class,
600                AttributeType::UniqueId,
601                AttributeType::Label,
602                AttributeType::Id,
603                AttributeType::Url,
604            ])?;
605        for attribute in attributes {
606            if let Attribute::Class(value) = attribute {
607                object_class = Some(value);
608            } else if let Attribute::UniqueId(value) = attribute {
609                key_unique_id = Some(value);
610            } else if let Attribute::Label(value) = attribute {
611                key_label = Some(value);
612            } else if let Attribute::Id(value) = attribute {
613                key_id = Some(value);
614            } else if let Attribute::Url(value) = attribute {
615                key_url = Some(value);
616            } else {
617                unreachable!("get_attributes only returns \
618                              requested attributes");
619            }
620        }
621
622        Ok(Self {
623            token,
624            composite_key: None,
625            object_class,
626            key_unique_id,
627            key_label,
628            key_id,
629            key_url,
630            openpgp_key: Mutex::new(None),
631
632            got_capabilities: false.into(),
633            signing_capable: false.into(),
634            decryption_capable: false.into(),
635        })
636    }
637
638    /// Returns the key's OpenPGP fingerprint.
639    ///
640    /// If the key is not an OpenPGP key, then this returns `None`.
641    pub fn fingerprint(&self) -> Option<Fingerprint> {
642        self.to_openpgp_key().ok().map(|key| key.fingerprint())
643    }
644}
645
646/// Used by `Context::select_internal` to return a list of keys or
647/// tokens.
648#[derive(Debug)]
649enum KeyOrToken {
650    Key(Key),
651    Token(Token),
652}
653
654impl KeyOrToken {
655    fn is_key(&self) -> bool {
656        self.key().is_some()
657    }
658
659    fn key(&self) -> Option<&Key> {
660        match self {
661            KeyOrToken::Key(key) => Some(key),
662            KeyOrToken::Token(_) => None,
663        }
664    }
665
666    fn key_unwrap(&self) -> &Key {
667        self.key().expect(
668            "Internal error: looked up a key, got a token")
669    }
670
671    fn key_mut(&mut self) -> Option<&mut Key> {
672        match self {
673            KeyOrToken::Key(key) => Some(key),
674            KeyOrToken::Token(_) => None,
675        }
676    }
677
678    fn key_mut_unwrap(&mut self) -> &mut Key {
679        self.key_mut().expect(
680            "Internal error: looked up a key, got a token")
681    }
682
683    fn into_key_unwrap(self) -> Key {
684        match self {
685            KeyOrToken::Key(key) => key,
686            KeyOrToken::Token(_) =>
687                panic!("Internal error: looked up a token, got a key"),
688        }
689    }
690
691    fn into_token_unwrap(self) -> Token {
692        match self {
693            KeyOrToken::Key(_) =>
694                panic!("Internal error: looked up a token, got a key"),
695            KeyOrToken::Token(token) => token,
696        }
697    }
698
699}
700
701/// The number of allowed matches.
702///
703/// Used by `Context::select_internal`.
704#[derive(Debug, Clone, Eq, PartialEq)]
705enum AllowedMatches {
706    None,
707    One,
708    Any,
709}
710
711/// The selector's scope.
712///
713/// Used by [`Context::select_one_key`], and [`Context::select_keys`]
714/// to specify whether public or private keys should be considered.
715#[derive(Debug, Clone, Eq, PartialEq)]
716pub enum SelectorScope {
717    All,
718    PublicKeys,
719    PrivateKeys,
720}
721
722// After initializing a backend, we have to finalize it before we can
723// initialize it again.  Cache the backends.
724static BACKENDS: Mutex<BTreeMap<PathBuf, Weak<Pkcs11>>>
725    = Mutex::new(BTreeMap::new());
726
727impl Context {
728    /// Returns a reference to the PKCS#11 contexts.
729    ///
730    /// The context has bound the specified libraries.  As this loads
731    /// the modules, this function may return an error if a module
732    /// can't be loaded.
733    pub fn backends(&self) -> Result<&[Backend]> {
734        tracer!(TRACE, "Context::backends");
735
736        if let Some(backends) = self.backends.get() {
737            return Ok(backends);
738        }
739
740        let modules = self.config.modules();
741        let mut backends = Vec::with_capacity(modules.len());
742        let mut load_err = None;
743        let mut init_err = None;
744        for lib in modules {
745            t!("Loading {}", lib.display());
746
747            // See if we already initialize the backend.
748            let mut backend = BACKENDS.lock().unwrap();
749            if let Some(context) = backend.get(lib) {
750                if let Some(context) = context.upgrade() {
751                    t!("Loaded {} (cached)", lib.display());
752
753                    backends.push(Backend {
754                        lib: lib.clone(),
755                        lib_str: lib.display().to_string(),
756                        context,
757                    });
758
759                    continue;
760                }
761            }
762
763            let context = match cryptoki::context::Pkcs11::new(lib) {
764                Ok(context) => context,
765                Err(err) => {
766                    log::debug!("{}: Error loading {}: {}",
767                                func!(), lib.display(), err);
768                    if load_err.is_none() {
769                        load_err = Some(err);
770                    }
771                    continue;
772                }
773            };
774
775            // Check if it is already initialized...
776            match context.initialize(
777                cryptoki::context::CInitializeArgs::new(
778                    cryptoki::context::CInitializeFlags::OS_LOCKING_OK))
779            {
780                Ok(context) => context,
781                Err(err) => {
782                    log::debug!("{}: Error initializing {}: {}",
783                                func!(), lib.display(), err);
784                    if init_err.is_none() {
785                        init_err = Some(err);
786                    }
787                    continue;
788                }
789            };
790            t!("Loaded {}", lib.display());
791
792            let context = Arc::new(context.into());
793
794            // Cache the context.
795            backend.insert(lib.clone(), Arc::downgrade(&context));
796
797            backends.push(Backend {
798                lib: lib.clone(),
799                lib_str: lib.display().to_string(),
800                context,
801            });
802        }
803
804        if let Some(err) = init_err {
805            return Err(err.into());
806        }
807        if let Some(err) = load_err {
808            return Err(err.into());
809        }
810
811        let _ = self.backends.set(backends);
812        let backends = self.backends.get().expect("just set");
813        Ok(backends)
814    }
815
816    /// Returns the matching keys (`key = true`) or tokens (`key =
817    /// false`).
818    ///
819    /// If `tokens` is `true`, then the selector's `key_unique_id`,
820    /// `key_label`, `key_id` and `key_url` fields are ignored, and
821    /// must be `None`.
822    ///
823    /// If `get_constituent` is `true`, then gets any constituent key.
824    fn select_internal(&self, selector: &KeySelector, key: bool,
825                       allowed_matches: AllowedMatches,
826                       scope: SelectorScope,
827                       get_constituent: bool)
828        -> Result<Vec<KeyOrToken>>
829    {
830        tracer!(TRACE, "Context::select_internal");
831
832        // All will only contain all of the objects if there are no
833        // matches.
834        let mut all: Vec<KeyOrToken> = Vec::new();
835        let mut matches: Vec<KeyOrToken> = Vec::new();
836
837        // If the user specified a backend, but it doesn't match any,
838        // print a pretty error message.
839        let mut backend_matched = false;
840        let mut backend_names = Vec::new();
841
842        for backend in self.backends()? {
843            backend_names.push(backend.lib_short());
844            if ! selector.backend_matches(&backend) {
845                continue;
846            } else {
847                backend_matched = true;
848            }
849
850            let slots = match backend.context().get_all_slots() {
851                Ok(slots) => slots,
852                Err(err) => {
853                    log::debug!("{}: Failed to enumerate slots for {}: {}",
854                                func!(), backend.lib().display(), err);
855                    continue;
856                }
857            };
858            t!("{} has {} slots", backend.lib().display(), slots.len());
859            'slot_loop: for slot in slots.into_iter() {
860                let info = match backend.context().get_token_info(slot.clone()) {
861                    Ok(info) => info,
862                    Err(err) => {
863                        t!("Failed to get token info for slot {}: {}",
864                           slot.id(), err);
865                        continue 'slot_loop;
866                    }
867                };
868
869                let matches_token =
870                    selector.slot_matches(slot.id())
871                    && selector.token_label_matches(info.label())
872                    && selector.token_serial_number_matches(
873                        info.serial_number());
874
875                if ! key {
876                    // Matching tokens.
877                    let token = Token {
878                        backend: backend.clone(),
879                        slot: slot,
880                        info: info.clone(),
881                    };
882
883                    if matches_token {
884                        matches.push(KeyOrToken::Token(token));
885                    } else {
886                        all.push(KeyOrToken::Token(token));
887                    }
888                } else {
889                    // Matching keys.
890                    let session = match backend.context().open_ro_session(slot) {
891                        Ok(session) => session,
892                        Err(err) => {
893                            log::debug!(
894                                "{}: Warning: {}'s slot {} is unusable: {}",
895                                func!(),
896                                backend.lib().display(), slot.id(),
897                                err);
898                            continue 'slot_loop;
899                        }
900                    };
901
902                    // Iterate over the objects on the token.
903                    let attrs = match scope {
904                        SelectorScope::All => &[][..],
905                        SelectorScope::PublicKeys => {
906                            &[ Attribute::Class(ObjectClass::PUBLIC_KEY) ]
907                        }
908                        SelectorScope::PrivateKeys => {
909                            &[ Attribute::Class(ObjectClass::PRIVATE_KEY) ]
910                        }
911                    };
912                    let objects = match session.iter_objects(attrs) {
913                        Ok(objects) => objects,
914                        Err(err) => {
915                            log::debug!(
916                                "{}: Error listing {}'s objects: {}",
917                                func!(),
918                                backend.lib().display(),
919                                err);
920                            continue 'slot_loop;
921                        }
922                    };
923
924                    'obj_loop: for (i, object) in objects.enumerate() {
925                        let object = match object {
926                            Ok(object) => object,
927                            Err(err) => {
928                                log::debug!(
929                                    "{}: Error reading object #{}: {}",
930                                    func!(), i + 1, err);
931                                continue 'obj_loop;
932                            }
933                        };
934
935                        // Get the label and the id.
936                        let token = Token {
937                            backend: backend.clone(),
938                            slot: slot,
939                            info: info.clone(),
940                        };
941                        let key = match Key::from_object(
942                            token, &session, object)
943                        {
944                            Ok(key) => key,
945                            Err(err) => {
946                                t!("Reading object #{}'s attributes: {}",
947                                   i + i, err);
948                                continue 'obj_loop;
949                            }
950                        };
951                        let matches_key_unique_id
952                            = selector.key_unique_id_matches(key.key_unique_id());
953
954                        let matches_key_label = if let Some(l) = selector.key_label() {
955                            // The user is selecting by key label.
956                            Some(l.as_bytes()) == key.key_label()
957                        } else {
958                            // key label not specified.  This is a match.
959                            true
960                        };
961
962                        let matches_key_id = selector.key_id_matches(key.key_id());
963                        let matches_key_url = selector.key_url_matches(key.key_url());
964
965                        if matches_token
966                            && matches_key_unique_id && matches_key_label
967                            && matches_key_id && matches_key_url
968                        {
969                            matches.push(KeyOrToken::Key(key));
970                        } else {
971                            all.push(KeyOrToken::Key(key));
972                        }
973                    }
974                }
975            }
976        }
977
978        // For each composite key, find its constituent key.
979        if key && get_constituent {
980            'next_match: for i in 0..matches.len() {
981                if i >= matches.len() {
982                    // This could happen because we remove entries.
983                    break;
984                }
985
986                // Figure out the name of the other key.
987                //
988                // Whether a key is part of a composite key and what
989                // part it is is encoded in the key ID.
990                let m = &matches[i];
991                let key = m.key_unwrap();
992                let key_id = if let Some(key_id) = key.key_id() {
993                    match String::from_utf8(key_id.to_vec()) {
994                        Ok(key_id) => key_id,
995                        Err(_err) => {
996                            // Not a key ID that we understand.
997                            continue;
998                        }
999                    }
1000                } else {
1001                    continue;
1002                };
1003
1004                // A bi-directional map between key ID prefixes for
1005                // composite keys.
1006                let map = &[
1007                    ("pgp:v6t:", "pgp:v6pq:"),
1008                    ("pgp:v4t:", "pgp:v4pq:"),
1009                ];
1010
1011                let mut other_key_id = None;
1012                for (one, other) in map.into_iter().map(|(a, b)| (*a, *b))
1013                    // Flip the map around.
1014                    .chain(map.into_iter().map(|(a, b)| (*b, *a)))
1015                {
1016                    if let Some(suffix) = key_id.strip_prefix(one) {
1017                        other_key_id = Some(format!("{}{}", other, suffix));
1018                        break;
1019                    }
1020                }
1021
1022                let other_key_id = if let Some(other_key_id) = other_key_id {
1023                    other_key_id
1024                } else {
1025                    // Not a (known) composite key.
1026                    continue;
1027                };
1028
1029                // Look up the constituent key.
1030
1031                // It may be that we already found the key that we're
1032                // looking for.
1033                if i + 1 < matches.len() {
1034                    for j in i + 1..matches.len() {
1035                        let other = matches[j].key_unwrap();
1036                        if other.key_id() == Some(other_key_id.as_bytes()) {
1037                            // Yup!  We're done.
1038                            let other = matches.remove(j).into_key_unwrap();
1039                            matches[i].key_mut_unwrap().combine_with(other);
1040                            continue 'next_match;
1041                        }
1042                    }
1043                }
1044
1045                // We need to look up the other key manually.  We
1046                // recurse and are careful to indicate that we
1047                // shouldn't look for this key.
1048                let other = self.select_internal(
1049                    &KeySelector::from_key_id(other_key_id),
1050                    true, // key
1051                    AllowedMatches::One,
1052                    SelectorScope::PublicKeys,
1053                    false, // Don't recurse.
1054                );
1055                match other {
1056                    Ok(results) => {
1057                        assert_eq!(results.len(), 1);
1058                        let other = results.into_iter().next().unwrap();
1059                        let other = other.into_key_unwrap();
1060                        matches[i].key_mut_unwrap().combine_with(other);
1061                    }
1062                    Err(err) => {
1063                        log::debug!(
1064                            "{}: Warning: {} is a composite key, \
1065                             but half the key is missing: {}",
1066                            func!(), key_id, err);
1067                    }
1068                }
1069            }
1070        }
1071
1072        let obj = if key { "key" } else { "token" };
1073        let objs = if key { "keys" } else { "tokens" };
1074
1075        if allowed_matches == AllowedMatches::None {
1076            // Don't want any matches.
1077            if matches.len() == 0 {
1078                Ok(vec![])
1079            } else {
1080                log::debug!("{}: The {} selector {} matches existing {}:",
1081                            func!(), obj, selector.args(), objs);
1082                Self::list_matches(matches);
1083
1084                if key {
1085                    Err(anyhow::anyhow!(
1086                        "The {} selector matches existing {}, choose a \
1087                         different label or use --ambiguous-key-label, \
1088                         or --random-key-label",
1089                        obj, objs))
1090                } else {
1091                    Err(anyhow::anyhow!(
1092                        "The {} selector matches existing {}", obj, objs))
1093                }
1094            }
1095        } else if allowed_matches == AllowedMatches::One && matches.len() == 0 {
1096            // No match, but want one.
1097            if let (Some(backend), false)
1098                = (selector.backend(), backend_matched)
1099            {
1100                Err(anyhow::anyhow!(
1101                    "The specified backend ({}) wasn't loaded (try: {})",
1102                    backend, backend_names.join(", ")))
1103            } else {
1104                log::debug!("{}: The {} selector {} does not match any of \
1105                             the {}.  Known {}:",
1106                            func!(), obj, selector.args(), objs, objs);
1107                Self::list_matches(all);
1108
1109                Err(anyhow::anyhow!(
1110                    "The specified selector ({}) doesn't match any of the {}",
1111                    selector.args(), objs))
1112            }
1113        } else if allowed_matches == AllowedMatches::One && matches.len() > 1 {
1114            // Want one match, but got multiple.
1115            log::debug!("{}: The {} selector {} matches multiple {}:",
1116                        func!(), obj, selector.args(), objs);
1117            Self::list_matches(matches);
1118
1119            Err(anyhow::anyhow!(
1120                "Multiple {} match {}, try being more specific.",
1121                objs, selector.args()))
1122        } else {
1123            Ok(matches)
1124        }
1125    }
1126
1127    /// Prints the items as a bulleted list on stderr.
1128    fn list_matches(items: Vec<KeyOrToken>) {
1129        let is_key = items.iter().next()
1130            .map(|o| o.is_key())
1131            .unwrap_or(false);
1132
1133        let list_token = |t: &Token| -> String {
1134            format!("--backend {} --slot {} --token-label {:?} \
1135                     --token-serial-number {}",
1136                    t.backend().lib_short(), t.slot().id(), t.info().label(),
1137                    t.info().serial_number())
1138        };
1139
1140        for obj in items.into_iter() {
1141            match obj {
1142                KeyOrToken::Key(key) => {
1143                    assert!(is_key);
1144                    let mut bits: Vec<Cow<str>> = Vec::new();
1145                    bits.push(list_token(&key.token()).into());
1146                    if let Some(key_unique_id) = key.key_unique_id() {
1147                        bits.push(Cow::Borrowed("--key-unique-id"));
1148                        bits.push(format!(
1149                            "{:?}", String::from_utf8_lossy(key_unique_id)).into());
1150                    }
1151                    if let Some(key_label) = key.key_label() {
1152                        bits.push(Cow::Borrowed("--key-label"));
1153                        bits.push(format!(
1154                            "{:?}", String::from_utf8_lossy(key_label)).into());
1155                    }
1156                    if let Some(key_id) = key.key_id() {
1157                        bits.push(Cow::Borrowed("--key-id"));
1158                        bits.push(format!(
1159                            "{:?}", String::from_utf8_lossy(key_id)).into());
1160                    }
1161                    if let Some(key_url) = key.key_url() {
1162                        bits.push(Cow::Borrowed("--key-url"));
1163                        bits.push(format!(
1164                            "{:?}", String::from_utf8_lossy(key_url)).into());
1165                    }
1166                    eprintln!("  - {}", bits.join(" "));
1167                }
1168                KeyOrToken::Token(token) => {
1169                    assert!(! is_key);
1170                    eprintln!("  - {}", list_token(&token));
1171                }
1172            }
1173        }
1174    }
1175
1176    /// Returns an iterator over all of the tokens.
1177    pub fn tokens(&self) -> Result<impl Iterator<Item=Token>> {
1178        let matches = self.select_internal(
1179            &KeySelector::unconstrained(), false,
1180            AllowedMatches::Any, SelectorScope::PublicKeys,
1181            // Resolve composite keys.
1182            false)?;
1183
1184        Ok(matches
1185           .into_iter()
1186           .map(|obj| obj.into_token_unwrap()))
1187    }
1188
1189    /// Selects the unique token designated by `selector`.
1190    ///
1191    /// Returns an error if no tokens or more than one token matches
1192    /// the selector.
1193    pub fn select_one_token(&self, selector: &TokenSelector)
1194        -> Result<Token>
1195    {
1196        let key_selector
1197            = KeySelector::from_token_selector(selector.clone());
1198        let matches = self.select_internal(&key_selector, false,
1199                                           AllowedMatches::One,
1200                                           SelectorScope::All,
1201                                           false)?;
1202
1203        assert_eq!(matches.len(), 1);
1204
1205        let token = matches.into_iter().next().unwrap().into_token_unwrap();
1206
1207        Ok(token)
1208    }
1209
1210    /// Returns an iterator over all of the keys.
1211    pub fn keys(&self) -> Result<impl Iterator<Item=Key>> {
1212        let matches = self.select_internal(
1213            &KeySelector::unconstrained(), true,
1214            AllowedMatches::Any, SelectorScope::PublicKeys,
1215            // Resolve composite keys.
1216            true)?;
1217
1218        Ok(matches
1219           .into_iter()
1220           .map(|obj| obj.into_key_unwrap()))
1221    }
1222
1223    /// Select the unique key designated by `selector`.
1224    ///
1225    /// Returns an error if no keys or more than one key matches the
1226    /// selector.
1227    pub fn select_one_key(&self, selector: &KeySelector, scope: SelectorScope)
1228        -> Result<Key>
1229    {
1230        let matches = self.select_internal(
1231            &selector, true, AllowedMatches::One, scope,
1232            // Resolve composite keys.
1233            true)?;
1234
1235        assert_eq!(matches.len(), 1);
1236
1237        let key = matches.into_iter().next().unwrap().into_key_unwrap();
1238
1239        Ok(key)
1240    }
1241
1242    /// Selects the keys designated by `selector`.
1243    ///
1244    /// Returns `Ok(vec![])` if there are no matches.  That is, no
1245    /// matches is not an error.
1246    pub fn select_keys(&self, selector: &KeySelector, scope: SelectorScope)
1247        -> Result<Vec<Key>>
1248    {
1249        let matches = self.select_internal(
1250            &selector, true, AllowedMatches::Any, scope,
1251            // Resolve composite keys.
1252            true)?;
1253
1254        let keys = matches
1255            .into_iter()
1256            .map(|obj| obj.into_key_unwrap())
1257            .collect::<Vec<Key>>();
1258
1259        Ok(keys)
1260    }
1261
1262    /// Returns an error if any keys have the specified label.
1263    pub fn check_no_keys_have_label(&self, label: &str)
1264        -> Result<()>
1265    {
1266        tracer!(TRACE, "config::check_no_keys_have_label");
1267        t!("Checking that the key label {} is unique", label);
1268
1269        let selector = KeySelector::from_key_label(label);
1270        self.select_internal(&selector, true,
1271                             AllowedMatches::None,
1272                             SelectorScope::All,
1273                             // Don't resolve composite keys.
1274                             false)?;
1275
1276        Ok(())
1277    }
1278
1279    /// Returns an error if any keys have the specified key ID.
1280    pub fn check_no_keys_have_id(&self, id: &str)
1281        -> Result<()>
1282    {
1283        tracer!(TRACE, "config::check_no_keys_have_id");
1284        t!("Checking that the key ID {} is unique", id);
1285
1286        let selector = KeySelector::from_key_id(id);
1287        self.select_internal(&selector, true,
1288                             AllowedMatches::None,
1289                             SelectorScope::All,
1290                             // Don't resolve composite keys.
1291                             false)?;
1292
1293        Ok(())
1294    }
1295}