Debian Codegraph @

src/sq.rs

raw
1 use std::borrow::Borrow;
2 use std::cell::RefCell;
3 use std::collections::BTreeMap;
4 use std::collections::btree_map::Entry;
5 use std::fmt;
6 use std::path::{Path, PathBuf};
7 use std::sync::Arc;
8 use std::sync::Mutex;
9 use std::time::SystemTime;
10
11 use typenum::Unsigned;
12
13 use anyhow::anyhow;
14 use anyhow::Context as _;
15
16 use once_cell::sync::OnceCell;
17
18 use sequoia_openpgp as openpgp;
19 use openpgp::Cert;
20 use openpgp::crypto;
21 use openpgp::crypto::Password;
22 use openpgp::Fingerprint;
23 use openpgp::KeyHandle;
24 use openpgp::Result;
25 use openpgp::cert::prelude::*;
26 use openpgp::cert::raw::RawCertParser;
27 use openpgp::packet::key::PublicParts;
28 use openpgp::packet::prelude::*;
29 use openpgp::parse::Parse;
30 use openpgp::policy::Policy;
31 use openpgp::policy::StandardPolicy as P;
32 use openpgp::policy::NullPolicy;
33 use openpgp::types::KeyFlags;
34 use openpgp::types::RevocationStatus;
35 use openpgp::types::RevocationType;
36
37 use sequoia_cert_store as cert_store;
38 use cert_store::LazyCert;
39 use cert_store::Store;
40 use cert_store::store::MergePublicCollectStats;
41 use cert_store::store::StoreError;
42 use cert_store::store::StoreUpdate;
43 use cert_store::store::UserIDQueryParams;
44
45 use sequoia_wot as wot;
46 use wot::store::Store as _;
47
48 use sequoia_keystore as keystore;
49 use keystore::Protection;
50
51 use crate::cli;
52 use crate::cli::types::CertDesignators;
53 use crate::cli::types::FileStdinOrKeyHandle;
54 use crate::cli::types::KeyDesignators;
55 use crate::cli::types::SpecialName;
56 use crate::cli::types::StdinWarning;
57 use crate::cli::types::cert_designator;
58 use crate::cli::types::key_designator;
59 use crate::cli::types::paths::StateDirectory;
60 use crate::common::password;
61 use crate::common::ui;
62 use crate::output::hint::Hint;
63 use crate::output::import::{ImportStats, ImportStatus};
64 use crate::PreferredUserID;
65 use crate::print_error_chain;
66
67 const TRACE: bool = false;
68
69 pub static NULL_POLICY: NullPolicy = unsafe { NullPolicy::new() };
70
71 /// Flags for Sq::get_keys and related functions.
72 #[derive(Debug, Clone, PartialEq, Eq)]
73 pub enum GetKeysOptions {
74 /// Don't ignore keys that are not alive.
75 AllowNotAlive,
76 /// Don't ignore keys that are not revoke.
77 AllowRevoked,
78 /// Use the NULL Policy.
79 NullPolicy,
80 }
81
82 /// Flag for Sq::get_keys and related function.
83 enum KeyType {
84 /// Only consider primary key.
85 Primary,
86 /// Only consider keys that have at least one of the specified
87 /// capabilities.
88 KeyFlags(KeyFlags),
89 }
90
91 /// The degree to which a binding needs to be authenticated.
92 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
93 pub enum TrustThreshold {
94 /// The binding must be fully authenticated.
95 Full = wot::FULLY_TRUSTED as isize,
96 /// The binding must be minimally authenticated (>= 1 out of 120).
97 Minimal = 1,
98 /// The binding doesn't need to be authenticated.
99 YOLO = 0,
100 }
101
102 impl From<TrustThreshold> for usize {
103 fn from(a: TrustThreshold) -> usize {
104 a as isize as usize
105 }
106 }
107
108 impl From<&TrustThreshold> for usize {
109 fn from(a: &TrustThreshold) -> usize {
110 *a as isize as usize
111 }
112 }
113
114 impl std::fmt::Display for TrustThreshold {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 write!(f, "{}", usize::from(self))
117 }
118 }
119
120
121 // A shorthand for our store type.
122 type WotStore<'store, 'rstore>
123 = wot::store::CertStore<'store, 'rstore, cert_store::CertStore<'store>>;
124
125 pub struct Sq<'store, 'rstore>
126 where 'store: 'rstore
127 {
128 pub config_file: crate::config::ConfigFile,
129 pub config: crate::config::Config,
130
131 /// Overwrite existing files.
132 pub overwrite: bool,
133
134 /// Prevent any kind of interactive prompting.
135 pub batch: bool,
136
137 pub time: SystemTime,
138 pub time_is_now: bool,
139 pub policy: &'rstore P<'rstore>,
140 pub policy_as_of: SystemTime,
141 pub home: Option<sequoia_directories::Home>,
142 pub cert_store_path: Option<StateDirectory>,
143 pub keyrings: Vec<PathBuf>,
144 // Map from key fingerprint to cert fingerprint and the key.
145 pub keyring_tsks: OnceCell<BTreeMap<
146 Fingerprint,
147 (Fingerprint, Key<key::PublicParts, key::UnspecifiedRole>)>>,
148
149 /// This will be set if the cert store has not been disabled, OR
150 /// --keyring is passed.
151 pub cert_store: OnceCell<WotStore<'store, 'rstore>>,
152
153 // The value of --trust-root.
154 pub trust_roots: Vec<Fingerprint>,
155 // The local trust root, as set in the cert store.
156 pub trust_root_local: OnceCell<Option<Fingerprint>>,
157
158 // The key store.
159 pub key_store_path: Option<StateDirectory>,
160 pub key_store: OnceCell<Mutex<keystore::Keystore>>,
161
162 /// A password cache. When encountering a locked key, we first
163 /// consult the password cache. The passwords are only tried if
164 /// it is safe. That is, the passwords are only tried if we are
165 /// sure that the key is not protected by a retry counter. If the
166 /// password cache doesn't contain the correct password, or the
167 /// key is protected by a retry counter, the user is prompted to
168 /// unlock the key. The correct password is added to the cache.
169 pub password_cache: Mutex<Vec<Password>>,
170 }
171
172 impl<'store: 'rstore, 'rstore> Sq<'store, 'rstore> {
173 /// Be verbose.
174 pub fn verbose(&self) -> bool {
175 self.config.verbose()
176 }
177
178 /// Be quiet.
179 pub fn quiet(&self) -> bool {
180 self.config.quiet()
181 }
182
183 /// Returns whether the cert store is disabled.
184 fn no_rw_cert_store(&self) -> bool {
185 self.cert_store_path.as_ref()
186 .map(|s| s.is_none())
187 .unwrap_or(self.home.is_none())
188 }
189
190 /// Returns whether the key store is disabled.
191 fn no_key_store(&self) -> bool {
192 self.key_store_path.as_ref()
193 .map(|s| s.is_none())
194 .unwrap_or(self.home.is_none())
195 }
196
197 /// Returns the cert store's base directory, if it is enabled.
198 pub fn cert_store_base(&self) -> Option<PathBuf> {
199 let default = || if let Ok(path) = std::env::var("PGP_CERT_D") {
200 Some(PathBuf::from(path))
201 } else {
202 self.home.as_ref()
203 .map(|h| h.data_dir(sequoia_directories::Component::CertD))
204 };
205
206 if let Some(state) = self.cert_store_path.as_ref() {
207 match state {
208 StateDirectory::Absolute(p) => Some(p.clone()),
209 StateDirectory::Default => default(),
210 StateDirectory::None => None,
211 }
212 } else {
213 default()
214 }
215 }
216
217 /// Returns the cert store.
218 ///
219 /// If the cert store is disabled, returns `Ok(None)`. If it is not yet
220 /// open, opens it.
221 pub fn cert_store(&self) -> Result<Option<&WotStore<'store, 'rstore>>> {
222 if self.no_rw_cert_store()
223 && self.keyrings.is_empty()
224 {
225 // The cert store is disabled.
226 return Ok(None);
227 }
228
229 if let Some(cert_store) = self.cert_store.get() {
230 // The cert store is already initialized, return it.
231 return Ok(Some(cert_store));
232 }
233
234 let create_dirs = |path: &Path| -> Result<()> {
235 use std::fs::DirBuilder;
236
237 let mut b = DirBuilder::new();
238 b.recursive(true);
239
240 // Create the parent with the normal umask.
241 if let Some(parent) = path.parent() {
242 // Note: since recursive is turned on, it is not an
243 // error if the directory exists, which is exactly
244 // what we want.
245 b.create(parent)
246 .with_context(|| {
247 format!("Creating the directory {:?}", parent)
248 })?;
249 }
250
251 // Create path with more restrictive permissions.
252 platform!{
253 unix => {
254 use std::os::unix::fs::DirBuilderExt;
255 b.mode(0o700);
256 },
257 windows => {
258 },
259 }
260
261 b.create(path)
262 .with_context(|| {
263 format!("Creating the directory {:?}", path)
264 })?;
265
266 Ok(())
267 };
268
269 // We need to initialize the cert store.
270 let mut cert_store = if ! self.no_rw_cert_store() {
271 // Open the cert-d.
272
273 let path = self.cert_store_base()
274 .expect("just checked that it is configured");
275
276 create_dirs(&path)
277 .and_then(|_| cert_store::CertStore::open(&path))
278 .with_context(|| {
279 format!("While opening the certificate store at {:?}",
280 &path)
281 })?
282 } else {
283 cert_store::CertStore::empty()
284 };
285
286 let keyring = cert_store::store::Certs::empty();
287 let mut tsks = BTreeMap::new();
288 let mut error = None;
289 for filename in self.keyrings.iter() {
290 let f = std::fs::File::open(filename)
291 .with_context(|| format!("Open {:?}", filename))?;
292 let parser = RawCertParser::from_reader(f)
293 .with_context(|| format!("Parsing {:?}", filename))?;
294
295 for cert in parser {
296 match cert {
297 Ok(cert) => {
298 for key in cert.keys() {
299 if key.has_secret() {
300 tsks.insert(
301 key.fingerprint(),
302 (cert.fingerprint(), key.clone()));
303 }
304 }
305
306 keyring.update(Arc::new(cert.into()))
307 .expect("implementation doesn't fail");
308 }
309 Err(err) => {
310 eprint!("Parsing certificate in {:?}: {}",
311 filename, err);
312 error = Some(err);
313 }
314 }
315 }
316 }
317
318 self.keyring_tsks.set(tsks).expect("uninitialized");
319
320 if let Some(err) = error {
321 return Err(err).context("Parsing keyrings");
322 }
323
324 cert_store.add_backend(
325 Box::new(keyring),
326 cert_store::AccessMode::Always);
327
328 // Sync certs from GnuPG's state if we are using the user's
329 // default home directory.
330 if self.home.as_ref().map(|h| h.is_default_location())
331 .unwrap_or(false)
332 && std::env::var("GNUPGHOME").is_err()
333 {
334 if let Err(e) = crate::compat::sync_from_gnupg(self, &cert_store) {
335 self.info(format_args!(
336 "Syncing state from GnuPG failed: {}", e));
337 }
338 }
339
340 let cert_store = WotStore::from_store(
341 cert_store, self.policy, self.time);
342
343 let _ = self.cert_store.set(cert_store);
344
345 Ok(Some(self.cert_store.get().expect("just configured")))
346 }
347
348 fn no_cert_store_err() -> clap::Error {
349 clap::Error::raw(clap::error::ErrorKind::ArgumentConflict,
350 "Operation requires a certificate store, \
351 but the certificate store is disabled")
352 }
353
354 /// Returns the cert store.
355 ///
356 /// If the cert store is disabled, returns an error.
357 pub fn cert_store_or_else(&self) -> Result<&WotStore<'store, 'rstore>> {
358 self.cert_store().and_then(|cert_store| cert_store.ok_or_else(|| {
359 Self::no_cert_store_err().into()
360 }))
361 }
362
363 /// Returns a mutable reference to the cert store.
364 ///
365 /// If the cert store is disabled, returns None. If it is not yet
366 /// open, opens it.
367 pub fn cert_store_mut(&mut self)
368 -> Result<Option<&mut WotStore<'store, 'rstore>>>
369 {
370 if self.no_rw_cert_store() {
371 return Err(Self::no_cert_store_err().into());
372 }
373
374 // self.cert_store() will do any required initialization, but
375 // it will return an immutable reference.
376 self.cert_store()?;
377 Ok(self.cert_store.get_mut())
378 }
379
380 /// Returns a mutable reference to the cert store.
381 ///
382 /// If the cert store is disabled, returns an error.
383 #[allow(unused)]
384 pub fn cert_store_mut_or_else(&mut self)
385 -> Result<&mut WotStore<'store, 'rstore>>
386 {
387 self.cert_store_mut().and_then(|cert_store| cert_store.ok_or_else(|| {
388 Self::no_cert_store_err().into()
389 }))
390 }
391
392 /// Returns a reference to the underlying certificate directory,
393 /// if it is configured.
394 ///
395 /// If the cert direcgory is disabled, returns an error.
396 pub fn certd_or_else(&self)
397 -> Result<&cert_store::store::certd::CertD<'store>>
398 {
399 const NO_CERTD_ERR: &str =
400 "A local trust root and other special certificates are \
401 only available when using an OpenPGP certificate \
402 directory";
403
404 let cert_store = self.cert_store_or_else()
405 .with_context(|| NO_CERTD_ERR.to_string())?;
406
407 cert_store.certd()
408 .ok_or_else(|| anyhow::anyhow!(NO_CERTD_ERR))
409 }
410
411
412 /// Returns a web-of-trust query builder.
413 ///
414 /// The trust roots are already set appropriately.
415 pub fn wot_query(&self)
416 -> Result<wot::NetworkBuilder<&WotStore<'store, 'rstore>>>
417 {
418 let cert_store = self.cert_store_or_else()?;
419 let network = wot::NetworkBuilder::rooted(cert_store,
420 &*self.trust_roots());
421 Ok(network)
422 }
423
424 /// Returns the key store's path.
425 ///
426 /// If the key store is disabled, returns `Ok(None)`.
427 pub fn key_store_path(&self) -> Result<Option<PathBuf>> {
428 let default = || {
429 Ok(self.home.as_ref()
430 .map(|h| h.data_dir(sequoia_directories::Component::Keystore)))
431 };
432
433 if let Some(dir) = self.key_store_path.as_ref() {
434 match dir {
435 StateDirectory::Absolute(p) => Ok(Some(p.clone())),
436 StateDirectory::Default => default(),
437 StateDirectory::None => Ok(None),
438 }
439 } else {
440 default()
441 }
442 }
443
444 fn no_key_store_err() -> clap::Error {
445 clap::Error::raw(clap::error::ErrorKind::ArgumentConflict,
446 "Operation requires a key store, \
447 but the key store is disabled")
448 }
449
450 /// Returns the key store's path.
451 ///
452 /// If the key store is disabled, returns an error.
453 pub fn key_store_path_or_else(&self) -> Result<PathBuf> {
454 if self.no_key_store() {
455 Err(Self::no_key_store_err().into())
456 } else {
457 self.key_store_path()?
458 .ok_or_else(|| {
459 Self::no_key_store_err().into()
460 })
461 }
462 }
463
464 /// Returns the key store.
465 ///
466 /// If the key store is disabled, returns `Ok(None)`. If it is not yet
467 /// open, opens it.
468 pub fn key_store(&self) -> Result<Option<&Mutex<keystore::Keystore>>> {
469 if self.no_key_store() {
470 return Ok(None);
471 }
472
473 self.key_store
474 .get_or_try_init(|| {
475 let mut c = keystore::Context::configure()
476 .home(self.key_store_path_or_else()?);
477
478 if let Some(p) = self.config.servers_path() {
479 c = c.lib(p);
480 }
481
482 let c = c.build()?;
483 let ks = keystore::Keystore::connect(&c)
484 .context("Connecting to key store")?;
485
486 Ok(Mutex::new(ks))
487 })
488 .map(Some)
489 }
490
491 /// Returns the key store.
492 ///
493 /// If the key store is disabled, returns an error.
494 pub fn key_store_or_else(&self) -> Result<&Mutex<keystore::Keystore>> {
495 self.key_store().and_then(|key_store| key_store.ok_or_else(|| {
496 Self::no_key_store_err().into()
497 }))
498 }
499
500 /// Returns the secret keys found in any specified keyrings.
501 pub fn keyring_tsks(&self)
502 -> Result<&BTreeMap<Fingerprint,
503 (Fingerprint, Key<key::PublicParts, key::UnspecifiedRole>)>>
504 {
505 if let Some(keyring_tsks) = self.keyring_tsks.get() {
506 Ok(keyring_tsks)
507 } else {
508 // This also initializes keyring_tsks.
509 self.cert_store()?;
510
511 // If something went wrong, we just set it to an empty
512 // map.
513 Ok(self.keyring_tsks.get_or_init(|| BTreeMap::new()))
514 }
515 }
516
517 /// Looks up an identifier.
518 ///
519 /// This matches on both the primary key and the subkeys.
520 ///
521 /// If `keyflags` is not `None`, then only returns certificates
522 /// where the matching key has at least one of the specified key
523 /// flags. If `or_by_primary` is set, then certificates with the
524 /// specified key handle and a subkey with the specified flags
525 /// also match.
526 ///
527 /// If `allow_ambiguous` is true, then all matching certificates
528 /// are returned. Otherwise, if an identifier matches multiple
529 /// certificates an error is returned.
530 ///
531 /// An error is also returned if any of the identifiers does not
532 /// match at least one certificate.
533 pub fn lookup<'a, I>(&self, handles: I,
534 keyflags: Option<KeyFlags>,
535 or_by_primary: bool,
536 allow_ambiguous: bool)
537 -> Result<Vec<Cert>>
538 where I: IntoIterator,
539 I::Item: Into<FileStdinOrKeyHandle>,
540 {
541 self.lookup_with_policy(
542 handles, keyflags, or_by_primary, allow_ambiguous,
543 self.policy, self.time)
544 }
545
546 /// Looks up an identifier.
547 ///
548 /// Like [`Sq::lookup`], but uses an alternate policy and an
549 /// alternate reference time.
550 pub fn lookup_with_policy<'a, I>(&self, handles: I,
551 keyflags: Option<KeyFlags>,
552 or_by_primary: bool,
553 allow_ambiguous: bool,
554 policy: &dyn Policy,
555 time: SystemTime)
556 -> Result<Vec<Cert>>
557 where I: IntoIterator,
558 I::Item: Into<FileStdinOrKeyHandle>,
559 {
560 let mut results = Vec::new();
561
562 for handle in handles {
563 let (kh, mut certs) = match handle.into() {
564 FileStdinOrKeyHandle::FileOrStdin(file) => {
565 let br = file.open("an OpenPGP certificate")?;
566 let cert = Cert::from_buffered_reader(br)?;
567 (cert.key_handle(), vec![ cert ])
568 }
569 FileStdinOrKeyHandle::KeyHandle(kh) => {
570 let certs = self.cert_store_or_else()?
571 .lookup_by_cert_or_subkey(&kh)
572 .with_context(|| {
573 format!("Failed to load {} from certificate store", kh)
574 })?
575 .into_iter()
576 .filter_map(|cert| {
577 match cert.to_cert() {
578 Ok(cert) => Some(cert.clone()),
579 Err(err) => {
580 let err = err.context(
581 format!("Failed to parse {} as loaded \
582 from certificate store", kh));
583 print_error_chain(&err);
584 None
585 }
586 }
587 })
588 .collect::<Vec<Cert>>();
589
590 (kh.clone(), certs)
591 }
592 };
593
594 if let Some(keyflags) = keyflags.as_ref() {
595 certs.retain(|cert| {
596 let vc = match cert.with_policy(policy, time)
597 {
598 Ok(vc) => vc,
599 Err(err) => {
600 let err = err.context(
601 format!("{} is not valid according \
602 to the current policy, ignoring",
603 kh));
604 print_error_chain(&err);
605 return false;
606 }
607 };
608
609 let checked_id = or_by_primary
610 && vc.cert().key_handle().aliases(&kh);
611
612 for ka in vc.keys() {
613 if checked_id || ka.key().key_handle().aliases(&kh) {
614 if &ka.key_flags().unwrap_or(KeyFlags::empty())
615 & keyflags
616 != KeyFlags::empty()
617 {
618 return true;
619 }
620 }
621 }
622
623 if checked_id {
624 weprintln!("Error: {} does not have a key with \
625 the required capabilities ({:?})",
626 cert.keyid(), keyflags);
627 } else {
628 weprintln!("Error: The subkey {} (cert: {}) \
629 does not have the required capabilities \
630 ({:?})",
631 kh, cert.keyid(), keyflags);
632 }
633 return false;
634 })
635 }
636
637 if ! allow_ambiguous && certs.len() > 1 {
638 return Err(anyhow::anyhow!(
639 "{} is ambiguous; it matches: {}",
640 kh,
641 certs.into_iter()
642 .map(|cert| cert.fingerprint().to_string())
643 .collect::<Vec<String>>()
644 .join(", ")));
645 }
646
647 if certs.len() == 0 {
648 return Err(StoreError::NotFound(kh.clone()).into());
649 }
650
651 results.extend(certs);
652 }
653
654 Ok(results)
655 }
656
657 /// Looks up a certificate.
658 ///
659 /// Like [`Sq::lookup`], but looks up a certificate, which must be
660 /// uniquely identified by `handle` and `keyflags`.
661 pub fn lookup_one<H>(&self, handle: H,
662 keyflags: Option<KeyFlags>, or_by_primary: bool)
663 -> Result<Cert>
664 where H: Into<FileStdinOrKeyHandle>
665 {
666 self.lookup_one_with_policy(handle, keyflags, or_by_primary,
667 self.policy, self.time)
668 }
669
670 /// Looks up a certificate.
671 ///
672 /// Like [`Sq::lookup_one_with_policy`], but uses an alternate
673 /// policy and an alternate reference time.
674 pub fn lookup_one_with_policy<H>(&self, handle: H,
675 keyflags: Option<KeyFlags>,
676 or_by_primary: bool,
677 policy: &dyn Policy,
678 time: SystemTime)
679 -> Result<Cert>
680 where H: Into<FileStdinOrKeyHandle>
681 {
682 self.lookup_with_policy(std::iter::once(handle.into()),
683 keyflags, or_by_primary, false,
684 policy, time)
685 .map(|certs| {
686 assert_eq!(certs.len(), 1);
687 certs.into_iter().next().expect("have one")
688 })
689 }
690
691
692 /// Looks up certificates by User ID or email address.
693 ///
694 /// This only returns certificates that can be authenticate for
695 /// the specified User ID (or email address, if `email` is true).
696 /// If no certificate can be authenticated for some User ID,
697 /// returns an error. If multiple certificates can be
698 /// authenticated for a given User ID or email address, then
699 /// returns them all.
700 pub fn lookup_by_userid(&self, userid: &[String], email: bool)
701 -> Result<Vec<Cert>>
702 {
703 if userid.is_empty() {
704 return Ok(Vec::new())
705 }
706
707 let cert_store = self.cert_store_or_else()?;
708
709 // Build a WoT network.
710
711 let cert_store = wot::store::CertStore::from_store(
712 cert_store, self.policy, self.time);
713 let n = wot::NetworkBuilder::rooted(&cert_store, &*self.trust_roots())
714 .build();
715
716 let mut results: Vec<Cert> = Vec::new();
717 // We try hard to not just stop at the first error, but lint
718 // the input so that the user gets as much feedback as
719 // possible. The first error that we encounter is saved here,
720 // and returned. The rest are printed directly.
721 let mut error: Option<anyhow::Error> = None;
722
723 // Iterate over each User ID address, find any certificates
724 // associated with the User ID, validate the certificates, and
725 // finally authenticate them for the User ID.
726 for userid in userid.iter() {
727 let matches: Vec<(Fingerprint, UserID)> = if email {
728 if let Err(err) = UserIDQueryParams::is_email(userid) {
729 weprintln!("{:?} is not a valid email address", userid);
730 if error.is_none() {
731 error = Some(err);
732 }
733
734 continue;
735 }
736
737 // Get all certificates that are associated with the email
738 // address.
739 cert_store.lookup_synopses_by_email(userid)
740 } else {
741 let userid = UserID::from(&userid[..]);
742 cert_store.lookup_synopses_by_userid(userid.clone())
743 .into_iter()
744 .map(|fpr| (fpr, userid.clone()))
745 .collect()
746 };
747
748 if matches.is_empty() {
749 return Err(anyhow::anyhow!(
750 "No certificates are associated with {:?}",
751 userid));
752 }
753
754 struct Entry {
755 fpr: Fingerprint,
756 userid: UserID,
757 cert: Result<Cert>,
758 }
759 let entries = matches.into_iter().map(|(fpr, userid)| {
760 // We've got a match, or two, or three... Lookup the certs.
761 let cert = match cert_store.lookup_by_cert_fpr(&fpr) {
762 Ok(cert) => cert,
763 Err(err) => {
764 let err = err.context(format!(
765 "Error fetching {} ({})",
766 fpr, ui::Safe(&userid)));
767 return Entry { fpr, userid, cert: Err(err), };
768 }
769 };
770
771 // Parse the LazyCerts.
772 let cert = match cert.to_cert() {
773 Ok(cert) => cert.clone(),
774 Err(err) => {
775 let err = err.context(format!(
776 "Error parsing {} ({})",
777 fpr, ui::Safe(&userid)));
778 return Entry { fpr, userid, cert: Err(err), };
779 }
780 };
781
782 // Check the certs for validity.
783 let vc = match cert.with_policy(self.policy, self.time) {
784 Ok(vc) => vc,
785 Err(err) => {
786 let err = err.context(format!(
787 "Certificate {} ({}) is invalid",
788 fpr, ui::Safe(&userid)));
789 return Entry { fpr, userid, cert: Err(err) };
790 }
791 };
792
793 if let Err(err) = vc.alive() {
794 let err = err.context(format!(
795 "Certificate {} ({}) is invalid",
796 fpr, ui::Safe(&userid)));
797 return Entry { fpr, userid, cert: Err(err), };
798 }
799
800 if let RevocationStatus::Revoked(_) = vc.revocation_status() {
801 let err = anyhow::anyhow!(
802 "Certificate {} ({}) is revoked",
803 fpr, ui::Safe(&userid));
804 return Entry { fpr, userid, cert: Err(err), };
805 }
806
807 if let Some(ua) = vc.userids().find(|ua| {
808 ua.userid() == &userid
809 })
810 {
811 if let RevocationStatus::Revoked(_) = ua.revocation_status() {
812 let err = anyhow::anyhow!(
813 "User ID {} on certificate {} is revoked",
814 ui::Safe(&userid), fpr);
815 return Entry { fpr, userid, cert: Err(err), };
816 }
817 }
818
819 // Authenticate the bindings.
820 let paths = n.authenticate(
821 &userid, cert.fingerprint(),
822 // XXX: Make this user configurable.
823 wot::FULLY_TRUSTED);
824 let r = if paths.amount() < wot::FULLY_TRUSTED {
825 Err(anyhow::anyhow!(
826 "{}, {} cannot be authenticated at the \
827 required level ({} of {}). After checking \
828 that {} really controls {}, you could certify \
829 their certificate by running \
830 `sq pki link add --cert {} --userid {:?}`.",
831 cert.fingerprint(),
832 ui::Safe(&userid),
833 paths.amount(), wot::FULLY_TRUSTED,
834 ui::Safe(&userid),
835 cert.fingerprint(),
836 cert.fingerprint(),
837 String::from_utf8_lossy(userid.value())))
838 } else {
839 Ok(cert)
840 };
841
842 Entry { fpr, userid, cert: r, }
843 });
844
845 // Partition into good (successfully authenticated) and
846 // bad (an error occurred).
847 let (good, bad): (Vec<Entry>, _)
848 = entries.partition(|entry| entry.cert.is_ok());
849
850 if good.is_empty() {
851 // We've only got errors.
852
853 let err = if bad.is_empty() {
854 // We got nothing :/.
855 if email {
856 anyhow::anyhow!(
857 "No known certificates have the email address {}",
858 ui::Safe(userid))
859 } else {
860 anyhow::anyhow!(
861 "No known certificates have the User ID {}",
862 ui::Safe(userid))
863 }
864 } else {
865 if email {
866 anyhow::anyhow!(
867 "None of the certificates with the email \
868 address {} can be authenticated using \
869 the configured trust model",
870 ui::Safe(userid))
871 } else {
872 anyhow::anyhow!(
873 "None of the certificates with the User ID \
874 {} can be authenticated using \
875 the configured trust model",
876 ui::Safe(userid))
877 }
878 };
879
880 weprintln!("{:?}:\n", err);
881 if error.is_none() {
882 error = Some(err);
883 }
884
885 // Print the errors.
886 for (i, Entry { fpr, userid, cert }) in bad.into_iter().enumerate() {
887 weprintln!("{}. When considering {} ({}):",
888 i + 1, fpr,
889 ui::Safe(&userid));
890 let err = match cert {
891 Ok(_) => unreachable!(),
892 Err(err) => err,
893 };
894
895 print_error_chain(&err);
896 }
897 } else {
898 // We have at least one authenticated certificate.
899 // Silently ignore any errors.
900 results.extend(
901 good.into_iter().filter_map(|Entry { cert, .. }| {
902 cert.ok()
903 }));
904 }
905 }
906
907 if let Some(error) = error {
908 Err(error)
909 } else {
910 Ok(results)
911 }
912 }
913
914 /// Returns the local trust root, creating it if necessary.
915 pub fn local_trust_root(&self) -> Result<Arc<LazyCert<'store>>> {
916 self.certd_or_else()?.trust_root().map(|(cert, _created)| {
917 cert
918 })
919 }
920
921 /// Returns the trust roots, including the cert store's trust
922 /// root, if any.
923 pub fn trust_roots(&self) -> Vec<Fingerprint> {
924 let trust_root_local = self.trust_root_local.get_or_init(|| {
925 self.cert_store_or_else()
926 .ok()
927 .and_then(|cert_store| cert_store.certd())
928 .and_then(|certd| {
929 match certd.certd().get(cert_store::store::openpgp_cert_d::TRUST_ROOT) {
930 Ok(Some((_tag, cert_bytes))) => Some(cert_bytes),
931 // Not found.
932 Ok(None) => None,
933 Err(err) => {
934 weprintln!("Error looking up local trust root: {}",
935 err);
936 None
937 }
938 }
939 })
940 .and_then(|cert_bytes| {
941 match RawCertParser::from_bytes(&cert_bytes[..]) {
942 Ok(mut parser) => {
943 match parser.next() {
944 Some(Ok(cert)) => Some(cert.fingerprint()),
945 Some(Err(err)) => {
946 weprintln!("Local trust root is \
947 corrupted: {}",
948 err);
949 None
950 }
951 None => {
952 weprintln!("Local trust root is \
953 corrupted: no data");
954 None
955 }
956 }
957 }
958 Err(err) => {
959 weprintln!("Error parsing local trust root: {}",
960 err);
961 None
962 }
963 }
964 })
965 });
966
967 if let Some(trust_root_local) = trust_root_local {
968 self.trust_roots.iter().cloned()
969 .chain(std::iter::once(trust_root_local.clone()))
970 .collect()
971 } else {
972 self.trust_roots.clone()
973 }
974 }
975
976 /// Imports the TSK into the soft key backend.
977 ///
978 /// On success, returns whether the key was imported, updated, or
979 /// unchanged and whether the cert was imported, updated, or
980 /// unchanged.
981 pub fn import_key(&self, cert: Cert, stats: &mut ImportStats)
982 -> Result<(ImportStatus, ImportStatus)>
983 {
984 if ! cert.is_tsk() {
985 return Err(anyhow::anyhow!(
986 "Nothing to import: certificate does not contain \
987 any secret key material"));
988 }
989
990 let keystore = self.key_store_or_else()?;
991 let mut keystore = keystore.lock().unwrap();
992
993 let mut softkeys = None;
994 for mut backend in keystore.backends()?.into_iter() {
995 if backend.id()? == "softkeys" {
996 softkeys = Some(backend);
997 break;
998 }
999 }
1000
1001 drop(keystore);
1002
1003 let mut softkeys = if let Some(softkeys) = softkeys {
1004 softkeys
1005 } else {
1006 return Err(anyhow::anyhow!("softkeys backend is not configured."));
1007 };
1008
1009 let mut key_import_status = ImportStatus::Unchanged;
1010 for (s, key) in softkeys.import(&cert)
1011 .map_err(|e| {
1012 stats.keys.errors += 1;
1013 e
1014 })?
1015 {
1016 self.info(format_args!(
1017 "Importing {} into key store: {:?}",
1018 key.fingerprint(), s));
1019
1020 key_import_status = key_import_status.max(s.into());
1021 }
1022
1023 match key_import_status {
1024 ImportStatus::New => stats.keys.new += 1,
1025 ImportStatus::Unchanged => stats.keys.unchanged += 1,
1026 ImportStatus::Updated => stats.keys.updated += 1,
1027 }
1028
1029 // Also insert the certificate into the certificate store.
1030 // If we can't, we don't fail. This allows, in
1031 // particular, `sq --cert-store=none key import` to work.
1032 let cert = cert.strip_secret_key_material();
1033 let fpr = cert.fingerprint();
1034 let mut cert_import_status = ImportStatus::Unchanged;
1035 match self.cert_store_or_else() {
1036 Ok(cert_store) => {
1037 let new_certs = stats.certs.new_certs();
1038 let updated_certs = stats.certs.updated_certs();
1039
1040 if let Err(err) = cert_store.update_by(
1041 Arc::new(LazyCert::from(cert)), stats)
1042 {
1043 self.info(format_args!(
1044 "While importing {} into cert store: {}",
1045 fpr, err));
1046 }
1047
1048 if stats.certs.new_certs() > new_certs {
1049 cert_import_status = ImportStatus::New;
1050 } else if stats.certs.updated_certs() > updated_certs {
1051 cert_import_status = ImportStatus::Updated;
1052 }
1053 }
1054 Err(err) => {
1055 self.info(format_args!(
1056 "Not importing {} into cert store: {}",
1057 fpr, err));
1058 }
1059 }
1060
1061 Ok((key_import_status, cert_import_status))
1062 }
1063
1064 /// Imports the certificate into the certificate store.
1065 ///
1066 /// On success, returns whether the key was imported, updated, or
1067 /// unchanged.
1068 pub fn import_cert(&self, cert: Cert) -> Result<ImportStatus> {
1069 let fpr = cert.fingerprint();
1070 let cert_store = self.cert_store_or_else()?;
1071
1072 let stats = MergePublicCollectStats::new();
1073 cert_store.update_by(Arc::new(LazyCert::from(cert)), &stats)
1074 .with_context(|| {
1075 format!("Failed to import {} into the certificate store",
1076 fpr)
1077 })?;
1078
1079 let import_status = if stats.new_certs() > 0 {
1080 ImportStatus::New
1081 } else if stats.updated_certs() > 0 {
1082 ImportStatus::Updated
1083 } else {
1084 ImportStatus::Unchanged
1085 };
1086
1087 Ok(import_status)
1088 }
1089
1090 /// Best-effort heuristic to compute the primary User ID of a given cert.
1091 ///
1092 /// The returned string is already sanitized, and safe for displaying.
1093 ///
1094 /// If `use_wot` is set, then we use the best authenticated user
1095 /// ID. If `use_wot` is not set, then we use the primary user ID.
1096 pub fn best_userid<'u>(&self, cert: &'u Cert, use_wot: bool)
1097 -> PreferredUserID
1098 {
1099 // Try to be more helpful by including a User ID in the
1100 // listing. We'd like it to be the primary one. Use
1101 // decreasingly strict policies.
1102 let mut primary_uid = None;
1103
1104 // First, apply our policy.
1105 if let Ok(vcert) = cert.with_policy(self.policy, self.time) {
1106 if let Ok(primary) = vcert.primary_userid() {
1107 primary_uid = Some(primary.userid());
1108 }
1109 }
1110
1111 // Second, apply the null policy.
1112 if primary_uid.is_none() {
1113 if let Ok(vcert) = cert.with_policy(&NULL_POLICY, self.time) {
1114 if let Ok(primary) = vcert.primary_userid() {
1115 primary_uid = Some(primary.userid());
1116 }
1117 }
1118 }
1119
1120 // As a last resort, pick the first user id.
1121 if primary_uid.is_none() {
1122 if let Some(primary) = cert.userids().next() {
1123 primary_uid = Some(primary.userid());
1124 }
1125 }
1126
1127 if let Some(primary_uid) = primary_uid {
1128 let fpr = cert.fingerprint();
1129
1130 let mut candidate: (&UserID, usize) = (primary_uid, 0);
1131
1132 #[allow(clippy::never_loop)]
1133 loop {
1134 // Don't fail if we can't query the user's web of trust.
1135 if ! use_wot { break; };
1136 let Ok(q) = self.wot_query() else { break; };
1137 let q = q.build();
1138 let authenticate = move |userid: &UserID| {
1139 let paths = q.authenticate(userid, &fpr, wot::FULLY_TRUSTED);
1140 paths.amount()
1141 };
1142
1143 // We're careful to *not* use a ValidCert so that we see all
1144 // user IDs, even those that are not self signed.
1145
1146 candidate = (primary_uid, authenticate(primary_uid));
1147
1148 for userid in cert.userids() {
1149 let userid = userid.component();
1150
1151 if candidate.1 >= wot::FULLY_TRUSTED {
1152 // Done.
1153 break;
1154 }
1155
1156 if userid == primary_uid {
1157 // We already considered this one.
1158 continue;
1159 }
1160
1161 let amount = authenticate(&userid);
1162 if amount > candidate.1 {
1163 candidate = (userid, amount);
1164 }
1165 }
1166
1167 break;
1168 }
1169
1170 let (uid, amount) = candidate;
1171 PreferredUserID::from_userid(uid.clone(), amount)
1172 } else {
1173 // Special case, there is no user id.
1174 PreferredUserID::unknown()
1175 }
1176 }
1177
1178 /// Best-effort heuristic to compute the primary User ID of a given cert.
1179 ///
1180 /// The returned string is already sanitized, and safe for displaying.
1181 ///
1182 /// If `use_wot` is set, then we use the best authenticated user
1183 /// ID. If `use_wot` is not set, then we use the primary user ID.
1184 pub fn best_userid_for<'u, F>(&self,
1185 key_handle: &KeyHandle,
1186 keyflags: F,
1187 use_wot: bool)
1188 -> (PreferredUserID, Result<Cert>)
1189 where
1190 F: Into<Option<KeyFlags>>,
1191 {
1192 let certs = self.lookup(std::iter::once(key_handle),
1193 keyflags.into(), false, true);
1194
1195 match certs {
1196 Ok(certs) => {
1197 assert!(! certs.is_empty());
1198
1199 // Compute the best user ID and the associated trust
1200 // amount for each cert.
1201 let mut certs = certs.into_iter().map(|c| {
1202 (self.best_userid(&c, use_wot), c)
1203 }).collect::<Vec<_>>();
1204
1205 // Sort by trust amount, then fingerprint. This way,
1206 // if two certs have the same trust amount, at least
1207 // the result will be stable.
1208 certs.sort_by_key(
1209 |(puid, cert)| (puid.trust_amount(), cert.fingerprint()));
1210
1211 // Then pick the one with the highest trust amount.
1212 let best =
1213 certs.into_iter().rev().next().expect("at least one");
1214 (best.0, Ok(best.1))
1215 }
1216 Err(err) => {
1217 if let Some(StoreError::NotFound(_))
1218 = err.downcast_ref()
1219 {
1220 (PreferredUserID::from_string("(certificate not found)", 0),
1221 Err(err))
1222 } else {
1223 (PreferredUserID::from_string(
1224 format!("(error looking up certificate: {})", err), 0),
1225 Err(err))
1226 }
1227 }
1228 }
1229 }
1230
1231 /// Caches a password.
1232 pub fn cache_password(&self, password: Password) {
1233 let mut cache = self.password_cache.lock().unwrap();
1234
1235 if ! cache.contains(&password) {
1236 cache.push(password);
1237 }
1238 }
1239
1240 /// Returns the cached passwords.
1241 pub fn cached_passwords(&self) -> impl Iterator<Item=Password> {
1242 self.password_cache.lock().unwrap().clone().into_iter()
1243 }
1244
1245 /// Decrypts a key, if possible.
1246 ///
1247 /// If the key is not decrypted, this just returns the key as is.
1248 /// Otherwise, the password cache is tried. If the key can't be
1249 /// decrypted using those passwords and `may_prompt` is true, the
1250 /// user is prompted. If a valid password is entered, it is added
1251 /// to the password cache.
1252 ///
1253 /// If `allow_skipping` is true, then the user is given the option
1254 /// to skip decrypting the key. If the user skips decrypting the
1255 /// key, then an error is returned.
1256 pub fn decrypt_key<R>(&self, cert: Option<&Cert>,
1257 key: Key<key::SecretParts, R>,
1258 may_prompt: bool,
1259 allow_skipping: bool)
1260 -> Result<Key<key::SecretParts, R>>
1261 where R: key::KeyRole + Clone
1262 {
1263 match key.secret() {
1264 SecretKeyMaterial::Unencrypted(_) => {
1265 Ok(key)
1266 }
1267 SecretKeyMaterial::Encrypted(e) => {
1268 if ! e.s2k().is_supported() {
1269 return Err(anyhow::anyhow!(
1270 "Unsupported key protection mechanism"));
1271 }
1272
1273 for p in self.password_cache.lock().unwrap().iter() {
1274 if let Ok(unencrypted) = e.decrypt(&key, &p) {
1275 let (key, _) = key.add_secret(unencrypted.into());
1276 return Ok(key);
1277 }
1278 }
1279
1280 let prompt = if let Some(cert) = cert {
1281 format!("{}/{} {}",
1282 cert.keyid(), key.keyid(),
1283 self.best_userid(cert, true).display())
1284 } else {
1285 format!("{}", key.keyid())
1286 };
1287
1288 if ! may_prompt {
1289 return Err(anyhow::anyhow!(
1290 "Unable to decrypt secret key material for {}", prompt))
1291 }
1292
1293 loop {
1294 // Prompt the user.
1295 let result = if allow_skipping {
1296 password::prompt_to_unlock_or_cancel(self, &prompt)
1297 } else {
1298 password::prompt_to_unlock(self, &prompt).map(Some)
1299 };
1300 match result {
1301 Ok(None) => break, // Give up.
1302 Ok(Some(p)) => {
1303 if let Ok(unencrypted) = e.decrypt(&key, &p) {
1304 let (key, _) = key.add_secret(unencrypted.into());
1305 self.password_cache.lock().unwrap().push(p);
1306 return Ok(key);
1307 }
1308
1309 weprintln!("Incorrect password.");
1310 }
1311 Err(err) => {
1312 weprintln!("While reading password: {}", err);
1313 break;
1314 }
1315 }
1316 }
1317
1318 Err(anyhow::anyhow!("Key {}: Unable to decrypt secret key material",
1319 key.keyid().to_hex()))
1320 }
1321 }
1322 }
1323
1324 /// Checks whether we have a secret key.
1325 pub fn have_secret_key<P, R, R2>(&self, ka: &KeyAmalgamation<P, R, R2>)
1326 -> bool
1327 where
1328 P: key::KeyParts + Clone,
1329 R: key::KeyRole + Clone
1330 {
1331 let try_tsk = |_: &Cert, key: &Key<_, _>|
1332 -> Result<_>
1333 {
1334 key.parts_as_secret()?;
1335 Ok(())
1336 };
1337 let try_keyrings = |cert: &Cert, key: &Key<_, _>|
1338 -> Result<_>
1339 {
1340 let keyring_tsks = self.keyring_tsks()?;
1341 if let Some((cert_fpr, key))
1342 = keyring_tsks.get(&key.fingerprint())
1343 {
1344 if cert_fpr == &cert.fingerprint() {
1345 return try_tsk(cert, key);
1346 }
1347 }
1348
1349 Err(anyhow!("no secret key material"))
1350 };
1351 let try_keystore = |ka: &KeyAmalgamation<_, _, R2>|
1352 -> Result<_>
1353 {
1354 let ks = self.key_store_or_else()?;
1355 let mut ks = ks.lock().unwrap();
1356 if ks.find_key(ka.key().key_handle())?.is_empty() {
1357 Err(anyhow!("no secret key material in the store"))
1358 } else {
1359 Ok(())
1360 }
1361 };
1362
1363 let key = ka.key().parts_as_public().role_as_unspecified();
1364 try_tsk(ka.cert(), key)
1365 .or_else(|_| try_keyrings(ka.cert(), key))
1366 .or_else(|_| try_keystore(ka))
1367 .is_ok()
1368 }
1369
1370 /// Gets a signer for the specified key.
1371 ///
1372 /// If `ka` includes secret key material, that is preferred.
1373 /// Otherwise, we look for the key on the key store.
1374 ///
1375 /// If the key is locked, we try to unlock it. If the key isn't
1376 /// protected by a retry counter, then the password cache is
1377 /// tried. Otherwise, or if that fails, the user is prompted to
1378 /// unlock the key. The correct password is added to the password
1379 /// cache.
1380 pub fn get_signer<P, R, R2>(&self, ka: &KeyAmalgamation<P, R, R2>)
1381 -> Result<Box<dyn crypto::Signer + Send + Sync>>
1382 where P: key::KeyParts + Clone, R: key::KeyRole + Clone
1383 {
1384 let try_tsk = |cert: &Cert, key: &Key<_, _>|
1385 -> Result<_>
1386 {
1387 if let Ok(key) = key.parts_as_secret() {
1388 let key = self.decrypt_key(
1389 Some(cert), key.clone(), true, false)?;
1390 let keypair = Box::new(key.into_keypair()
1391 .expect("decrypted secret key material"));
1392 Ok(keypair)
1393 } else {
1394 Err(anyhow!("No secret key material."))
1395 }
1396 };
1397 let try_keyrings = |cert: &Cert, key: &Key<_, _>|
1398 -> Result<_>
1399 {
1400 let keyring_tsks = self.keyring_tsks()?;
1401 if let Some((cert_fpr, key))
1402 = keyring_tsks.get(&key.fingerprint())
1403 {
1404 if cert_fpr == &cert.fingerprint() {
1405 return try_tsk(cert, key);
1406 }
1407 }
1408
1409 Err(anyhow!("No secret key material."))
1410 };
1411 let try_keystore = |ka: &KeyAmalgamation<_, _, R2>|
1412 -> Result<_>
1413 {
1414 let ks = self.key_store_or_else()?;
1415
1416 let mut ks = ks.lock().unwrap();
1417
1418 let remote_keys = ks.find_key(ka.key().key_handle())?;
1419
1420 let uid = self.best_userid(ka.cert(), true);
1421
1422 // XXX: Be a bit smarter. If there are multiple
1423 // keys, sort them so that we try the easiest one
1424 // first (available, no password).
1425
1426 'key: for mut key in remote_keys.into_iter() {
1427 if let Protection::Password(hint) = key.locked()? {
1428 if self.cached_passwords()
1429 .find(|password| {
1430 key.unlock(password.clone()).is_ok()
1431 })
1432 .is_none()
1433 {
1434 if let Some(hint) = hint {
1435 weprintln!("{}", hint);
1436 }
1437
1438 loop {
1439 let p = password::prompt_to_unlock(self, &format!(
1440 "{}/{}, {}",
1441 ka.cert().keyid(), ka.key().keyid(),
1442 uid.display()))?;
1443
1444 if p == "".into() {
1445 weprintln!("Giving up.");
1446 continue 'key;
1447 }
1448
1449 match key.unlock(p.clone()) {
1450 Ok(()) => {
1451 self.cache_password(p.clone());
1452 break;
1453 }
1454 Err(err) => {
1455 weprintln!("Failed to unlock key: {}", err);
1456 }
1457 }
1458 }
1459 }
1460 }
1461
1462 return Ok(Box::new(key));
1463 }
1464
1465 Err(anyhow!("Key not managed by keystore."))
1466 };
1467
1468 let key = ka.key().parts_as_public().role_as_unspecified();
1469
1470 if let Ok(key) = try_tsk(ka.cert(), key) {
1471 Ok(key)
1472 } else if let Ok(key) = try_keyrings(ka.cert(), key) {
1473 Ok(key)
1474 } else if let Ok(key) = try_keystore(ka) {
1475 Ok(key)
1476 } else {
1477 Err(anyhow!("No secret key material."))
1478 }
1479 }
1480
1481 /// Returns a signer for each certificate.
1482 ///
1483 /// This returns one key for each certificate. If a certificate
1484 /// doesn't have a suitable key, then this returns an error.
1485 ///
1486 /// A key is considered suitable if:
1487 ///
1488 /// - the certificate is valid
1489 /// - the key matches the key type specified in `keytype` (it's either
1490 /// the primary, or it has one of the key capabilities)
1491 /// - the key is alive (unless allowed by `options`)
1492 /// - the key is not revoked (unless allowed by `options`)
1493 /// - the key's algorithm is supported by the underlying crypto engine.
1494 ///
1495 /// If a key is locked, then the user will be prompted to enter
1496 /// the password.
1497 fn get_keys<C>(&self, certs: &[C],
1498 keytype: KeyType,
1499 options: Option<&[GetKeysOptions]>)
1500 -> Result<Vec<(Cert, Box<dyn crypto::Signer + Send + Sync>)>>
1501 where C: Borrow<Cert>
1502 {
1503 let mut bad = Vec::new();
1504
1505 let options = options.unwrap_or(&[][..]);
1506 let allow_not_alive = options.contains(&GetKeysOptions::AllowNotAlive);
1507 let allow_revoked = options.contains(&GetKeysOptions::AllowRevoked);
1508 let null_policy = options.contains(&GetKeysOptions::NullPolicy);
1509
1510 let policy = if null_policy {
1511 &NULL_POLICY as &dyn Policy
1512 } else {
1513 self.policy as &dyn Policy
1514 };
1515
1516 let mut keys = vec![];
1517
1518 'next_cert: for cert in certs {
1519 let cert = cert.borrow();
1520 let vc = match cert.with_policy(policy, self.time) {
1521 Ok(vc) => vc,
1522 Err(err) => {
1523 return Err(
1524 err.context(format!("Found no suitable key on {}", cert)));
1525 }
1526 };
1527
1528 let keyiter = match keytype {
1529 KeyType::Primary => {
1530 Box::new(
1531 std::iter::once(
1532 vc.keys()
1533 .next()
1534 .expect("a valid cert has a primary key")))
1535 as Box<dyn Iterator<Item=ValidErasedKeyAmalgamation<openpgp::packet::key::PublicParts>>>
1536 },
1537 KeyType::KeyFlags(ref flags) => {
1538 Box::new(vc.keys().key_flags(flags.clone()))
1539 as Box<dyn Iterator<Item=_>>
1540 },
1541 };
1542 for ka in keyiter {
1543 let mut bad_ = [
1544 ! allow_not_alive && matches!(ka.alive(), Err(_)),
1545 ! allow_revoked && matches!(ka.revocation_status(),
1546 RevocationStatus::Revoked(_)),
1547 ! ka.key().pk_algo().is_supported(),
1548 false,
1549 ];
1550 if bad_.iter().any(|x| *x) {
1551 bad.push((ka.key().fingerprint(), bad_));
1552 continue;
1553 }
1554
1555 if let Ok(key) = self.get_signer(ka.amalgamation()) {
1556 keys.push((cert.clone(), key));
1557 continue 'next_cert;
1558 } else {
1559 bad_[3] = true;
1560 bad.push((ka.key().fingerprint(), bad_));
1561 continue;
1562 }
1563 }
1564
1565 // We didn't get a key. Lint the cert.
1566
1567 let time = chrono::DateTime::<chrono::offset::Utc>::from(self.time);
1568
1569 let mut context = Vec::new();
1570 for (fpr, [not_alive, revoked, not_supported, no_secret_key]) in bad {
1571 let id: String = if fpr == cert.fingerprint() {
1572 fpr.to_string()
1573 } else {
1574 format!("{}/{}", cert.fingerprint(), fpr)
1575 };
1576
1577 let preface = if ! self.time_is_now {
1578 format!("{} was not considered because\n\
1579 at the specified time ({}) it was",
1580 id, time)
1581 } else {
1582 format!("{} was not considered because\nit is", fpr)
1583 };
1584
1585 let mut reasons = Vec::new();
1586 if not_alive {
1587 reasons.push("not alive");
1588 }
1589 if revoked {
1590 reasons.push("revoked");
1591 }
1592 if not_supported {
1593 reasons.push("not supported");
1594 }
1595 if no_secret_key {
1596 reasons.push("missing the secret key");
1597 }
1598
1599 context.push(format!("{}: {}",
1600 preface, reasons.join(", ")));
1601 }
1602
1603 if context.is_empty() {
1604 return Err(anyhow::anyhow!(
1605 format!("Found no suitable key on {}", cert)));
1606 } else {
1607 let context = context.join("\n");
1608 return Err(
1609 anyhow::anyhow!(
1610 format!("Found no suitable key on {}", cert))
1611 .context(context));
1612 }
1613 }
1614
1615 Ok(keys)
1616 }
1617
1618 /// Returns a signer for each certificate's primary key.
1619 ///
1620 /// This returns one key for each certificate. If a certificate
1621 /// doesn't have a suitable key, then this returns an error.
1622 ///
1623 /// A key is considered suitable if:
1624 ///
1625 /// - the certificate is valid
1626 /// - the key is alive (unless allowed by `options`)
1627 /// - the key is not revoked (unless allowed by `options`)
1628 /// - the key's algorithm is supported by the underlying crypto engine.
1629 ///
1630 /// If a key is locked, then the user will be prompted to enter
1631 /// the password.
1632 pub fn get_primary_keys<C>(&self, certs: &[C],
1633 options: Option<&[GetKeysOptions]>)
1634 -> Result<Vec<Box<dyn crypto::Signer + Send + Sync>>>
1635 where C: std::borrow::Borrow<Cert>
1636 {
1637 self.get_keys(certs, KeyType::Primary, options)
1638 .map(|keys| keys.into_iter()
1639 .map(|(_, signer)| signer)
1640 .collect())
1641 }
1642
1643 /// Returns a signer for the certificate's primary key.
1644 ///
1645 /// If the certificate doesn't have a suitable key, then this
1646 /// returns an error.
1647 ///
1648 /// A key is considered suitable if:
1649 ///
1650 /// - the certificate is valid
1651 /// - the key is alive (unless allowed by `options`)
1652 /// - the key is not revoked (unless allowed by `options`)
1653 /// - the key's algorithm is supported by the underlying crypto engine.
1654 ///
1655 /// If a key is locked, then the user will be prompted to enter
1656 /// the password.
1657 pub fn get_primary_key<C>(&self, certs: C,
1658 options: Option<&[GetKeysOptions]>)
1659 -> Result<Box<dyn crypto::Signer + Send + Sync>>
1660 where C: std::borrow::Borrow<Cert>
1661 {
1662 let keys = self.get_primary_keys(&[certs], options)?;
1663 assert!(
1664 keys.len() == 1,
1665 "Expected exactly one result from get_primary_keys()"
1666 );
1667 Ok(keys.into_iter().next().unwrap())
1668 }
1669
1670 /// Returns a signer for a signing-capable key for each
1671 /// certificate.
1672 ///
1673 /// This returns one key for each certificate. If a certificate
1674 /// doesn't have a suitable key, then this returns an error.
1675 ///
1676 /// A key is considered suitable if:
1677 ///
1678 /// - the certificate is valid
1679 /// - the key is signing capable
1680 /// - the key is alive (unless allowed by `options`)
1681 /// - the key is not revoked (unless allowed by `options`)
1682 /// - the key's algorithm is supported by the underlying crypto engine.
1683 ///
1684 /// If a key is locked, then the user will be prompted to enter
1685 /// the password.
1686 pub fn get_signing_keys<C>(&self, certs: &[C],
1687 options: Option<&[GetKeysOptions]>)
1688 -> Result<Vec<(Cert, Box<dyn crypto::Signer + Send + Sync>)>>
1689 where C: Borrow<Cert>
1690 {
1691 self.get_keys(certs,
1692 KeyType::KeyFlags(KeyFlags::empty().set_signing()),
1693 options)
1694 }
1695
1696 /// Returns a signer for a signing-capable key for the
1697 /// certificate.
1698 ///
1699 /// If a certificate doesn't have a suitable key, then this
1700 /// returns an error.
1701 ///
1702 /// A key is considered suitable if:
1703 ///
1704 /// - the certificate is valid
1705 /// - the key is signing capable
1706 /// - the key is alive (unless allowed by `options`)
1707 /// - the key is not revoked (unless allowed by `options`)
1708 /// - the key's algorithm is supported by the underlying crypto engine.
1709 ///
1710 /// If a key is locked, then the user will be prompted to enter
1711 /// the password.
1712 pub fn get_signing_key<C>(&self, cert: C,
1713 options: Option<&[GetKeysOptions]>)
1714 -> Result<Box<dyn crypto::Signer + Send + Sync>>
1715 where C: Borrow<Cert>
1716 {
1717 let keys = self.get_signing_keys(&[cert], options)?;
1718 assert!(
1719 keys.len() == 1,
1720 "Expected exactly one result from get_signing_keys()"
1721 );
1722 Ok(keys.into_iter().next().unwrap().1)
1723 }
1724
1725 /// Returns a signer for a certification-capable key for each
1726 /// certificate.
1727 ///
1728 /// This returns one key for each certificate. If a certificate
1729 /// doesn't have a suitable key, then this returns an error.
1730 ///
1731 /// A key is considered suitable if:
1732 ///
1733 /// - the certificate is valid
1734 /// - the key is certification capable
1735 /// - the key is alive (unless allowed by `options`)
1736 /// - the key is not revoked (unless allowed by `options`)
1737 /// - the key's algorithm is supported by the underlying crypto engine.
1738 ///
1739 /// If a key is locked, then the user will be prompted to enter
1740 /// the password.
1741 pub fn get_certification_keys<C>(&self, certs: &[C],
1742 options: Option<&[GetKeysOptions]>)
1743 -> Result<Vec<(Cert, Box<dyn crypto::Signer + Send + Sync>)>>
1744 where C: std::borrow::Borrow<Cert>
1745 {
1746 self.get_keys(certs,
1747 KeyType::KeyFlags(KeyFlags::empty().set_certification()),
1748 options)
1749 }
1750
1751 /// Returns a signer for a certification-capable key for the
1752 /// certificate.
1753 ///
1754 /// This returns one key for each certificate. If a certificate
1755 /// doesn't have a suitable key, then this returns an error.
1756 ///
1757 /// A key is considered suitable if:
1758 ///
1759 /// - the certificate is valid
1760 /// - the key is certification capable
1761 /// - the key is alive (unless allowed by `options`)
1762 /// - the key is not revoked (unless allowed by `options`)
1763 /// - the key's algorithm is supported by the underlying crypto engine.
1764 ///
1765 /// If a key is locked, then the user will be prompted to enter
1766 /// the password.
1767 pub fn get_certification_key<C>(&self, cert: C,
1768 options: Option<&[GetKeysOptions]>)
1769 -> Result<Box<dyn crypto::Signer + Send + Sync>>
1770 where C: std::borrow::Borrow<Cert>
1771 {
1772 let keys = self.get_certification_keys(&[cert], options)?;
1773 assert!(
1774 keys.len() == 1,
1775 "Expected exactly one result from get_certification_keys()"
1776 );
1777 Ok(keys.into_iter().next().unwrap().1)
1778 }
1779
1780 /// Prints additional information in verbose mode.
1781 pub fn info(&self, msg: fmt::Arguments) {
1782 if self.verbose() {
1783 weprintln!("{}", msg);
1784 }
1785 }
1786
1787 /// Prints a hint for the user.
1788 pub fn hint(&self, msg: fmt::Arguments) -> Hint {
1789 Hint::new(! self.config.hints())
1790 .hint(msg)
1791 }
1792
1793 /// Resolve cert designators to certificates.
1794 ///
1795 /// When matching on a user ID, a certificate is only returned if
1796 /// the matching user ID can be authenticated at the specified
1797 /// amount (`trust_amount`). Note: when `trust_amount` is 0,
1798 /// matching user IDs do not have to be self signed. If a
1799 /// designator matches multiple certificates, all of them are
1800 /// returned.
1801 ///
1802 /// When matching by key handle via `--cert`, or reading a
1803 /// certificate from a file, or from stdin, the certificate is not
1804 /// further authenticated.
1805 ///
1806 /// The returned certificates are deduped (duplicate certificates
1807 /// are merged).
1808 ///
1809 /// This function returns a vector of certificates and a vector of
1810 /// errors. If processing a certificate results in an error, we
1811 /// add it to the list of errors. If a designator does not match
1812 /// any certificates, an error is added to the error vector. In
1813 /// general, designator-specific errors are returned as `Err`s in
1814 /// the `Vec`. General errors, like the certificate store is
1815 /// disabled, are returned using the outer `Result`.
1816 pub fn resolve_certs<Arguments, Prefix, Options, Doc>(
1817 &self,
1818 designators: &CertDesignators<Arguments, Prefix, Options, Doc>,
1819 trust_amount: TrustThreshold,
1820 )
1821 -> Result<(Vec<Cert>, Vec<anyhow::Error>)>
1822 where
1823 Prefix: cert_designator::ArgumentPrefix,
1824 {
1825 self.resolve_certs_filter(designators, trust_amount, &mut |_, _| Ok(()))
1826 }
1827
1828
1829 /// Like [`Sq::resolve_certs`], but takes a filter option.
1830 ///
1831 /// The filter is applied in such a way that cert designators that
1832 /// can match more than one certificate (such as `--cert-domain`)
1833 /// only fail if they don't match any cert after filtering.
1834 ///
1835 /// Note: just because `filter` is called on a certificate, and it
1836 /// returns `Ok` doesn't mean that the certificate will
1837 /// necessarily be returned.
1838 pub fn resolve_certs_filter<Arguments, Prefix, Options, Doc>(
1839 &self,
1840 designators: &CertDesignators<Arguments, Prefix, Options, Doc>,
1841 trust_amount: TrustThreshold,
1842 filter: &mut dyn FnMut(&cert_designator::CertDesignator, &LazyCert)
1843 -> Result<()>,
1844 )
1845 -> Result<(Vec<Cert>, Vec<anyhow::Error>)>
1846 where
1847 Prefix: cert_designator::ArgumentPrefix,
1848 {
1849 self.resolve_certs_filter_intern(
1850 &designators.designators, Prefix::prefix(), trust_amount, filter)
1851 }
1852
1853 /// Like [`Sq::resolve_certs_filter`], but prevents
1854 /// monomorphization.
1855 fn resolve_certs_filter_intern(
1856 &self,
1857 designators: &[cert_designator::CertDesignator],
1858 prefix: &str,
1859 trust_amount: TrustThreshold,
1860 mut filter: &mut dyn FnMut(&cert_designator::CertDesignator, &LazyCert)
1861 -> Result<()>,
1862 )
1863 -> Result<(Vec<Cert>, Vec<anyhow::Error>)>
1864 {
1865 tracer!(TRACE, "Sq::resolve_certs_filter_intern");
1866 t!("{:?}", designators);
1867
1868 // To report all errors, and not just the first one that we
1869 // encounter, we maintain a list of errors.
1870 let mut errors: Vec<anyhow::Error> = Vec::new();
1871
1872 // We merge the certificates eagerly. To do so, we maintain a
1873 // list of certificates that we've looked up.
1874 let mut results: Vec<Cert> = Vec::new();
1875
1876 // Whether `ret` added something. This needs to be a
1877 // `RefCell`. because the `ret` closure holds a `&mut` to
1878 // `results`.
1879 let matched: RefCell<bool> = RefCell::new(false);
1880
1881 // Whether we've seen the given certificate. The boolean is
1882 // if we merged in the certificate from the cert store. The
1883 // index is the index of the certificate in `results`.
1884 let mut have: BTreeMap<Fingerprint, (bool, usize)>
1885 = BTreeMap::new();
1886
1887 // The list of user ID queries.
1888 let mut userid_queries: Vec<(&cert_designator::CertDesignator, _, String)>
1889 = Vec::new();
1890
1891 // Only open the cert store if we actually need it.
1892 let mut cert_store_ = None;
1893 let mut cert_store = || -> Result<_> {
1894 if let Some(cert_store) = cert_store_ {
1895 Ok(cert_store)
1896 } else {
1897 cert_store_ = Some(self.cert_store_or_else()?);
1898 Ok(cert_store_.expect("just set"))
1899 }
1900 };
1901
1902 // Return a certificate or an error to the caller.
1903 //
1904 // `from_cert_store` is whether the certificate was read from
1905 // the certificate store or not.
1906 //
1907 // If `apply_filter` is true, `filter` is applied. This
1908 // should be done for designators that precisely designate
1909 // certs (e.g. by fingerprint, or file), and false if the designator can
1910 // match more than one cert (e.g. by user ID match).
1911 let mut ret = |designator: &cert_designator::CertDesignator,
1912 cert: Result<Arc<LazyCert>>,
1913 from_cert_store: bool,
1914 apply_filter: Option<
1915 &mut dyn FnMut(&cert_designator::CertDesignator,
1916 &LazyCert)
1917 -> Result<()>>|
1918 {
1919 let cert = match cert {
1920 Ok(cert) => cert,
1921 Err(err) => {
1922 errors.push(
1923 err.context(format!(
1924 "Failed to resolve {}",
1925 designator.argument_with_prefix(prefix))));
1926 return;
1927 }
1928 };
1929
1930 if let Some(filter) = apply_filter {
1931 if let Err(err) = filter(designator, &cert) {
1932 errors.push(
1933 err.context(format!(
1934 "Failed to resolve {}",
1935 designator.argument_with_prefix(prefix))));
1936 return;
1937 }
1938 }
1939
1940 match have.entry(cert.fingerprint()) {
1941 Entry::Occupied(mut oe) => {
1942 let (have_from_cert_store, have_cert) = oe.get_mut();
1943 if from_cert_store {
1944 if *have_from_cert_store {
1945 // We read `cert` from the cert store, and
1946 // we read the same cert from the cert
1947 // store in the past. There's nothing to
1948 // merge; we're done.
1949 *matched.borrow_mut() = true;
1950 return;
1951 }
1952 }
1953
1954 let cert = match cert.to_cert() {
1955 Ok(cert) => cert.clone(),
1956 Err(err) => {
1957 errors.push(
1958 err.context(format!(
1959 "Failed to resolve {}",
1960 designator.argument_with_prefix(prefix))));
1961 return;
1962 }
1963 };
1964
1965 assert!(*have_cert < results.len());
1966 if let Some(have_cert) = results.get_mut(*have_cert) {
1967 *have_cert = have_cert.clone()
1968 .merge_public_and_secret(cert)
1969 .expect("same cert");
1970 }
1971
1972 *have_from_cert_store |= from_cert_store;
1973
1974 *matched.borrow_mut() = true;
1975 }
1976 Entry::Vacant(ve) => {
1977 let cert = match cert.to_cert() {
1978 Ok(cert) => cert.clone(),
1979 Err(err) => {
1980 errors.push(
1981 err.context(format!(
1982 "Failed to resolve {}",
1983 designator.argument_with_prefix(prefix))));
1984 return;
1985 }
1986 };
1987
1988 ve.insert((from_cert_store, results.len()));
1989
1990 results.push(cert);
1991
1992 *matched.borrow_mut() = true;
1993 }
1994 }
1995 };
1996
1997 for designator in designators {
1998 *matched.borrow_mut() = false;
1999
2000 match designator {
2001 cert_designator::CertDesignator::Cert(kh) => {
2002 t!("Looking up certificate by handle {}", kh);
2003
2004 match cert_store()?.lookup_by_cert(kh) {
2005 Ok(matches) => {
2006 for cert in matches.into_iter() {
2007 // We matched on the primary key.
2008 ret(designator, Ok(cert), true, Some(&mut filter));
2009 }
2010 }
2011 Err(err) => {
2012 ret(designator, Err(err), true, Some(&mut filter));
2013 }
2014 }
2015 }
2016
2017 cert_designator::CertDesignator::UserID(userid) => {
2018 t!("Looking up certificate by userid {:?}", userid);
2019
2020 match designator.query_params() {
2021 Ok(Some((q, pattern))) =>
2022 userid_queries.push((designator, q, pattern)),
2023
2024 Ok(None) =>
2025 unreachable!("designator matches on user IDs"),
2026
2027 Err(err) =>
2028 ret(designator, Err(err), true, None),
2029 }
2030 }
2031
2032 cert_designator::CertDesignator::Email(email) => {
2033 t!("Looking up certificate by email {:?}", email);
2034
2035 match designator.query_params() {
2036 Ok(Some((q, pattern))) =>
2037 userid_queries.push((designator, q, pattern)),
2038
2039 Ok(None) =>
2040 unreachable!("designator matches on user IDs"),
2041
2042 Err(err) =>
2043 ret(designator, Err(err), true, None),
2044 }
2045 }
2046
2047 cert_designator::CertDesignator::Domain(domain) => {
2048 t!("Looking up certificate by domain {:?}", domain);
2049
2050 match designator.query_params() {
2051 Ok(Some((q, pattern))) =>
2052 userid_queries.push((designator, q, pattern)),
2053
2054 Ok(None) =>
2055 unreachable!("designator matches on user IDs"),
2056
2057 Err(err) =>
2058 ret(designator, Err(err), true, None),
2059 }
2060 }
2061
2062 cert_designator::CertDesignator::Grep(pattern) => {
2063 t!("Looking up certificate by pattern {:?}", pattern);
2064
2065 match designator.query_params() {
2066 Ok(Some((q, pattern))) =>
2067 userid_queries.push((designator, q, pattern)),
2068
2069 Ok(None) =>
2070 unreachable!("designator matches on user IDs"),
2071
2072 Err(err) =>
2073 ret(designator, Err(err), true, None),
2074 }
2075 }
2076
2077 cert_designator::CertDesignator::File(filename) => {
2078 t!("Reading certificates from the file {}",
2079 filename.display());
2080
2081 match crate::load_certs(
2082 std::iter::once(filename.as_path()))
2083 {
2084 Ok(found) => {
2085 if found.is_empty() {
2086 ret(designator,
2087 Err(anyhow::anyhow!(
2088 "File does not contain any \
2089 certificates")),
2090 false, Some(&mut filter));
2091 } else {
2092 for cert in found.into_iter() {
2093 ret(designator,
2094 Ok(Arc::new(cert.into())),
2095 false, Some(&mut filter));
2096 }
2097 }
2098 },
2099 Err(err) => {
2100 ret(designator, Err(err), false, Some(&mut filter));
2101 }
2102 }
2103 }
2104
2105 cert_designator::CertDesignator::Stdin => {
2106 t!("Reading certificates from stdin");
2107 let parser = CertParser::from_reader(StdinWarning::certs())
2108 .with_context(|| {
2109 format!("Failed to load certs from stdin")
2110 })?;
2111 for cert in parser {
2112 match cert {
2113 Ok(cert) => {
2114 ret(
2115 designator,
2116 Ok(Arc::new(cert.into())),
2117 false, Some(&mut filter));
2118 }
2119 Err(err) => {
2120 ret(designator,
2121 Err(err),
2122 false, Some(&mut filter));
2123 continue;
2124 }
2125 }
2126 }
2127 if ! *matched.borrow() {
2128 ret(
2129 designator,
2130 Err(anyhow::anyhow!(
2131 "stdin did not contain any certificates")),
2132 false, Some(&mut filter));
2133 }
2134 }
2135 cert_designator::CertDesignator::Special(name) => {
2136 let certd = match self.certd_or_else() {
2137 Ok(certd) => certd,
2138 Err(err) => {
2139 ret(
2140 designator,
2141 Err(err),
2142 true, Some(&mut filter));
2143 continue;
2144 }
2145 };
2146
2147 let result = match name {
2148 SpecialName::PublicDirectories => {
2149 certd.public_directory_ca()
2150 }
2151 SpecialName::KeysOpenpgpOrg => {
2152 certd.shadow_ca_keys_openpgp_org()
2153 }
2154 SpecialName::KeysMailvelopeCom => {
2155 certd.shadow_ca_keys_mailvelope_com()
2156 }
2157 SpecialName::ProtonMe => {
2158 certd.shadow_ca_proton_me()
2159 }
2160 SpecialName::WKD => {
2161 certd.shadow_ca_wkd()
2162 }
2163 SpecialName::DANE => {
2164 certd.shadow_ca_dane()
2165 }
2166 SpecialName::Autocrypt => {
2167 certd.shadow_ca_autocrypt()
2168 }
2169 SpecialName::Web => {
2170 certd.shadow_ca_web()
2171 }
2172 };
2173
2174 ret(
2175 designator,
2176 result
2177 .map(|(cert, _created)| cert)
2178 .with_context(|| {
2179 format!("Looking up special certificate {}",
2180 name)
2181 }),
2182 true, Some(&mut filter));
2183 },
2184
2185 cert_designator::CertDesignator::Self_ => {
2186 let (certs, config): (Box<dyn Iterator<Item=&Fingerprint>>, _)
2187 = match prefix
2188 {
2189 "for-" => (
2190 Box::new(self.config.encrypt_for_self().iter()),
2191 cli::encrypt::ENCRYPT_FOR_SELF,
2192 ),
2193 "signer-" => (
2194 Box::new(self.config.sign_signer_self().iter()),
2195 cli::sign::SIGNER_SELF,
2196 ),
2197 "certifier-" => (
2198 Box::new(self.config.pki_vouch_certifier_self().iter()),
2199 cli::pki::vouch::CERTIFIER_SELF,
2200 ),
2201 _ => return Err(anyhow::anyhow!(
2202 "self designator used with unexpected prefix: {}", prefix)),
2203 };
2204
2205 let mut one = false;
2206 for fp in certs {
2207 let cert = self.resolve_cert(
2208 &openpgp::KeyHandle::from(
2209 fp.clone()).into(), TrustThreshold::YOLO)?.0;
2210 ret(designator,
2211 Ok(Arc::new(cert.into())),
2212 true, Some(&mut filter));
2213 one = true;
2214 }
2215
2216 if ! one {
2217 return Err(anyhow::anyhow!(
2218 "`--{}self` is given but no default \
2219 is set in the configuration file under `{}`",
2220 prefix,
2221 config));
2222 }
2223 },
2224 }
2225 }
2226
2227 let n = if ! userid_queries.is_empty() {
2228 Some(self.wot_query()?.build())
2229 } else {
2230 None
2231 };
2232
2233 for (designator, q, pattern) in userid_queries.iter() {
2234 t!("Executing query {:?} against {}", q, pattern);
2235
2236 let n = n.as_ref().unwrap();
2237
2238 *matched.borrow_mut() = false;
2239
2240 let cert_store = cert_store()?;
2241 match cert_store.select_userid(q, pattern) {
2242 Ok(found) => {
2243 t!("=> {} results", found.len());
2244
2245 // Apply the filter, if any.
2246 let (found, error) = found.into_iter().fold(
2247 (Vec::new(), None),
2248 |(mut found, mut error), c|
2249 {
2250 match filter(designator, &c) {
2251 Ok(()) => found.push(c),
2252 Err(err) => {
2253 if error.is_none() {
2254 error = Some(err);
2255 }
2256 }
2257 }
2258
2259 (found, error)
2260 });
2261
2262 if found.is_empty() {
2263 ret(designator,
2264 Err(error.unwrap_or_else(|| {
2265 anyhow::anyhow!(
2266 "query did not match any certificates")
2267 })),
2268 true, None);
2269 continue;
2270 }
2271
2272 // If the designator doesn't match anything, we
2273 // can sometimes provide a hint, e.g., weak
2274 // crypto.
2275 let mut hint = Vec::new();
2276
2277 for cert in found.into_iter() {
2278 let mut authenticated = false;
2279 if trust_amount == TrustThreshold::YOLO {
2280 authenticated = true;
2281 } else {
2282 // Find the matching user ID and
2283 // authenticate it.
2284 for userid in cert.userids() {
2285 if q.check(&userid, pattern) {
2286 let paths = n.authenticate(
2287 &userid, cert.fingerprint(),
2288 trust_amount.into());
2289 if paths.amount() < trust_amount.into() {
2290 hint.push(Err(anyhow::anyhow!(
2291 "{}, {} cannot be authenticated \
2292 at the required level ({} of {}). \
2293 After checking that {} really \
2294 controls {}, you could certify \
2295 their certificate by running \
2296 `sq pki link add --cert {} \
2297 --userid {:?}`.",
2298 cert.fingerprint(),
2299 ui::Safe(&userid),
2300 paths.amount(), trust_amount,
2301 ui::Safe(&userid),
2302 cert.fingerprint(),
2303 cert.fingerprint(),
2304 String::from_utf8_lossy(userid.value()))));
2305 } else {
2306 authenticated = true;
2307 break;
2308 }
2309 }
2310 }
2311 }
2312
2313 if authenticated {
2314 ret(designator, Ok(cert), true, None);
2315 }
2316 }
2317
2318 if ! *matched.borrow() {
2319 // The designator didn't match any
2320 // certificates.
2321 if hint.is_empty() {
2322 ret(designator,
2323 Err(anyhow::anyhow!("Didn't match any certificates")),
2324 true, None);
2325 } else {
2326 for hint in hint.into_iter() {
2327 ret(designator,
2328 hint,
2329 true, None);
2330 }
2331 }
2332 }
2333 }
2334 Err(err) => {
2335 t!("=> {}", err);
2336 ret(designator, Err(err), true, None);
2337 }
2338 }
2339 }
2340
2341 Ok((results, errors))
2342 }
2343
2344 /// Like `Sq::resolve_certs`, but bails if there is an error
2345 /// resolving a certificate.
2346 pub fn resolve_certs_or_fail<Arguments, Prefix, Options, Doc>(
2347 &self,
2348 designators: &CertDesignators<Arguments, Prefix, Options, Doc>,
2349 trust_amount: TrustThreshold,
2350 )
2351 -> Result<Vec<Cert>>
2352 where
2353 Prefix: cert_designator::ArgumentPrefix,
2354 {
2355 let (certs, errors) = self.resolve_certs(designators, trust_amount)?;
2356
2357 for error in errors.iter() {
2358 print_error_chain(error);
2359 }
2360 if ! errors.is_empty() {
2361 return Err(anyhow::anyhow!("Failed to resolve certificates"));
2362 }
2363
2364 Ok(certs)
2365 }
2366
2367 /// Like `Sq::resolve_certs`, but bails if there is not exactly
2368 /// one designator, or the designator resolves to multiple
2369 /// certificates.
2370 ///
2371 /// Returns whether the certificate was read from a file.
2372 pub fn resolve_cert<Arguments, Prefix, Options, Doc>(
2373 &self,
2374 designators: &CertDesignators<Arguments, Prefix, Options, Doc>,
2375 trust_amount: TrustThreshold,
2376 )
2377 -> Result<(Cert, FileStdinOrKeyHandle)>
2378 where
2379 Prefix: cert_designator::ArgumentPrefix,
2380 {
2381 self.resolve_cert_intern(
2382 &designators.designators, Prefix::prefix(), trust_amount)
2383 }
2384
2385 /// Like [`Sq::resolve_certs`], but prevents monomorphization.
2386 fn resolve_cert_intern(
2387 &self,
2388 designators: &[cert_designator::CertDesignator],
2389 prefix: &str,
2390 trust_amount: TrustThreshold,
2391 )
2392 -> Result<(Cert, FileStdinOrKeyHandle)>
2393 {
2394 // Assuming this is only called with OneValue, then the
2395 // following are not required.
2396 if designators.len() == 0 {
2397 panic!("clap failed to enforce that the {} argument is \
2398 required.",
2399 prefix);
2400 } else if designators.len() > 1 {
2401 panic!("clap failed to enforce that the {} argument is \
2402 specified at most once.",
2403 prefix);
2404 }
2405
2406 let (certs, errors) =
2407 self.resolve_certs_filter_intern(designators, prefix, trust_amount,
2408 &mut |_, _| Ok(()))?;
2409 if certs.len() > 1 {
2410 weprintln!("{} is ambiguous. It resolves to multiple certificates.",
2411 designators[0].argument_with_prefix(prefix));
2412 for cert in certs.iter() {
2413 eprintln!(" - {} {}",
2414 cert.fingerprint(),
2415 self.best_userid(cert, true).display());
2416 }
2417
2418 return Err(anyhow::anyhow!(
2419 "{} is ambiguous. It resolves to multiple certificates.",
2420 designators[0].argument_with_prefix(prefix)))
2421 }
2422
2423 if let Some(errors) = errors.into_iter().next() {
2424 return Err(errors);
2425 }
2426
2427 let cert = certs.into_iter().next().unwrap();
2428 let handle = cert.key_handle();
2429 Ok((cert,
2430 match &designators[0] {
2431 cert_designator::CertDesignator::Stdin =>
2432 FileStdinOrKeyHandle::FileOrStdin(Default::default()),
2433 cert_designator::CertDesignator::File(p) =>
2434 FileStdinOrKeyHandle::FileOrStdin(p.as_path().into()),
2435 _ => handle.into()
2436 }))
2437 }
2438
2439 /// Resolves keys.
2440 ///
2441 /// Keys are resolved to valid keys (according to the current
2442 /// policy) that are not hard revoked.
2443 ///
2444 /// `cert` and `cert_handle` are as returned by
2445 /// `sq::resolve_cert`.
2446 pub fn resolve_keys<'a, KOptions, KDoc>(
2447 &self,
2448 vc: &ValidCert<'a>, cert_handle: &FileStdinOrKeyHandle,
2449 keys: &KeyDesignators<KOptions, KDoc>,
2450 return_hard_revoked: bool)
2451 -> Result<Vec<ValidErasedKeyAmalgamation<'a, PublicParts>>>
2452 where
2453 KOptions: typenum::Unsigned,
2454 {
2455 assert!(keys.len() > 0);
2456
2457 let options = KOptions::to_usize();
2458 let only_subkeys = (options & key_designator::OnlySubkeys::to_usize()) > 0;
2459
2460 let khs = keys.iter()
2461 .map(|d| {
2462 match d {
2463 key_designator::KeyDesignator::KeyHandle(kh) => kh,
2464 }
2465 })
2466 .collect::<Vec<_>>();
2467
2468 // Don't stop at the first error.
2469 let mut bad = Vec::new();
2470 let mut missing = Vec::new();
2471 let mut kas = Vec::new();
2472 for kh in khs {
2473 if let Some(ka) = vc.keys().key_handle(kh.clone()).next() {
2474 // The key is bound to the certificate.
2475
2476 if only_subkeys && ka.primary() {
2477 let err = format!(
2478 "Selected key {} is a primary key, not a subkey.",
2479 ka.key().fingerprint());
2480 weprintln!("{}", err);
2481 bad.push(anyhow::anyhow!(err));
2482 continue;
2483 }
2484
2485 // Make sure it is not hard revoked.
2486 let mut hard_revoked = false;
2487 if ! return_hard_revoked {
2488 if let RevocationStatus::Revoked(sigs)
2489 = ka.revocation_status()
2490 {
2491 for sig in sigs {
2492 let reason = sig.reason_for_revocation();
2493 hard_revoked = if let Some((reason, _)) = reason {
2494 reason.revocation_type() == RevocationType::Hard
2495 } else {
2496 true
2497 };
2498
2499 if hard_revoked {
2500 break;
2501 }
2502 }
2503 }
2504 }
2505
2506 if hard_revoked {
2507 let err = anyhow::anyhow!(
2508 "Can't use {}, it is hard revoked",
2509 ka.key().fingerprint());
2510 weprintln!("{}", err);
2511 bad.push(err);
2512 } else {
2513 // Looks good!
2514 kas.push(ka);
2515 }
2516 } else if let Some(ka)
2517 = vc.cert().keys().key_handle(kh.clone()).next()
2518 {
2519 // See if the key is associated with the certificate
2520 // in some way. This isn't enough to return it, but
2521 // we may be able to generate a better error message.
2522
2523 let fingerprint = ka.key().fingerprint();
2524
2525 let err = match ka.with_policy(vc.policy(), vc.time()) {
2526 Ok(_) => unreachable!("key magically became usable"),
2527 Err(err) => err,
2528 };
2529
2530 weprintln!("Selected key {} is unusable: {}.",
2531 fingerprint, err);
2532
2533 bad.push(err);
2534
2535 self.hint(format_args!(
2536 "After checking the integrity of the certificate, you \
2537 may be able to repair it using:"))
2538 .sq().arg("cert").arg("lint").arg("--fix")
2539 .arg_value(
2540 match &cert_handle {
2541 FileStdinOrKeyHandle::KeyHandle(_kh) => {
2542 "--cert"
2543 }
2544 FileStdinOrKeyHandle::FileOrStdin(_file) => {
2545 "--cert-file"
2546 }
2547 },
2548 match &cert_handle {
2549 FileStdinOrKeyHandle::KeyHandle(kh) => {
2550 kh.to_string()
2551 }
2552 FileStdinOrKeyHandle::FileOrStdin(file) => {
2553 file.path()
2554 .map(|p| p.display().to_string())
2555 .unwrap_or_else(|| "".into())
2556 }
2557 })
2558 .done();
2559 } else {
2560 // The key isn't bound to the certificate at all.
2561 weprintln!("Selected key {} is not part of the certificate.",
2562 kh);
2563 missing.push(kh);
2564 }
2565 }
2566
2567 assert_eq!(keys.len(), kas.len() + missing.len() + bad.len(),
2568 "Didn't partition {} keys: {} valid, {} missing, {} bad",
2569 keys.len(), kas.len(), missing.len(), bad.len());
2570
2571 if ! missing.is_empty() {
2572 weprintln!();
2573 if only_subkeys {
2574 weprintln!("{} has the following subkeys:", vc.cert().fingerprint());
2575 } else {
2576 weprintln!("{} has the following keys:", vc.cert().fingerprint());
2577 }
2578 weprintln!();
2579 for ka in vc.keys().skip(if only_subkeys { 1 } else { 0 }) {
2580 weprintln!(" - {}", ka.key().fingerprint());
2581 }
2582 }
2583
2584 if let Some(err) = bad.into_iter().next() {
2585 return Err(err);
2586 } else if ! missing.is_empty() {
2587 return Err(anyhow::anyhow!(
2588 "Some keys are not associated with the certificate"));
2589 }
2590
2591 // Dedup.
2592 kas.sort_by_key(|ka| ka.key().fingerprint());
2593 kas.dedup_by_key(|ka| ka.key().fingerprint());
2594
2595 assert!(kas.len() > 0);
2596
2597 Ok(kas)
2598 }
2599 }