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