Skip to main content

sequoia_cryptoki/
objects.rs

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