Skip to main content

sequoia_keystore/
lib.rs

1//! Sequoia's key store.
2//!
3//! Sequoia's key store is a service, which manages and multiplexes
4//! access to secret key material.  Conceptually, keys live on
5//! devices, and devices are managed by backends.  A device may be as
6//! simple as an on-disk file (a soft key), it may be a smartcard, or
7//! it could be another key store server that is accessed over the
8//! network.  The key store manages all of these devices, and provides
9//! a common, higher-level interface.
10//!
11//! The key store is a server.  It normally lives in a separate
12//! process, but it may be co-located with the application.  Using a
13//! separate process improves security, because secret key material
14//! isn't exposed to the application, which can help prevent
15//! [Heartbleed-style bugs].  It also means that the state can be
16//! shared, which improves usability.  For instance, the server can
17//! cache passwords.  Sometimes, a separate process is not desirable,
18//! or awkward, e.g., when using the key store from an initrd.  In
19//! these cases, the co-located key store is better.
20//!
21//!   [Heartbleed-style bugs]: https://heartbleed.com/
22use std::any::Any;
23use std::sync::Arc;
24
25use capnp::any_pointer;
26use capnp::capability;
27use capnp::capability_list;
28use capnp::message;
29use capnp::traits::HasTypeId;
30
31use sequoia_openpgp as openpgp;
32use openpgp::Cert;
33use openpgp::Fingerprint;
34use openpgp::KeyID;
35use openpgp::KeyHandle;
36use openpgp::crypto::mpi;
37use openpgp::crypto::SessionKey;
38use openpgp::crypto::Password;
39use openpgp::packet;
40use openpgp::packet::PKESK;
41use openpgp::packet::key;
42use openpgp::parse::Parse;
43use openpgp::types::HashAlgorithm;
44use openpgp::types::PublicKeyAlgorithm;
45use openpgp::types::SymmetricAlgorithm;
46
47pub use sequoia_ipc;
48use sequoia_ipc as ipc;
49pub use ipc::Context;
50
51/// Re-export, since this is part of our API.
52pub use sequoia_directories;
53
54mod import_status;
55pub use import_status::ImportStatus;
56mod password_source;
57pub use password_source::PasswordSource;
58mod protection;
59pub use protection::Protection;
60
61#[allow(dead_code)] mod keystore_protocol_capnp;
62use crate::keystore_protocol_capnp::keystore;
63
64/// Macros managing requests and responses.
65#[macro_use] mod macros;
66mod error;
67pub use error::Error;
68mod server;
69mod capnp_relay;
70use capnp_relay::CapnProtoRelay;
71use capnp_relay::Cap;
72use capnp_relay::CapTable;
73
74#[cfg(test)]
75mod testdata;
76
77
78/// Result type.
79pub type Result<T, E=anyhow::Error> = ::std::result::Result<T, E>;
80
81
82#[doc(hidden)]
83pub fn descriptor(c: &Context) -> ipc::Descriptor {
84    ipc::Descriptor::new(
85        c,
86        c.home().join("keystore.cookie"),
87        c.lib().join("sequoia-keystore"),
88        server::Keystore::new_descriptor,
89    )
90}
91
92/// A handle to the key store.
93pub struct Keystore {
94    relay: Arc<CapnProtoRelay>,
95    cap: Cap,
96}
97
98impl Keystore {
99    /// Connects to the keystore.
100    ///
101    /// To set the context's home directory, you should usually
102    /// instantiate a `sequoia_dirs::Home` object, and use the value
103    /// returned by
104    /// `home.data_dir(sequoia_dirs::Component::Keystore)`.
105    pub fn connect(c: &Context) -> Result<Self> {
106        let descriptor = descriptor(&c);
107
108        let relay = CapnProtoRelay::new(descriptor)?;
109        let root = relay.root();
110        Ok(Self {
111            relay: relay,
112            cap: root,
113        })
114    }
115
116    crpc!(
117        /// Lists all backends.
118        fn [keystore] backends/0(&mut self)
119            -> Result<Vec<Cap>>
120            -> Result<Vec<Backend>>
121        // Marshal.
122        |_root: keystore::backends_params::Builder| -> Result<()> {
123            Ok(())
124        };
125        // Extract.
126        |relay, captable, response: keystore::backends_results::Reader| {
127            use keystore::result::Which;
128            match response.get_result()?.which()? {
129                // The RPC's result:
130                Which::Ok(Ok(r)) => {
131                    let r: capability_list::Reader<keystore::backend::Client> = r;
132                    let backends = r.iter()
133                        .map(|backend| {
134                            let cap: keystore::backend::Client = backend?;
135                            Ok(captable.insert(cap.client))
136                        }).collect::<Result<Vec<Cap>>>()?;
137
138                    Ok(backends)
139                },
140                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
141
142                // Protocol violations:
143                // Protocol error:
144                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
145                // Error reading the result from the response:
146                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
147            }
148        };
149        |caps: Vec<Cap>| {
150            let backends: Vec<Backend> = caps
151                .into_iter()
152                .map(|cap| {
153                    Backend {
154                        relay: Arc::clone(&self.relay),
155                        cap: cap,
156                    }
157                })
158                .collect();
159            Ok(backends)
160        });
161
162    /// Finds the specified keys.
163    ///
164    /// As a key may reside on multiple devices, this may return
165    /// multiple handles for a given key.
166    ///
167    /// The second return value is the list of keys that were not
168    /// found on the keystore.
169    #[async_generic::async_generic]
170    pub fn find_keys(&mut self, ids: &[KeyHandle])
171        -> Result<(Vec<Key>, Vec<KeyHandle>)>
172    {
173        let mut found: Vec<Key> = Vec::new();
174
175        let backends = if _sync {
176            self.backends()
177        } else {
178            self.backends_async().await
179        };
180
181        for mut b in backends.unwrap_or_else(|_| Vec::new()).into_iter() {
182            let devices = if _sync {
183                b.devices()
184            } else {
185                b.devices_async().await
186            };
187
188            for mut d in devices.unwrap_or_else(|_| Vec::new()).into_iter() {
189                let keys = if _sync {
190                    d.keys()
191                } else {
192                    d.keys_async().await
193                };
194
195                for mut k in keys.unwrap_or_else(|_| Vec::new()).into_iter() {
196                    let id = if _sync {
197                        k.id()
198                    } else {
199                        k.id_async().await
200                    };
201
202                    if let Ok(fpr) = id.and_then(|f| f.parse::<Fingerprint>()) {
203                        if ids.iter().any(|id| id.aliases(KeyHandle::from(&fpr))) {
204                            found.push(k);
205                        }
206                    }
207                }
208            }
209        }
210
211        let have: Vec<KeyHandle> = found.iter().map(|k| {
212            KeyHandle::from(k.fingerprint())
213        }).collect();
214
215        let missing = ids
216            .iter()
217            .filter(|id| ! have.iter().any(|fpr| id.aliases(fpr)))
218            .cloned()
219            .collect();
220
221        Ok((found, missing))
222    }
223
224    /// Finds the specified key.
225    ///
226    /// As a key may reside on multiple devices, this may return
227    /// multiple keys for a given id.
228    #[async_generic::async_generic]
229    pub fn find_key(&mut self, id: KeyHandle) -> Result<Vec<Key>> {
230        let result = if _sync {
231            self.find_keys(&[id])
232        } else {
233            self.find_keys_async(&[id]).await
234        };
235
236        result.map(|r| r.0)
237    }
238
239    crpc!(
240        /// Decrypts a PKESK.
241        ///
242        /// The keystore tries to decrypt the PKESKs in an arbitrary
243        /// order.  When it succeeds in decrypting a PKESK, it stops
244        /// and returns the decrypted session key.  By not enforcing
245        /// an order, the keystore is able to first try keys that are
246        /// immediately available, and only try keys that need to be
247        /// unlocked or connected to if that fails.
248        ///
249        /// On success, this function returns the index of the PKESK
250        /// that was decrypted, the fingerprint of the key that
251        /// decrypted the PKESK, and the plaintext (the symmetric
252        /// algorithm and the session key).
253        fn [keystore]decrypt/1(&mut self, pkesks: &[PKESK])
254            -> Result<(usize, Fingerprint, Option<SymmetricAlgorithm>, SessionKey)>
255        // Marshal.
256        |root: keystore::decrypt_params::Builder| -> Result<()> {
257            // Convert the arguments into the form expected by the RPC.
258            let mut pkesks_param = root.init_pkesks(pkesks.len() as u32);
259
260            pkesks
261                .iter()
262                .enumerate()
263                .for_each(|(i, pkesk)| {
264                    use openpgp::serialize::MarshalInto;
265                    let pkesk = pkesk.to_vec()
266                        .expect("serializing to a vec is infallible");
267                    pkesks_param.set(i as u32, &pkesk[..]);
268                });
269
270            Ok(())
271        };
272        // Extract.
273        |relay, captable, response: keystore::decrypt_results::Reader| {
274            use keystore::result::Which;
275            match response.get_result()?.which()? {
276                // The RPC's result:
277                Which::Ok(Ok(r)) => {
278                    let i = r.get_index() as usize;
279                    let fp_version = r.get_fingerprint_version();
280                    let fpr = Fingerprint::from_bytes(
281                        fp_version, r.get_fingerprint()?)?;
282                    let algo = match r.get_algo() as u8 {
283                        0 => None,
284                        n => Some(n.into()),
285                    };
286                    let session_key = SessionKey::from(r.get_session_key()?);
287
288                    let r: (usize, Fingerprint, Option<SymmetricAlgorithm>, SessionKey)
289                        = (i, fpr, algo, session_key);
290                    Ok(r)
291                },
292                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
293
294                // Protocol violations:
295                // Protocol error:
296                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
297                // Error reading the result from the response:
298                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
299            }
300        });
301}
302
303/// A handle to a backend.
304///
305/// The key store may have multiple backends.  These include a backend
306/// for soft keys (keys stored on disk), and a `gpg-agent` backend.
307///
308/// Use [`Keystore::backends`] to get a list of the backends that are
309/// enabled.
310pub struct Backend {
311    relay: Arc<CapnProtoRelay>,
312    cap: Cap,
313}
314
315impl Backend {
316    crpc!(
317        /// Returns the backend's ID.
318        fn [keystore::backend]id/0(&mut self) -> Result<String>
319        // Marshal.
320        |_root: keystore::backend::id_params::Builder| -> Result<()> {
321            Ok(())
322        };
323        // Extract.
324        |relay, captable, response: keystore::backend::id_results::Reader| {
325            use keystore::result::Which;
326            match response.get_result()?.which()? {
327                // The RPC's result:
328                Which::Ok(Ok(r)) => {
329                    Ok(r.to_string()?)
330                },
331                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
332
333                // Protocol violations:
334                // Protocol error:
335                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
336                // Error reading the result from the response:
337                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
338            }
339        });
340
341    crpc!(
342        /// Lists all devices.
343        ///
344        /// Lists the devices managed by a backend.
345        fn [keystore::backend] devices/1(&mut self)
346            -> Result<Vec<Cap>>
347            -> Result<Vec<Device>>
348        // Marshal.
349        |_root: keystore::backend::devices_params::Builder| -> Result<()> {
350            Ok(())
351        };
352        // Extract.
353        |relay, captable, response: keystore::backend::devices_results::Reader| {
354            use keystore::result::Which;
355            match response.get_result()?.which()? {
356                // The RPC's result:
357                Which::Ok(Ok(r)) => {
358                    let r: capability_list::Reader<keystore::device::Client> = r;
359                    let devices = r.iter()
360                        .map(|device| {
361                            let cap: keystore::device::Client = device?;
362                            Ok(captable.insert(cap.client))
363                        }).collect::<Result<Vec<Cap>>>()?;
364
365                    Ok(devices)
366                },
367                Which::Err(Ok(e)) => Err(Error::from_capnp(
368                    Arc::clone(&relay), captable, e)),
369
370                // Protocol violations:
371                // Protocol error:
372                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
373                // Error reading the result from the response:
374                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
375            }
376        };
377        |caps: Vec<Cap>| {
378            let devices: Vec<Device> = caps
379                .into_iter()
380                .map(|cap| {
381                    Device {
382                        relay: Arc::clone(&self.relay),
383                        cap: cap,
384                    }
385                })
386                .collect();
387            Ok(devices)
388        });
389
390    crpc!(
391        /// Imports secret key material.
392        ///
393        /// cert is a TSK.  Any keys without secret key material are
394        /// silent ignored.
395        ///
396        /// If a key already exists, it is overwritten.
397        ///
398        /// An [`ImportStatus`] is returned for each secret key.  If the
399        /// TSK doesn't include any secret keys, then an empty list is
400        /// returned.
401        ///
402        /// Some backends require additional information to import a
403        /// key.  These backends should
404        /// [`Error::ExternalImportRequired`], and indicate how a user
405        /// might import a key to this backend.
406        fn [keystore::backend] import/2(&mut self, cert: &Cert)
407            -> Result<Vec<(ImportStatus,
408                           Cap,
409                           packet::Key::<key::PublicParts,
410                                         key::UnspecifiedRole>)>>
411            -> Result<Vec<(ImportStatus, Key)>>
412        // Marshal.
413        |root: keystore::backend::import_params::Builder| -> Result<()> {
414            use openpgp::serialize::MarshalInto;
415
416            let bytes = cert.as_tsk().to_vec()?;
417            let cert_param = root.init_cert(bytes.len() as u32);
418            cert_param.copy_from_slice(&bytes);
419
420            Ok(())
421        };
422        // Extract.
423        |relay, captable, response: keystore::backend::import_results::Reader| {
424            use keystore::result::Which;
425            match response.get_result()?.which()? {
426                // The RPC's result:
427                Which::Ok(Ok(r)) => {
428                    let r: capnp::struct_list::Reader<keystore::import_result::Owned> = r;
429                    let r = r.iter()
430                        .map(|x| {
431                            use openpgp::parse::Parse;
432
433                            let status =
434                                ImportStatus::try_from(x.get_status()?)?;
435
436                            let key = x.get_key()?;
437
438                            let cap = key.get_handle()?;
439                            let pk = key.get_public_key()?;
440                            let pk = packet::Key::<key::UnspecifiedParts,
441                                                   key::UnspecifiedRole>
442                                ::from_bytes(pk)?;
443                            let pk = pk.parts_into_public();
444                            Ok((status, captable.insert(cap.client), pk))
445                        }).collect::<Result<Vec<(ImportStatus, Cap, packet::Key<_, _>)>>>();
446
447                    Ok(r?)
448                },
449                Which::Err(Ok(e)) => Err(Error::from_capnp(
450                    Arc::clone(&relay), captable, e)),
451
452                // Protocol violations:
453                // Protocol error:
454                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
455                // Error reading the result from the response:
456                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
457            }
458        };
459        |caps: Vec<(ImportStatus, Cap, packet::Key<_, _>)>| {
460            let keys: Vec<(ImportStatus, Key)> = caps
461                .into_iter()
462                .map(|(import_status, cap, key)| {
463                    (
464                        import_status,
465                        Key {
466                            relay: Arc::clone(&self.relay),
467                            cap: cap,
468                            key: key,
469                        }
470                    )
471                })
472                .collect();
473            Ok(keys)
474        });
475
476//    crpc!(fn [keystore::backend]scan/2(&mut self) -> Result<()>
477//          });
478
479//    crpc!(fn register(&mut self, description: &str) -> Result<Device>
480//          |slf: &mut Self, device| {
481//              Ok(Device {
482//                  relay: Arc::clone(&slf.relay),
483//                  cap: Arc::new(Mutex::new(device)),
484//              })
485//          });
486}
487
488/// A handle to a Device.
489///
490/// A device contains zero or more keys.
491///
492/// Some backends manage multiple physical devices.  For instance, the
493/// smartcard backend exposes each smartcard as a separate device.
494/// Other backends use the device abstraction to logically group
495/// related keys together.  For instance, the soft keys backend
496/// exposes each certificate as a separate device.
497pub struct Device {
498    relay: Arc<CapnProtoRelay>,
499    cap: Cap,
500}
501
502impl Device {
503    crpc!(
504        /// Returns the device's ID.
505        fn [keystore::device]id/0(&mut self) -> Result<String>
506        // Marshal.
507        |_root: keystore::device::id_params::Builder| -> Result<()> {
508            Ok(())
509        };
510        // Extract.
511        |relay, captable, response: keystore::device::id_results::Reader| {
512            use keystore::result::Which;
513            match response.get_result()?.which()? {
514                // The RPC's result:
515                Which::Ok(Ok(r)) => {
516                    Ok(r.to_string()?)
517                },
518                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
519
520                // Protocol violations:
521                // Protocol error:
522                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
523                // Error reading the result from the response:
524                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
525            }
526        });
527
528    crpc!(
529        /// List keys on a device.
530        ///
531        /// Lists the keys on the device.
532        ///
533        /// Some of the returned keys may be known, but not currently
534        /// available.  For instance, if a smartcard is not plugged
535        /// in, or an ssh connection is not established.
536        fn [keystore::device] keys/1(&mut self)
537            -> Result<Vec<(Cap,
538                           packet::Key::<key::PublicParts,
539                                         key::UnspecifiedRole>)>>
540            -> Result<Vec<Key>>
541        // Marshal.
542        |_root: keystore::device::keys_params::Builder| -> Result<()> {
543            Ok(())
544        };
545        // Extract.
546        |relay, captable, response: keystore::device::keys_results::Reader| {
547            use keystore::result::Which;
548            match response.get_result()?.which()? {
549                // The RPC's result:
550                Which::Ok(Ok(r)) => {
551                    let r: capnp::struct_list::Reader<keystore::key_descriptor::Owned> = r;
552                    let r = r.iter()
553                        .map(|x| {
554                            use openpgp::parse::Parse;
555
556                            let cap = x.get_handle()?;
557                            let pk = x.get_public_key()?;
558                            let pk = packet::Key::<key::UnspecifiedParts,
559                                                   key::UnspecifiedRole>
560                                ::from_bytes(pk)?;
561                            let pk = pk.parts_into_public();
562                            Ok((captable.insert(cap.client), pk))
563                        }).collect::<Result<Vec<(Cap, packet::Key<_, _>)>>>();
564
565                    Ok(r?)
566                },
567                Which::Err(Ok(e)) => Err(Error::from_capnp(
568                    Arc::clone(&relay), captable, e)),
569
570                // Protocol violations:
571                // Protocol error:
572                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
573                // Error reading the result from the response:
574                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
575            }
576        };
577        |caps: Vec<(Cap, packet::Key<_, _>)>| {
578            let keys: Vec<Key> = caps
579                .into_iter()
580                .map(|(cap, key)| {
581                    Key {
582                        relay: Arc::clone(&self.relay),
583                        cap: cap,
584                        key: key,
585                    }
586                })
587                .collect();
588            Ok(keys)
589        });
590
591    // /// Forget a device.
592    // ///
593    // /// Unregister the device from the backend.  This should not
594    // /// destroy any secret key material stored on the device.
595    // pub fn unregister(&mut self) -> Result<()> {
596    //     todo!()
597    // }
598
599    // /// Unlock a device.
600    // ///
601    // /// Connects to and unlocks a device.
602    // ///
603    // /// Some devices need to be initialized.  For instance, to access a
604    // /// remote key, it may be necessary to create an ssh tunnel.  Some
605    // /// devices need to be unlocked before the keys can be enumerated.
606    // /// For instance, if soft keys are stored in a database and the
607    // /// database is encrypted, it may be necessary to supply a password to
608    // /// decrypt the database.  In this case, the parameter might be
609    // /// "password='1234'".
610    // pub fn unlock(&mut self, _password: &[u8]) -> Result<()> {
611    //     todo!();
612    // }
613
614    // /// Lock a device.
615    // ///
616    // /// Locks the device if it has been previously unlock.  If the device
617    // /// is locked or can't be locked, this is a noop.  If the device needs
618    // /// to be deinitialized, it MAY be deinitialized lazily if doing so
619    // /// cannot result in a user-visible error.  For instance, if the
620    // /// device uses an ssh tunnel, the ssh tunnel be closed later.  A
621    // /// smartcard, however, should be released immediately.
622    // pub fn lock(&mut self) -> Result<()> {
623    //     todo!()
624    // }
625}
626
627/// A handle to a key.
628///
629/// A key encapsulates secret key material, and exposes some secret
630/// key operations like decrypting a message, signing a message,
631/// changing the key's password, and deleting the secret key material.
632/// Not all keys implement all operations.  In particular, a key will
633/// typically either implement [`Key::decrypt_ciphertext`] or
634/// [`Key::sign_message`].
635#[derive(Clone)]
636pub struct Key {
637    relay: Arc<CapnProtoRelay>,
638    cap: Cap,
639    key: packet::Key<key::PublicParts, key::UnspecifiedRole>,
640}
641
642impl Key {
643    /// Returns the key's key handle.
644    pub fn key_handle(&self) -> KeyHandle {
645        self.key.fingerprint().into()
646    }
647
648    /// Returns the key's fingerprint.
649    pub fn fingerprint(&self) -> Fingerprint {
650        self.key.fingerprint()
651    }
652
653    /// Returns the key's Key ID.
654    pub fn keyid(&self) -> KeyID {
655        self.key.keyid()
656    }
657
658    /// Returns the key's public key.
659    pub fn public_key(&self)
660        -> &packet::Key<key::PublicParts, key::UnspecifiedRole>
661    {
662        &self.key
663    }
664
665    crpc!(
666        /// Returns a unique key identifier.
667        ///
668        /// It should be a well-formed UTF-8 string, which should give a
669        /// curious user a pretty good idea of what key this is.
670        fn [keystore::key]id/0(&mut self) -> Result<String>
671        // Marshal.
672        |_root: keystore::key::id_params::Builder| -> Result<()> {
673            Ok(())
674        };
675        // Extract.
676        |relay, captable, response: keystore::key::id_results::Reader| {
677            use keystore::result::Which;
678            match response.get_result()?.which()? {
679                // The RPC's result:
680                Which::Ok(Ok(r)) => {
681                    Ok(r.to_string()?)
682                },
683                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
684
685                // Protocol violations:
686                // Protocol error:
687                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
688                // Error reading the result from the response:
689                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
690            }
691        });
692
693    crpc!(
694        /// Unlocks a key.
695        ///
696        /// A key is typically unlocked by providing a password or pin.  Not
697        /// all keys are locked.  If the key is not available, this should
698        /// attempt to connect to the device.  If the device is not available
699        /// or cannot be initialized, then this should fail.
700        fn [keystore::key]unlock/3(&mut self, password: Password) -> Result<()>
701            // Marshal.
702            |mut root: keystore::key::unlock_params::Builder| -> Result<()> {
703                password.map(|password| {
704                    root.set_password(&password[..]);
705                });
706                Ok(())
707            };
708            // Extract.
709            |relay, captable, response: keystore::key::unlock_results::Reader| {
710                use keystore::void_result::Which;
711                match response.get_result()?.which()? {
712                    // The RPC's result:
713                    Which::Ok(()) => Ok(()),
714                    Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
715
716                    // Protocol violations:
717                    // Protocol error:
718                    Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
719                }
720            });
721
722    // /// Lock a key (optional)
723    // ///
724    // /// Relocks the key.  This usually causes the backend to forget the
725    // /// key's password.  If the key can't be locked or is already locked,
726    // /// this is a noop.
727    // pub fn lock(&mut self) -> Result<()> {
728    //     todo!()
729    // }
730
731    crpc!(
732        /// Decrypts a ciphertext.
733        ///
734        /// This function corresponds to [`Decryptor::decrypt`].
735        ///
736        /// When decrypting a message you normally don't want to manually
737        /// try to decrypt each PKESK using this function, but use
738        /// [`Keystore::decrypt`], which first tries to use keys that
739        /// don't require user interaction.
740        ///
741        /// [`Decryptor::decrypt`]: https://docs.sequoia-pgp.org/sequoia_openpgp/crypto/trait.Decryptor.html#tymethod.decrypt
742        ///
743        /// If you want to decrypt a `PKESK`, then you should pass the
744        /// `Key` to `PKESK::decrypt`.
745        fn [keystore::key]decrypt_ciphertext/1(&mut self,
746                                               ciphertext: &Ciphertext,
747                                               plaintext_len: Option<usize>)
748            -> Result<SessionKey>
749        // Marshal.
750        |mut root: keystore::key::decrypt_ciphertext_params::Builder| -> Result<()> {
751            // Convert the arguments into the form expected by the RPC.
752            let algo = ciphertext.pk_algo().map(u8::from).unwrap_or(0);
753            let ciphertext = {
754                use sequoia_openpgp::serialize::MarshalInto;
755                ciphertext.to_vec().expect("serializing to a vec is infallible")
756            };
757
758            root.set_algo(algo);
759            root.set_ciphertext(&ciphertext);
760            root.set_plaintext_len(plaintext_len.unwrap_or(0) as u32);
761
762            Ok(())
763        };
764        // Extract.
765        |relay, captable, response: keystore::key::decrypt_ciphertext_results::Reader| {
766            use keystore::result::Which;
767            match response.get_result()?.which()? {
768                // The RPC's result:
769                Which::Ok(Ok(r)) => {
770                    let r: capnp::data::Reader = r;
771                    Ok(SessionKey::from(r))
772                },
773                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
774
775                // Protocol violations:
776                // Protocol error:
777                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
778                // Error reading the result from the response:
779                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
780            }
781        });
782
783    crpc!(
784        /// Signs a message.
785        ///
786        /// `digest` is the message to sign.
787        fn [keystore::key]sign_message/2(&mut self, hash_algo: HashAlgorithm,
788                                         digest: &[u8])
789            -> Result<mpi::Signature>
790        // Marshal.
791        |mut root: keystore::key::sign_message_params::Builder| -> Result<()> {
792            // Convert the arguments into the form expected by the RPC.
793            root.set_hash_algo(u8::from(hash_algo));
794            root.set_digest(digest);
795
796            Ok(())
797        };
798        // Extract.
799        |relay, captable, response: keystore::key::sign_message_results::Reader| {
800            use keystore::result::Which;
801            match response.get_result()?.which()? {
802                // The RPC's result:
803                Which::Ok(Ok(r)) => {
804                    let pk_algo = PublicKeyAlgorithm::from(r.get_pk_algo());
805                    let mpis = r.get_mpis()?;
806
807                    let sig = mpi::Signature::parse(pk_algo, mpis)?;
808                    Ok(sig)
809                },
810                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
811
812                // Protocol violations:
813                // Protocol error:
814                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
815                // Error reading the result from the response:
816                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
817            }
818        });
819
820    crpc!(
821        /// Whether the key is available.
822        ///
823        /// If false, this usually means the device needs to be
824        /// connected, e.g., a smartcard needs to be plugged in.
825        fn [keystore::key]available/4(&mut self) -> Result<bool>
826        // Marshal.
827        |_root: keystore::key::available_params::Builder| -> Result<()> {
828            Ok(())
829        };
830        // Extract.
831        |relay, captable, response: keystore::key::available_results::Reader| {
832            use keystore::bool_result::Which;
833            match response.get_result()?.which()? {
834                // The RPC's result:
835                Which::Ok(b) => {
836                    Ok(b)
837                },
838                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
839
840                // Protocol violations:
841                // Protocol error:
842                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
843            }
844        });
845
846    crpc!(
847        /// Whether the key is locked, and the type of protection.
848        fn [keystore::key]locked/5(&mut self) -> Result<Protection>
849        // Marshal.
850        |_root: keystore::key::locked_params::Builder| -> Result<()> {
851            Ok(())
852        };
853        // Extract.
854        |relay, captable, response: keystore::key::locked_results::Reader| {
855            use keystore::result::Which;
856            match response.get_result()?.which()? {
857                // The RPC's result:
858                Which::Ok(protection) => {
859                    Protection::try_from(protection?)
860                },
861                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
862
863                // Protocol violations:
864                // Protocol error:
865                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
866            }
867        });
868
869    crpc!(
870        /// How the password is obtained to unlock the key.
871        ///
872        /// This is independent of whether the key is currently
873        /// protected.
874        fn [keystore::key]password_source/9(&mut self) -> Result<PasswordSource>
875        // Marshal.
876        |_root: keystore::key::password_source_params::Builder| -> Result<()> {
877            Ok(())
878        };
879        // Extract.
880        |relay, captable, response: keystore::key::password_source_results::Reader| {
881            use keystore::result::Which;
882            match response.get_result()?.which()? {
883                // The RPC's result:
884                Which::Ok(password_source) => {
885                    PasswordSource::try_from(password_source?)
886                },
887                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
888
889                // Protocol violations:
890                // Protocol error:
891                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
892            }
893        });
894
895    crpc!(
896        /// Whether the key can be used for decryption.
897        fn [keystore::key]decryption_capable/6(&mut self) -> Result<bool>
898        // Marshal.
899        |_root: keystore::key::decryption_capable_params::Builder| -> Result<()> {
900            Ok(())
901        };
902        // Extract.
903        |relay, captable, response: keystore::key::decryption_capable_results::Reader| {
904            use keystore::bool_result::Which;
905            match response.get_result()?.which()? {
906                // The RPC's result:
907                Which::Ok(b) => {
908                    Ok(b)
909                },
910                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
911
912                // Protocol violations:
913                // Protocol error:
914                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
915            }
916        });
917
918    crpc!(
919        /// Whether the key can be used for signing.
920        fn [keystore::key]signing_capable/7(&mut self) -> Result<bool>
921        // Marshal.
922        |_root: keystore::key::signing_capable_params::Builder| -> Result<()> {
923            Ok(())
924        };
925        // Extract.
926        |relay, captable, response: keystore::key::signing_capable_results::Reader| {
927            use keystore::bool_result::Which;
928            match response.get_result()?.which()? {
929                // The RPC's result:
930                Which::Ok(b) => {
931                    Ok(b)
932                },
933                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
934
935                // Protocol violations:
936                // Protocol error:
937                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
938            }
939        });
940
941    crpc!(
942        /// Exports the secret key material.
943        fn [keystore::key]export/8(&mut self)
944            -> Result<openpgp::packet::Key<
945                   openpgp::packet::key::SecretParts,
946                   openpgp::packet::key::UnspecifiedRole>>
947        // Marshal.
948        |mut _root: keystore::key::export_params::Builder| -> Result<()> {
949            // Convert the arguments into the form expected by the RPC.
950            Ok(())
951        };
952        // Extract.
953        |relay, captable, response: keystore::key::export_results::Reader| {
954            use keystore::result::Which;
955            match response.get_result()?.which()? {
956                // The RPC's result:
957                Which::Ok(Ok(bytes)) => {
958                    let key = openpgp::packet::Key::from_bytes(bytes)?;
959                    let secret_key = key.parts_into_secret()?;
960                    Ok(secret_key)
961                },
962                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
963
964                // Protocol violations:
965                // Protocol error:
966                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
967                // Error reading the result from the response:
968                Which::Ok(Err(e)) => Err(anyhow::Error::from(e)),
969            }
970        });
971
972    crpc!(
973        /// Changes the key's password.
974        fn [keystore::key]change_password/10(&mut self, password: Option<&Password>)
975            -> Result<()>
976        // Marshal.
977        |root: keystore::key::change_password_params::Builder| -> Result<()> {
978            // Convert the arguments into the form expected by the RPC.
979            let mut change_password_action = root.init_password();
980            if let Some(password) = password {
981                password.map(|password| {
982                    change_password_action.set_password(&password[..]);
983                });
984            } else {
985                change_password_action.set_ask(());
986            }
987
988            Ok(())
989        };
990        // Extract.
991        |relay, captable, response: keystore::key::change_password_results::Reader| {
992            use keystore::void_result::Which;
993            match response.get_result()?.which()? {
994                // The RPC's result:
995                Which::Ok(()) => Ok(()),
996                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
997
998                // Protocol violations:
999                // Protocol error:
1000                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
1001            }
1002        });
1003
1004    crpc!(
1005        /// Deletes the specified key's secret key material.
1006        ///
1007        /// On success, the key is no registered with the device, and
1008        /// future operations on the current key handle will fail.
1009        fn [keystore::key]delete_secret_key_material/11(&mut self)
1010            -> Result<()>
1011        // Marshal.
1012        |_root: keystore::key::delete_secret_key_material_params::Builder| -> Result<()> {
1013            // Convert the arguments into the form expected by the RPC.
1014
1015            Ok(())
1016        };
1017        // Extract.
1018        |relay, captable, response: keystore::key::delete_secret_key_material_results::Reader| {
1019            use keystore::void_result::Which;
1020            match response.get_result()?.which()? {
1021                // The RPC's result:
1022                Which::Ok(()) => Ok(()),
1023                Which::Err(Ok(e)) => Err(Error::from_capnp(relay, captable, e)),
1024
1025                // Protocol violations:
1026                // Protocol error:
1027                Which::Err(Err(e)) => Err(anyhow::Error::from(e)),
1028            }
1029        });
1030}
1031
1032/// Information about key that could not be used for decryption.
1033///
1034/// This is returned by [`Keystore::decrypt`] when a key appears to be
1035/// able to decrypt a message, but the key isn't accessible, e.g.,
1036/// because it is locked.
1037#[derive(Clone)]
1038pub struct InaccessibleDecryptionKey {
1039    key: Key,
1040    pkesk: PKESK,
1041}
1042
1043impl std::fmt::Debug for InaccessibleDecryptionKey {
1044    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1045        write!(f, "InaccessibleDecryptionKey {{ {} }}",
1046               self.key.fingerprint())
1047    }
1048}
1049
1050impl InaccessibleDecryptionKey {
1051    /// Returns the key handle.
1052    pub fn key(&self) -> &Key {
1053        &self.key
1054    }
1055
1056    /// Returns the key handle.
1057    pub fn key_mut(&mut self) -> &mut Key {
1058        &mut self.key
1059    }
1060
1061    /// Returns the key handle.
1062    pub fn into_key(self) -> Key {
1063        self.key
1064    }
1065
1066    /// Returns the PKESK that could not be decrypted.
1067    ///
1068    /// Normally, you'd follow up the failed generic decryption by
1069    /// retrying with the unlocked key, and the relevant PKESK.
1070    pub fn pkesk(&self) -> &PKESK {
1071        &self.pkesk
1072    }
1073}
1074
1075
1076use openpgp::crypto::Decryptor;
1077use openpgp::crypto::Signer;
1078use openpgp::crypto::mpi::Ciphertext;
1079use openpgp::crypto::mpi::Signature;
1080
1081impl Decryptor for &mut Key {
1082    fn public(&self) -> &packet::Key<key::PublicParts, key::UnspecifiedRole> {
1083        self.public_key()
1084    }
1085
1086    fn decrypt(
1087        &mut self,
1088        ciphertext: &Ciphertext,
1089        plaintext_len: Option<usize>
1090    ) -> Result<SessionKey> {
1091        <Key as Decryptor>::decrypt(self, ciphertext, plaintext_len)
1092    }
1093}
1094
1095impl Decryptor for Key {
1096    fn public(&self) -> &packet::Key<key::PublicParts, key::UnspecifiedRole> {
1097        self.public_key()
1098    }
1099
1100    fn decrypt(
1101        &mut self,
1102        ciphertext: &Ciphertext,
1103        plaintext_len: Option<usize>
1104    ) -> Result<SessionKey> {
1105        self.decrypt_ciphertext(ciphertext, plaintext_len)
1106    }
1107}
1108
1109impl Signer for &mut Key {
1110    fn public(&self) -> &packet::Key<key::PublicParts, key::UnspecifiedRole> {
1111        self.public_key()
1112    }
1113
1114    fn sign(
1115        &mut self,
1116        hash_algo: HashAlgorithm,
1117        digest: &[u8]
1118    ) -> Result<Signature> {
1119        <Key as Signer>::sign(self, hash_algo, digest)
1120    }
1121}
1122
1123impl Signer for Key {
1124    fn public(&self) -> &packet::Key<key::PublicParts, key::UnspecifiedRole> {
1125        self.public_key()
1126    }
1127
1128    fn sign(
1129        &mut self,
1130        hash_algo: HashAlgorithm,
1131        digest: &[u8]
1132    ) -> Result<Signature> {
1133        self.sign_message(hash_algo, digest)
1134    }
1135}
1136
1137#[cfg(test)]
1138mod tests {
1139    use test_log::test;
1140
1141    use super::*;
1142
1143    use anyhow::Context as _;
1144
1145    use openpgp::Cert;
1146    use openpgp::cert::CertBuilder;
1147    use openpgp::PacketPile;
1148    use openpgp::packet::PKESK;
1149    use openpgp::packet::Packet;
1150    use openpgp::packet::SEIP;
1151    use openpgp::packet::signature::SignatureBuilder;
1152    use openpgp::parse::PacketParserBuilder;
1153    use openpgp::parse::PacketParserResult;
1154    use openpgp::parse::Parse;
1155    use openpgp::types::SignatureType;
1156
1157    use sequoia_directories::Home;
1158    use sequoia_directories::Component;
1159
1160    use testdata::password;
1161    use testdata::simple;
1162
1163    /// Tries to decrypt the message using the key store.
1164    ///
1165    /// Iterates over each of the PKESKs and tries to decrypt them
1166    /// using a key on the keystore.  If the key is in recipients and
1167    /// has a password, the key is also unlocked, if needed.
1168    ///
1169    /// If assert_exact is true, asserts that exactly the recipients
1170    /// in `recipients` decrypt the message.  That is, if there are
1171    /// two recipients, then both must decrypt the message, and no
1172    /// others.
1173    ///
1174    /// Returns the keys that decrypted the message and whether they
1175    /// were in `recipients`.
1176    fn try_decrypt(ks: &mut Keystore, msg: &[u8],
1177                   recipients: &[(Fingerprint, Option<&str>)],
1178                   assert_exact: bool)
1179        -> Result<Vec<(Fingerprint, bool)>>
1180    {
1181        let mut results: Vec<(Fingerprint, bool)> = Vec::new();
1182
1183        let mut saw_pkesk = false;
1184        let mut ppr = PacketParserBuilder::from_bytes(msg)
1185            .expect("PacketParserBuilder")
1186            .buffer_unread_content()
1187            .build()
1188            .context("Parsing message")?;
1189
1190        while let PacketParserResult::Some(pp) = ppr {
1191            // Get the packet out of the parser and start parsing
1192            // the next packet, recursing.
1193            let (packet, next_ppr) = pp.recurse()?;
1194            ppr = next_ppr;
1195
1196            if let Packet::PKESK(pkesk) = packet {
1197                saw_pkesk = true;
1198
1199                let recipient = pkesk.recipient();
1200
1201                let should_decrypt = recipients.iter()
1202                    .find(|(rcpv, _password)| {
1203                        recipient.as_ref()
1204                            .map(|r| r.aliases(KeyHandle::from(rcpv)))
1205                            .unwrap_or(false)
1206                    });
1207
1208                let recipient = if let Some(r) = recipient {
1209                    r
1210                } else {
1211                    continue;
1212                };
1213
1214                let kh = match ks.find_key(recipient.clone()) {
1215                    Ok(kh) => kh,
1216                    Err(err) => {
1217                        if should_decrypt.is_some() {
1218                            eprintln!("{} should decrypt message, \
1219                                       but isn't on the key store: {}",
1220                                      recipient, err);
1221                        }
1222                        continue;
1223                    }
1224                };
1225                let mut kh = if let Some(kh) = kh.into_iter().next() {
1226                    kh
1227                } else {
1228                    continue;
1229                };
1230                let fpr = kh.fingerprint();
1231                assert!(recipient.aliases(KeyHandle::from(&fpr)));
1232                let recipient: Fingerprint = fpr;
1233
1234                let decrypted = pkesk.decrypt(&mut kh, None);
1235
1236                match (decrypted, should_decrypt) {
1237                    (Some(_), Some((_, _))) => {
1238                        eprintln!("PKESK ({}) decrypted as expected.",
1239                                  recipient);
1240                        results.push((recipient.clone(), true));
1241                    }
1242                    (Some(_), None) => {
1243                        eprintln!("PKESK ({}) unexpectedly decrypted!",
1244                                  recipient);
1245                        results.push((recipient.clone(), false));
1246                    }
1247                    (None, Some((_, password))) => {
1248                        if let Some(password) = password {
1249                            if let Err(err) = kh.unlock(Password::from(*password)) {
1250                                eprintln!("Failed to unlock {}: {}",
1251                                          recipient, err);
1252                            } else {
1253                                if pkesk.decrypt(&mut kh, None).is_some() {
1254                                    results.push((recipient.clone(), true));
1255                                } else {
1256                                    eprintln!("Failed to decrypt PKESK for {} \
1257                                               after unlocking it",
1258                                              recipient);
1259                                }
1260                            }
1261                        } else {
1262                            eprintln!("Failed to unlock PKESK for {}",
1263                                      recipient);
1264                        }
1265                    }
1266                    (None, None) => {
1267                        eprintln!("Failed to decrypt PKESK ({}), \
1268                                   and shouldn't have.",
1269                                  recipient);
1270                    }
1271                }
1272            }
1273        }
1274
1275        // All messages have at least one PKESK.
1276        assert!(saw_pkesk);
1277
1278        if assert_exact {
1279            let mut decryptors = results.iter()
1280                .map(|(decryptor, expected)| {
1281                    assert!(expected, "Unexpected decrypted PKESK for {}",
1282                            decryptor);
1283                    decryptor
1284                })
1285                .collect::<Vec<&Fingerprint>>();
1286            decryptors.sort();
1287
1288            let mut recipients: Vec<&Fingerprint>
1289                = recipients.iter().map(|(r, _)| r).collect();
1290            recipients.sort();
1291
1292            assert_eq!(decryptors, recipients);
1293        }
1294
1295        Ok(results)
1296    }
1297
1298    // A simple test that lists all the keys.
1299    #[test]
1300    #[cfg(feature = "softkeys")]
1301    fn simple_ping() -> Result<()> {
1302        let home = Home::ephemeral().unwrap();
1303        eprintln!("Using {}", home);
1304        let keystore_home = home.data_dir(Component::Keystore);
1305
1306        let source = simple::dir().join("keystore");
1307        dircpy::copy_dir(&source, &keystore_home)
1308            .with_context(|| format!("Copying {:?} to {:?}",
1309                                     source, keystore_home))?;
1310
1311        // Start and connect to the keystore.
1312        let c = Context::configure()
1313            .ephemeral()
1314            .home(keystore_home)
1315            .build()?;
1316        let mut ks = Keystore::connect(&c)?;
1317
1318        let mut backends = ks.backends()?;
1319        eprintln!("Got {} backends", backends.len());
1320        for backend in &mut backends {
1321            eprintln!(" - {}", backend.id()?);
1322        }
1323
1324        eprintln!("Listing devices");
1325        let mut saw_softkeys = false;
1326        for backend in &mut backends {
1327            let is_softkeys = backend.id().map(|id| id == "softkeys")
1328                .unwrap_or(false);
1329            if is_softkeys {
1330                saw_softkeys = true;
1331            }
1332
1333            eprintln!(" - {}", backend.id()?);
1334            let devices = backend.devices()?;
1335            if is_softkeys {
1336                assert_eq!(devices.len(), 3);
1337            }
1338            for mut device in devices {
1339                eprintln!("   - {}", device.id()?);
1340                let keys = device.keys()?;
1341                if is_softkeys {
1342                    assert_eq!(keys.len(), 4);
1343                }
1344                for mut key in keys.into_iter() {
1345                    eprintln!("     - {}", key.id()?);
1346                }
1347            }
1348        }
1349        assert!(saw_softkeys);
1350
1351        Ok(())
1352    }
1353
1354    // Bash on the relay from multiple threads.
1355    #[test]
1356    #[cfg(feature = "softkeys")]
1357    fn simple_bash() -> Result<()> {
1358        use std::thread;
1359        use std::sync::Mutex;
1360
1361        let home = Home::ephemeral().unwrap();
1362        eprintln!("Using {}", home);
1363        let keystore_home = home.data_dir(Component::Keystore);
1364
1365        let source = simple::dir().join("keystore");
1366        dircpy::copy_dir(&source, &keystore_home)
1367            .with_context(|| format!("Copying {:?} to {:?}",
1368                                     source, keystore_home))?;
1369
1370        // Start and connect to the keystore.
1371        let c = Context::configure()
1372            .ephemeral()
1373            .home(keystore_home)
1374            .build()?;
1375        let ks = Arc::new(Mutex::new(Box::new(Keystore::connect(&c)?)));
1376
1377        let handles: Vec<_> = (0..10u32).map(|t| {
1378            let ks = Arc::clone(&ks);
1379            thread::spawn(move || -> Result<()> {
1380                for _ in 0..10 {
1381                    thread::yield_now();
1382
1383                    let mut ks = ks.lock().unwrap();
1384                    let backends: Vec<Backend> = ks.backends()?;
1385                    // Drop ks to increase concurrency.
1386                    drop(ks);
1387
1388                    let mut saw_softkeys = false;
1389                    for (b, mut backend) in &mut backends.into_iter().enumerate() {
1390                        let is_softkeys = backend.id().map(|id| id == "softkeys")
1391                            .unwrap_or(false);
1392                        if is_softkeys {
1393                            saw_softkeys = true;
1394                        }
1395
1396                        // Don't just use a capability once and then throw it
1397                        // away.
1398                        for _ in 1..3 {
1399                            eprintln!(" {}.{}. {}", t, b, backend.id()?);
1400                            let devices = backend.devices()?;
1401                            if is_softkeys {
1402                                assert_eq!(devices.len(), 3);
1403                            }
1404                            for (d, mut device) in devices.into_iter().enumerate() {
1405                                for _ in 1..3 {
1406                                    eprintln!("   {}.{}.{}. {}",
1407                                              t, b, d, device.id()?);
1408                                    let keys = device.keys()?;
1409                                    if is_softkeys {
1410                                        assert_eq!(keys.len(), 4);
1411                                    }
1412                                    for (k, mut key) in keys.into_iter().enumerate() {
1413                                        eprintln!("     {}.{}.{}.{}. {}",
1414                                                  t, b, d, k, key.id()?);
1415                                    }
1416                                }
1417                            }
1418                        }
1419                    }
1420                    assert!(saw_softkeys);
1421                }
1422
1423                Ok(())
1424            })
1425        }).collect();
1426
1427        for h in handles.into_iter() {
1428            h.join().unwrap().expect("worked");
1429        }
1430
1431        Ok(())
1432    }
1433
1434    // Test Keystore::decrypt using the simple keystore.
1435    #[test]
1436    #[cfg(feature = "softkeys")]
1437    fn simple_keystore_decrypt() -> Result<()> {
1438        let home = Home::ephemeral().unwrap();
1439        eprintln!("Using {}", home);
1440        let keystore_home = home.data_dir(Component::Keystore);
1441
1442        let source = simple::dir().join("keystore");
1443        dircpy::copy_dir(&source, &keystore_home)
1444            .with_context(|| format!("Copying {:?} to {:?}",
1445                                     source, keystore_home))?;
1446
1447        // Start and connect to the keystore.
1448        let c = Context::configure()
1449            .ephemeral()
1450            .home(keystore_home)
1451            .build()?;
1452        let mut ks = Keystore::connect(&c)?;
1453
1454        // Run the tests.
1455        let mut bad = 0;
1456        for msg in simple::msgs() {
1457            eprintln!("Decrypting {}", msg.filename);
1458
1459            let mut pkesks = Vec::new();
1460
1461            let mut decrypted = false;
1462            let mut ppr = PacketParserBuilder::from_bytes(
1463                    testdata::file(msg.filename))?
1464                .buffer_unread_content()
1465                .build()?;
1466            while let PacketParserResult::Some(mut pp) = ppr {
1467                if let Packet::SEIP(_) = pp.packet {
1468                    match ks.decrypt(&pkesks[..]) {
1469                        // Decrypted, but shouldn't have.
1470                        Ok(_) if msg.recipients.is_empty() => {
1471                            eprintln!("Decrypted, but should have failed");
1472                            bad += 1;
1473                        }
1474                        // Decrypted, and should have.
1475                        Ok((i, fpr, algo, sk)) => {
1476                            let fpr = KeyHandle::from(fpr);
1477
1478                            // Make sure we used an expected PKESK.
1479                            if ! msg.recipients.iter().any(|&r| {
1480                                KeyHandle::from(r).aliases(&fpr)
1481                            })
1482                            {
1483                                eprintln!("fpr ({:?}) is not an expected \
1484                                           recipient ({})",
1485                                          fpr,
1486                                          msg.recipients
1487                                              .iter()
1488                                              .map(|r| format!("{:?}", r))
1489                                              .collect::<Vec<String>>()
1490                                              .join(", "));
1491                                bad += 1;
1492                                break;
1493                            }
1494
1495                            // Make sure the fpr and the pkesk match.
1496                            if ! pkesks[i].recipient()
1497                                .map(|r| fpr.aliases(r))
1498                                .unwrap_or(true)
1499                            {
1500                                eprintln!("fpr ({}) and pkesk ({}) \
1501                                           don't match",
1502                                          fpr, pkesks[i].recipient().unwrap());
1503                                bad += 1;
1504                                break;
1505                            }
1506
1507                            // Decrypt the SEIP.
1508                            match pp.decrypt(algo, &sk) {
1509                                Ok(()) => {
1510                                    decrypted = true;
1511                                }
1512                                Err(err) => {
1513                                    eprintln!("Failed to decrypt SEIP: {}",
1514                                              err);
1515                                    bad += 1;
1516                                    break;
1517                                }
1518                            }
1519                        }
1520
1521                        // Can't decrypt, as expected.
1522                        Err(_) if msg.recipients.is_empty() => break,
1523                        // Can't decrypt, and that's a problem.
1524                        Err(err) => {
1525                            eprintln!("Failed to decrypt: {}", err);
1526                            bad += 1;
1527                            break;
1528                        }
1529                    }
1530                }
1531
1532                // Get the packet out of the parser and start parsing
1533                // the next packet, recursing.
1534                let (packet, next_ppr) = pp.recurse()?;
1535                ppr = next_ppr;
1536
1537                #[allow(deprecated)]
1538                match packet {
1539                    Packet::PKESK(pkesk) if ! decrypted => pkesks.push(pkesk),
1540                    Packet::SEIP(_) if decrypted => (),
1541                    Packet::MDC(_) if decrypted => (),
1542                    Packet::CompressedData(_) if decrypted => (),
1543                    Packet::Literal(lit) if decrypted => {
1544                        if msg.content.as_bytes() != lit.body() {
1545                            eprintln!("Decrypted plaintext does not match \
1546                                       expected plaintext:\n    got: {:?}\n\
1547                                       expected: {:?}",
1548                                      String::from_utf8_lossy(lit.body()),
1549                                      msg.content);
1550                            bad += 1;
1551                            break;
1552                        }
1553                    }
1554                    p => unreachable!("Unexpected packet: {}.", p.tag()),
1555                }
1556            }
1557        }
1558
1559        if bad > 0 {
1560            panic!("{} tests failed", bad);
1561        }
1562
1563        Ok(())
1564    }
1565
1566    // Test Key::decrypt_pkesk using the simple keystore.
1567    #[test]
1568    #[cfg(feature = "softkeys")]
1569    fn simple_key_decrypt_pkesk() -> Result<()> {
1570        let home = Home::ephemeral().unwrap();
1571        eprintln!("Using {}", home);
1572        let keystore_home = home.data_dir(Component::Keystore);
1573
1574        let source = simple::dir().join("keystore");
1575        dircpy::copy_dir(&source, &keystore_home)
1576            .with_context(|| format!("Copying {:?} to {:?}",
1577                                     source, keystore_home))?;
1578
1579        // Start and connect to the keystore.
1580        let c = Context::configure()
1581            .ephemeral()
1582            .home(keystore_home)
1583            .build()?;
1584        let mut ks = Keystore::connect(&c)?;
1585
1586        // We also try to decrypt with Alice's and Carol's primary
1587        // keys to make sure that that fails.
1588        let alice_pri = ks.find_key(KeyHandle::from(&simple::fp().alice_pri))
1589            .expect("keystore is up");
1590        // In the simple keystore, keys are not repeated.
1591        assert!(alice_pri.len() <= 1);
1592        let mut alice_pri = if let Some(kh) = alice_pri.into_iter().next() {
1593            kh
1594        } else {
1595            panic!("Alice's primary key is not present on the key store.");
1596        };
1597
1598        let carol_pri = ks.find_key(KeyHandle::from(&simple::fp().carol_pri))
1599            .expect("keystore is up");
1600        // In the simple keystore, keys are not repeated.
1601        assert!(carol_pri.len() <= 1);
1602        let mut carol_pri = if let Some(kh) = carol_pri.into_iter().next() {
1603            kh
1604        } else {
1605            panic!("Carol's primary key is not present on the key store.");
1606        };
1607
1608
1609        // Run the tests.
1610        let mut bad = 0;
1611        for msg in simple::msgs() {
1612            eprintln!("Decrypting {}", msg.filename);
1613
1614            let mut saw_pkesk = false;
1615            let mut ppr = PacketParserBuilder::from_bytes(
1616                    testdata::file(msg.filename))?
1617                .buffer_unread_content()
1618                .build()?;
1619            while let PacketParserResult::Some(pp) = ppr {
1620                // Get the packet out of the parser and start parsing
1621                // the next packet, recursing.
1622                let (packet, next_ppr) = pp.recurse()?;
1623                ppr = next_ppr;
1624
1625                if let Packet::PKESK(pkesk) = packet {
1626                    saw_pkesk = true;
1627
1628                    let recip = pkesk.recipient();
1629
1630                    let should_decrypt = msg.recipients
1631                        .iter()
1632                        .any(|&r| {
1633                            recip.as_ref()
1634                                .map(|recip| recip.aliases(&KeyHandle::from(r)))
1635                                .unwrap_or(false)
1636                        });
1637
1638                    let recip = if let Some(r) = recip {
1639                        r
1640                    } else {
1641                        continue;
1642                    };
1643
1644                    let kh = ks.find_key(recip.clone())?;
1645                    // In the simple keystore, keys are not repeated.
1646                    assert!(kh.len() <= 1);
1647                    let mut kh = if let Some(kh) = kh.into_iter().next() {
1648                        kh
1649                    } else {
1650                        // No key corresponding to recip in the key
1651                        // store.
1652                        if should_decrypt {
1653                            eprintln!("Should decrypt PKESK ({}), \
1654                                       but there is no key for it on the \
1655                                       key store.",
1656                                      recip);
1657                            bad += 1;
1658                        }
1659                        continue;
1660                    };
1661
1662                    let decrypted = pkesk.decrypt(&mut kh, None);
1663
1664                    match (decrypted, should_decrypt) {
1665                        (Some(_), true) => {
1666                            eprintln!("PKESK ({}) decrypted as expected.",
1667                                      recip);
1668                        }
1669                        (Some(_), false) => {
1670                            eprintln!("PKESK ({}) unexpectedly decrypted!",
1671                                      recip);
1672                            bad += 1;
1673                        }
1674                        (None, true) => {
1675                            eprintln!("Failed to decrypt PKESK ({}), \
1676                                       but should have!",
1677                                      recip);
1678                            bad += 1;
1679                        }
1680                        (None, false) => {
1681                            eprintln!("Failed to decrypt PKESK ({}), \
1682                                       and shouldn't have.",
1683                                      recip);
1684                        }
1685                    }
1686
1687                    // Make sure we can't decrypt using alice's or
1688                    // carol's primary keys.
1689                    if pkesk.decrypt(&mut alice_pri, None).is_some() {
1690                        eprintln!("Unexpected decrypted message using \
1691                                   alice's primary key");
1692                        bad += 1;
1693                    }
1694                    if pkesk.decrypt(&mut carol_pri, None).is_some() {
1695                        eprintln!("Unexpected decrypted message using \
1696                                   carol's primary key");
1697                        bad += 1;
1698                    }
1699                }
1700            }
1701
1702            // All messages have at least one PKESK.
1703            assert!(saw_pkesk);
1704        }
1705
1706        if bad > 0 {
1707            panic!("{} tests failed", bad);
1708        }
1709
1710        Ok(())
1711    }
1712
1713    #[test]
1714    #[cfg(feature = "softkeys")]
1715    fn simple_key_sign() -> Result<()> {
1716        let home = Home::ephemeral().unwrap();
1717        eprintln!("Using {}", home);
1718        let keystore_home = home.data_dir(Component::Keystore);
1719
1720        let source = simple::dir().join("keystore");
1721        dircpy::copy_dir(&source, &keystore_home)
1722            .with_context(|| format!("Copying {:?} to {:?}",
1723                                     source, keystore_home))?;
1724
1725        let certs = [
1726            testdata::file("simple/keystore/softkeys/alice.pgp"),
1727            testdata::file("simple/keystore/softkeys/bob.pgp"),
1728            testdata::file("simple/keystore/softkeys/carol.pgp")
1729        ];
1730        let certs: Vec<Cert> = certs.iter()
1731            .map(|cert| {
1732                Cert::from_bytes(cert)
1733            })
1734            .collect::<Result<Vec<Cert>>>()?;
1735        let lookup = |fpr: Fingerprint| {
1736            certs
1737                .iter()
1738                .flat_map(|cert| cert.keys())
1739                .find(|k| {
1740                    k.key().fingerprint() == fpr
1741                })
1742        };
1743
1744        // Start and connect to the keystore.
1745        let c = Context::configure()
1746            .ephemeral()
1747            .home(keystore_home)
1748            .build()?;
1749        let mut ks = Keystore::connect(&c)?;
1750
1751        let msg = b"hi?!";
1752
1753        let mut bad = 0;
1754
1755        let mut backends = ks.backends()?;
1756
1757        let mut saw_softkeys = false;
1758        for backend in &mut backends {
1759            let is_softkeys = backend.id().map(|id| id == "softkeys")
1760                .unwrap_or(false);
1761            if is_softkeys {
1762                saw_softkeys = true;
1763            } else {
1764                continue;
1765            }
1766
1767            let devices = backend.devices()?;
1768            assert_eq!(devices.len(), 3);
1769
1770            for mut device in devices {
1771                let keys = device.keys()?;
1772                assert_eq!(keys.len(), 4);
1773
1774                for mut key in keys.into_iter() {
1775                    let ka = lookup(key.fingerprint())
1776                        .expect("have corresponding certificate");
1777
1778                    eprintln!("  - {} ({}, {})",
1779                              ka.key().fingerprint(),
1780                              ka
1781                                  .cert()
1782                                  .userids()
1783                                  .next()
1784                                  .map(|ua| {
1785                                      String::from_utf8_lossy(ua.userid().value())
1786                                          .into_owned()
1787                                  })
1788                                  .unwrap_or_else(|| {
1789                                      String::from("<no user ids>")
1790                                  }),
1791                              ka.key().pk_algo());
1792
1793                    // Note: we don't consider keyflags, because the
1794                    // key store can't either (even if a backend has
1795                    // the whole cert, it may not be up to date).
1796                    let bad_key = ! ka.key().pk_algo().for_signing();
1797
1798                    let sig = SignatureBuilder::new(SignatureType::Binary);
1799
1800                    match sig.sign_message(&mut key, msg) {
1801                        Ok(sig) => {
1802                            if bad_key {
1803                                eprintln!("Key created signature, \
1804                                           but shouldn't have.");
1805                                bad += 1;
1806                                continue;
1807                            }
1808
1809                            // Make sure the signature checks out.
1810                            if let Err(err) = sig.clone()
1811                                .verify_message(ka.key(), msg)
1812                            {
1813                                eprintln!("Failed to verify signature, \
1814                                           but should have: {}", err);
1815                                bad += 1;
1816                                continue;
1817                            }
1818                        }
1819                        Err(err) => {
1820                            if ! bad_key {
1821                                eprintln!("Key failed to create signature, \
1822                                           but should have: {}",
1823                                          err);
1824                                bad += 1;
1825                                continue;
1826                            }
1827                        }
1828                    }
1829                }
1830            }
1831        }
1832        assert!(saw_softkeys);
1833
1834        if bad > 0 {
1835            panic!("{} tests failed", bad);
1836        }
1837
1838        Ok(())
1839    }
1840
1841    // Test Key::decrypt_pkesk using the password keystore.
1842    #[test]
1843    #[cfg(feature = "softkeys")]
1844    fn password_key_decrypt_pkesk() -> Result<()> {
1845        let _ = env_logger::Builder::from_default_env().try_init();
1846
1847        let home = Home::ephemeral().unwrap();
1848        eprintln!("Using {}", home);
1849        let keystore_home = home.data_dir(Component::Keystore);
1850
1851        let source = password::dir().join("keystore");
1852        dircpy::copy_dir(&source, &keystore_home)
1853            .with_context(|| format!("Copying {:?} to {:?}",
1854                                     source, keystore_home))?;
1855
1856        // Start and connect to the keystore.
1857        let c = Context::configure()
1858            .ephemeral()
1859            .home(keystore_home)
1860            .build()?;
1861        let mut ks = Keystore::connect(&c)?;
1862
1863        // Run the tests.
1864        for (msg, pw) in password::msgs() {
1865            eprintln!("Decrypting {}", msg.filename);
1866
1867            let content = testdata::file(msg.filename);
1868
1869            let recipients = msg.recipients.iter().map(|&r| (r.clone(), pw))
1870                .collect::<Vec<(Fingerprint, Option<&str>)>>();
1871            try_decrypt(
1872                &mut ks, content, &recipients[..], true)
1873                .unwrap();
1874        }
1875
1876        Ok(())
1877    }
1878
1879    // Test Key::decrypt_pkesk using the password keystore.
1880    #[test]
1881    #[cfg(feature = "softkeys")]
1882    fn password_key_decrypt_pkesk2() -> Result<()> {
1883        let home = Home::ephemeral().unwrap();
1884        eprintln!("Using {}", home);
1885        let keystore_home = home.data_dir(Component::Keystore);
1886
1887        let source = password::dir().join("keystore");
1888        dircpy::copy_dir(&source, &keystore_home)
1889            .with_context(|| format!("Copying {:?} to {:?}",
1890                                     source, keystore_home))?;
1891
1892        // Start and connect to the keystore.
1893        let c = Context::configure()
1894            .ephemeral()
1895            .home(keystore_home)
1896            .build()?;
1897        let mut ks = Keystore::connect(&c)?;
1898
1899        for (msg, password) in testdata::password::msgs() {
1900            eprintln!("{}", msg.filename);
1901
1902            let pp = PacketPile::from_bytes(testdata::file(msg.filename))
1903                .expect("valid OpenPGP message");
1904
1905            pp.children().enumerate().for_each(|(i, p)| {
1906                eprintln!("  {}: {}", i, p.tag());
1907            });
1908
1909            let pkesks: Vec<PKESK> = pp.children()
1910                .filter_map(|p| {
1911                    match p {
1912                        Packet::PKESK(p) => Some(p.clone()),
1913                        _ => None,
1914                    }
1915                })
1916                .collect();
1917            assert!(pkesks.len() > 0);
1918
1919            let seip: Vec<&SEIP> = pp.children()
1920                .filter_map(|p| {
1921                    match p {
1922                        Packet::SEIP(p) => Some(p),
1923                        _ => None,
1924                    }
1925                })
1926                .collect();
1927            assert!(seip.len() == 1);
1928
1929            match (ks.decrypt(&pkesks), password) {
1930                (Ok(_), None) => {
1931                    // Decrypted and no password is required.  Success.
1932                }
1933                (Ok(_), Some(_password)) => {
1934                    panic!("Decrypted, but a password should be required.");
1935                }
1936                (Err(err), None) => {
1937                    panic!("Failed to decrypt, but a password isn't required: {}.",
1938                           err);
1939                }
1940                (Err(mut err), Some(password)) => {
1941                    let keys = if let Some(Error::InaccessibleDecryptionKey(keys))
1942                        = err.downcast_mut()
1943                    {
1944                        keys
1945                    } else {
1946                        panic!("Unexpected error decrypting message: {}",
1947                               err);
1948                    };
1949
1950                    // There's only one.
1951                    assert_eq!(keys.len(), 1);
1952                    let key = &mut keys[0];
1953                    let pkesk = key.pkesk().clone();
1954
1955                    // Try to decryt it; it should still be locked.
1956                    let r = pkesk.decrypt(key.key_mut(), None);
1957                    assert!(r.is_none());
1958
1959                    // Unlock it and try again.
1960                    key.key_mut().unlock(Password::from(password))
1961                        .expect("correct password");
1962
1963                    let r = pkesk.decrypt(key.key_mut(), None);
1964                    assert!(r.is_some());
1965                }
1966            }
1967        }
1968
1969        Ok(())
1970    }
1971
1972    // Test Key::import and Key::export.
1973    #[test]
1974    #[cfg(feature = "softkeys")]
1975    fn import_export() -> Result<()> {
1976        let home = Home::ephemeral().unwrap();
1977        eprintln!("Using {}", home);
1978        let keystore_home = home.data_dir(Component::Keystore);
1979
1980        // Start and connect to the keystore.
1981        let c = Context::configure()
1982            .ephemeral()
1983            .home(keystore_home)
1984            .build()?;
1985        let mut ks = Keystore::connect(&c)?;
1986
1987        let mut softkeys = None;
1988        for mut backend in ks.backends()?.into_iter() {
1989            if backend.id().expect("ok") == "softkeys" {
1990                softkeys = Some(backend);
1991                break;
1992            }
1993        }
1994        let mut softkeys = softkeys.expect("have softkeys backend");
1995
1996        use openpgp::cert::CipherSuite::*;
1997        for cs in [ Cv25519, RSA3k, P256, P384, P521, RSA2k, RSA4k ] {
1998            if cs.is_supported().is_err() {
1999                continue;
2000            }
2001
2002            eprintln!("Testing a {:?} cert", cs);
2003
2004            let (cert, _rev) = CertBuilder::general_purpose(
2005                Some("alice"))
2006                .set_cipher_suite(cs)
2007                .generate()?;
2008
2009            softkeys.import(&cert).expect("can import");
2010
2011            for key in cert.keys() {
2012                eprintln!("Exporting {}", key.key().fingerprint());
2013
2014                let key = key.parts_into_secret().expect("has secret");
2015
2016                let remote = ks.find_key(key.key().key_handle()).expect("have key");
2017                assert_eq!(remote.len(), 1, "only one key under this name");
2018                let mut remote = remote.into_iter().next().unwrap();
2019                assert_eq!(remote.fingerprint(), key.key().fingerprint());
2020
2021                let export = remote.export().expect("can export");
2022                assert_eq!(&export, key.key());
2023            }
2024        }
2025
2026        Ok(())
2027    }
2028
2029
2030    // Test Key::password_source.
2031    #[test]
2032    #[cfg(feature = "softkeys")]
2033    fn password_source() -> Result<()> {
2034        let home = Home::ephemeral().unwrap();
2035        eprintln!("Using {}", home);
2036        let keystore_home = home.data_dir(Component::Keystore);
2037
2038        // Start and connect to the keystore.
2039        let c = Context::configure()
2040            .ephemeral()
2041            .home(keystore_home)
2042            .build()?;
2043        let mut ks = Keystore::connect(&c)?;
2044
2045        let mut softkeys = None;
2046        for mut backend in ks.backends()?.into_iter() {
2047            if backend.id().expect("ok") == "softkeys" {
2048                softkeys = Some(backend);
2049                break;
2050            }
2051        }
2052        let mut softkeys = softkeys.expect("have softkeys backend");
2053
2054        // This is a pretty naive test: we just make sure the backend
2055        // returns success.
2056        for password in [false, true] {
2057            let mut builder = CertBuilder::general_purpose(Some("alice"));
2058            if password {
2059                builder = builder.set_password(Some("foo".into()));
2060            }
2061            let (cert, _rev) = builder.generate()?;
2062
2063            let result = softkeys.import(&cert).expect("can import");
2064            assert_eq!(result.len(), cert.keys().count());
2065            for (_import_status, mut key) in result.into_iter() {
2066                match key.locked() {
2067                    Ok(Protection::Unlocked) => {
2068                        if password {
2069                            panic!("Key is password protected and should be locked, \
2070                                    but is unlocked?");
2071                        }
2072                    }
2073                    Ok(other) => {
2074                        if ! password {
2075                            panic!("Key is not password protected and shouldn't \
2076                                    be locked, but got: {:?}",
2077                                   other);
2078                        }
2079                    }
2080                    Err(err) => {
2081                        panic!("Getting locked status: {}", err);
2082                    }
2083                }
2084                assert!(key.password_source().is_ok());
2085            }
2086        }
2087
2088        Ok(())
2089    }
2090
2091    // Test Key::change_password
2092    #[test]
2093    #[cfg(feature = "softkeys")]
2094    fn change_password() -> Result<()> {
2095        let _ = env_logger::Builder::from_default_env().try_init();
2096
2097        let home = Home::ephemeral().unwrap();
2098        eprintln!("Using {}", home);
2099        let keystore_home = home.data_dir(Component::Keystore);
2100
2101        let source = password::dir().join("keystore");
2102        dircpy::copy_dir(&source, &keystore_home)
2103            .with_context(|| format!("Copying {:?} to {:?}",
2104                                     source, keystore_home))?;
2105
2106        // Start and connect to the keystore.
2107        let c = Context::configure()
2108            .ephemeral()
2109            .home(keystore_home)
2110            .build()?;
2111        let mut ks = Keystore::connect(&c)?;
2112
2113        // Run the tests.
2114        for (msg, pw) in password::msgs() {
2115            eprintln!("Decrypting {}", msg.filename);
2116
2117            let content = testdata::file(msg.filename);
2118
2119            let new_password = "a NEW pa$$word";
2120
2121            let recipients = msg.recipients.iter().map(|&r| (r.clone(), pw))
2122                .collect::<Vec<(Fingerprint, Option<&str>)>>();
2123
2124            try_decrypt(
2125                &mut ks, content, &recipients[..], true)
2126                .unwrap();
2127
2128            // Change the passwords.
2129            let recipients = msg.recipients.iter()
2130                .map(|&r| {
2131                    let kh = ks.find_key(KeyHandle::from(r))
2132                        .expect(&format!("Have key {}", r));
2133                    let mut kh = if let Some(kh) = kh.into_iter().next() {
2134                        kh
2135                    } else {
2136                        panic!("Should have a key for {}", r);
2137                    };
2138
2139                    if let Some(pw) = pw {
2140                        if let Protection::Password(_hint)
2141                            = kh.locked().expect("locked")
2142                        {
2143                            kh.unlock(Password::from(pw))
2144                                .expect("Can unlock locked key");
2145                        }
2146                    }
2147                    kh.change_password(Some(&Password::from(new_password)))
2148                        .expect("can change password");
2149
2150                    (r.clone(), Some(new_password))
2151                })
2152                .collect::<Vec<(Fingerprint, Option<&str>)>>();
2153
2154            try_decrypt(
2155                &mut ks, content, &recipients[..], true)
2156                .unwrap();
2157        }
2158
2159
2160        Ok(())
2161    }
2162}