Debian Codegraph @

src/common/pki/authenticate.rs

raw
1 use std::collections::BTreeSet;
2
3 use anyhow::Context;
4
5 use typenum::Unsigned;
6
7 use sequoia_openpgp as openpgp;
8 use openpgp::Cert;
9 use openpgp::Fingerprint;
10 use openpgp::KeyHandle;
11 use openpgp::Result;
12 use openpgp::types::RevocationStatus;
13 use openpgp::packet::UserID;
14
15 use sequoia_cert_store as cert_store;
16 use cert_store::store::StoreError;
17 use cert_store::store::UserIDQueryParams;
18 use cert_store::Store as _;
19
20 use sequoia_wot as wot;
21 use wot::store::Backend;
22 use wot::store::Store;
23
24 use crate::cli;
25 use cli::types::CertDesignators;
26 use cli::types::TrustAmount;
27 use cli::types::UserIDDesignators;
28 use cli::types::cert_designator;
29 use cli::types::userid_designator;
30
31 use super::output::ConciseHumanReadableOutputNetwork;
32 use super::output::OutputType;
33
34 use crate::{
35 Sq,
36 common::ui,
37 };
38
39 const TRACE: bool = false;
40
41 /// The different kinds of queries that we support.
42 pub enum QueryKind {
43 AuthenticatedCert(KeyHandle),
44 Cert(KeyHandle),
45 UserID(String),
46 Email(String),
47 UserIDBinding(KeyHandle, String),
48 EmailBinding(KeyHandle, String),
49 Domain(String),
50 Pattern(String),
51 All,
52 }
53
54 pub struct Query {
55 /// The user-supplied command-line argument, e.g., `--cert
56 /// FINGERPRINT`.
57 pub argument: Option<String>,
58 pub kind: QueryKind,
59 }
60
61 impl Query {
62 /// Returns a `Query` that matches all bindings.
63 pub fn all() -> Self {
64 Query {
65 argument: None,
66 kind: QueryKind::All,
67 }
68 }
69
70 /// Returns a `Query` for a key handle.
71 ///
72 /// `argument` is the user-supplied command-line argument, e.g.,
73 /// `--cert FINGERPRINT`.
74 pub fn for_key_handle(argument: Option<String>, kh: KeyHandle)
75 -> Query
76 {
77 Query {
78 argument,
79 kind: QueryKind::Cert(kh),
80 }
81 }
82
83 /// Converts a set of certificate designators to a set of queries.
84 pub fn for_cert_designators<Arguments, Prefix, Options, Doc>(
85 designators: CertDesignators<Arguments, Prefix, Options, Doc>,
86 certs_are_authenticated: bool)
87 -> Vec<Query>
88 where
89 Arguments: typenum::Unsigned,
90 Prefix: cert_designator::ArgumentPrefix,
91 {
92 let arguments = Arguments::to_usize();
93 let file_arg = (arguments & cert_designator::FileArg::to_usize()) > 0;
94 let special_arg = (arguments & cert_designator::SpecialArg::to_usize()) > 0;
95 let self_arg = (arguments & cert_designator::SelfArg::to_usize()) > 0;
96
97 assert!(! file_arg);
98 assert!(! special_arg);
99 assert!(! self_arg);
100
101 designators.iter()
102 .map(|designator| {
103 use cert_designator::CertDesignator::*;
104 let kind = match designator {
105 Stdin | File(_) | Special(_) | Self_ => {
106 unreachable!("Not allowed in this context");
107 }
108 Cert(kh) => {
109 if certs_are_authenticated {
110 QueryKind::AuthenticatedCert(kh.clone())
111 } else {
112 QueryKind::Cert(kh.clone())
113 }
114 }
115 UserID(userid) => QueryKind::UserID(userid.clone()),
116 Email(email) => QueryKind::Email(email.clone()),
117 Domain(domain) => QueryKind::Domain(domain.clone()),
118 Grep(pattern) => QueryKind::Pattern(pattern.clone()),
119 };
120
121 Query {
122 argument: Some(designator.argument::<Prefix>()),
123 kind,
124 }
125 })
126 .collect()
127 }
128
129 /// Creates a query for a binding consisting of a certificate
130 /// designator and a user ID designator.
131 pub fn for_binding<CertPrefix, CertOptions, CertDoc,
132 UserIDArguments, UserIDOptions, UserIDDocumentation>
133 (cert: CertDesignators<cert_designator::CertArg,
134 CertPrefix, CertOptions, CertDoc>,
135 userid: UserIDDesignators<UserIDArguments,
136 UserIDOptions, UserIDDocumentation>)
137 -> Vec<Query>
138 where
139 CertOptions: typenum::Unsigned,
140 CertPrefix: cert_designator::ArgumentPrefix,
141 UserIDArguments: typenum::Unsigned,
142 UserIDOptions: typenum::Unsigned,
143 {
144 // One required value.
145 let cert_options = CertOptions::to_usize();
146 let cert_one_value
147 = (cert_options & cert_designator::OneValue::to_usize()) > 0;
148 let cert_optional_value
149 = (cert_options & cert_designator::OptionalValue::to_usize()) > 0;
150 assert!(cert_one_value);
151 assert!(! cert_optional_value);
152
153 // One required value.
154 let userid_options = UserIDOptions::to_usize();
155 let userid_one_value
156 = (userid_options & userid_designator::OneValue::to_usize()) > 0;
157 let userid_optional_value
158 = (userid_options & userid_designator::OptionalValue::to_usize()) > 0;
159 assert!(userid_one_value);
160 assert!(! userid_optional_value);
161
162 assert_eq!(cert.len(), 1);
163 let cert = cert.iter().next().unwrap();
164 let kh = if let cert_designator::CertDesignator::Cert(kh) = cert {
165 kh
166 } else {
167 unreachable!("Only CertArg");
168 };
169
170 assert_eq!(userid.len(), 1);
171 let userid = userid.iter().next().unwrap();
172 let kind = match userid {
173 userid_designator::UserIDDesignator::UserID(_, userid) => {
174 QueryKind::UserIDBinding(kh.clone(), userid.clone())
175 }
176 userid_designator::UserIDDesignator::Email(_, email) => {
177 QueryKind::EmailBinding(kh.clone(), email.clone())
178 }
179 userid_designator::UserIDDesignator::Name(_, _name) => {
180 unreachable!("--name is disabled")
181 }
182 };
183
184 vec![
185 Query {
186 argument: Some(format!("{} {}",
187 cert.argument::<CertPrefix>(),
188 userid.argument::<UserIDArguments>())),
189 kind,
190 }
191 ]
192 }
193 }
194
195 impl<Arguments, Prefix, Options, Doc>
196 From<CertDesignators<Arguments, Prefix, Options, Doc>> for Vec<Query>
197 where
198 Arguments: typenum::Unsigned,
199 Prefix: cert_designator::ArgumentPrefix,
200 {
201 fn from(designators: CertDesignators<Arguments, Prefix, Options, Doc>)
202 -> Vec<Query>
203 {
204 Query::for_cert_designators(designators, false)
205 }
206 }
207
208 impl<Arguments, Options, Documentation>
209 From<UserIDDesignators<Arguments, Options, Documentation>> for Vec<Query>
210 where
211 Arguments: typenum::Unsigned,
212 {
213 fn from(designators: UserIDDesignators<Arguments, Options, Documentation>)
214 -> Vec<Query>
215 {
216 designators.iter()
217 .map(|designator| {
218 use userid_designator::UserIDDesignator::*;
219 let kind = match designator {
220 UserID(_, userid) => QueryKind::UserID(userid.clone()),
221 Email(_, email) => QueryKind::Email(email.clone()),
222 Name(_, _name) => {
223 unreachable!("--name is disabled");
224 }
225 };
226
227 Query {
228 argument: Some(designator.argument::<Arguments>()),
229 kind,
230 }
231 })
232 .collect()
233 }
234 }
235
236 pub fn required_trust_amount(trust_amount: Option<TrustAmount<usize>>,
237 certification_network: bool)
238 -> Result<usize>
239 {
240 let amount = if let Some(v) = &trust_amount {
241 v.amount()
242 } else {
243 if certification_network {
244 // Look for multiple paths. Specifically, try to find 10
245 // paths.
246 10 * wot::FULLY_TRUSTED
247 } else {
248 wot::FULLY_TRUSTED
249 }
250 };
251
252 Ok(amount)
253 }
254
255 /// The context in which authenticate is called.
256 ///
257 /// This controls the output.
258 #[derive(Debug, Clone, PartialEq, Eq)]
259 pub enum AuthenticateContext {
260 PKI,
261 Download,
262 }
263
264 /// Authenticate bindings defined by a Query on a Network
265 ///
266 /// If `gossip` is specified, paths that are not rooted are still
267 /// shown (with a trust amount of 0, of course).
268 pub fn authenticate<'store, 'rstore, Q>(
269 o: &mut dyn std::io::Write,
270 sq: &Sq<'store, 'rstore>,
271 context: AuthenticateContext,
272 queries: Vec<Q>,
273 gossip: bool,
274 unusable: bool,
275 certification_network: bool,
276 trust_amount: Option<TrustAmount<usize>>,
277 show_paths: bool,
278 ) -> Result<()>
279 where 'store: 'rstore,
280 Q: Into<Query>
281 {
282 tracer!(TRACE, "authenticate");
283
284 make_qprintln!(sq.quiet());
285
286 let mut queries: Vec<Query>
287 = queries.into_iter().map(|q| q.into()).collect();
288 if queries.is_empty() {
289 queries.push(Query::all());
290 };
291
292 let return_all = queries.iter().any(|q| matches!(q.kind, QueryKind::All));
293
294 // Build the network.
295 let cert_store = sq.cert_store_or_else()?;
296 if return_all {
297 cert_store.precompute();
298 }
299
300 let mut n = wot::NetworkBuilder::rooted(cert_store, &*sq.trust_roots());
301 if certification_network {
302 n = n.certification_network();
303 }
304 let n = n.build();
305
306 let required_amount =
307 required_trust_amount(trust_amount, certification_network)?;
308 t!("required amount: {} (gossip: {})", required_amount, gossip);
309
310 // Map a key handle to the named certificates.
311 let resolve_key_handle = |kh: &KeyHandle| -> Vec<Fingerprint> {
312 match kh {
313 KeyHandle::Fingerprint(fpr) => vec![ fpr.clone() ],
314 KeyHandle::KeyID(_) => {
315 if let Ok(certs) = cert_store.lookup_by_cert(&kh) {
316 certs.into_iter().map(|c| c.fingerprint()).collect()
317 } else {
318 // We don't error out here: at the end of this
319 // function we check that all queries matched at
320 // least one certificate.
321 vec![]
322 }
323 }
324 }
325 };
326
327 // Get the candidates.
328 //
329 // The `bool` means: always show the certificate, even if it can't
330 // be authenticated. The `Vec<usize>` are the queries that
331 // resolve to that binding.
332 let mut bindings: Vec<(Fingerprint, Option<UserID>, bool, Vec<usize>)>
333 = Vec::new();
334
335 // Whether query #index matched something.
336 let mut queries_satisfied = vec![false; queries.len()];
337
338 for (i, query) in queries.iter().enumerate() {
339 match &query.kind {
340 QueryKind::AuthenticatedCert(kh) | QueryKind::Cert(kh) => {
341 t!("Authenticating {}", kh);
342
343 let cert_authenticated
344 = matches!(query.kind, QueryKind::AuthenticatedCert(_));
345
346 for fpr in resolve_key_handle(kh) {
347 let count = bindings.len();
348 bindings.extend(
349 n.certified_userids_of(&fpr)
350 .into_iter()
351 .map(|userid| {
352 (fpr.clone(), Some(userid),
353 cert_authenticated, vec![ i ])
354 }));
355
356 if bindings.len() == count {
357 // No user IDs. Add the certificate.
358 bindings.push((fpr.clone(), None,
359 cert_authenticated, vec![ i ]));
360 }
361 }
362 }
363 QueryKind::UserID(userid) => {
364 t!("Authenticating user ID: {:?}", userid);
365
366 bindings.extend(
367 n.lookup_synopses_by_userid(UserID::from(&userid[..]))
368 .into_iter()
369 .map(|fpr| {
370 (fpr, Some(UserID::from(&userid[..])),
371 false, vec![ i ])
372 }));
373 }
374 QueryKind::EmailBinding(_, email) | QueryKind::Email(email) =>
375 {
376 let kh = if let QueryKind::EmailBinding(kh, _) = &query.kind {
377 t!("Authenticating binding: {}, {:?}", kh, email);
378 Some(kh)
379 } else {
380 t!("Authenticating email: {:?}", email);
381 None
382 };
383
384 let userid_check = UserID::from(format!("<{}>", email));
385 if let Ok(Some(email_check)) = userid_check.email() {
386 if email != email_check {
387 return Err(anyhow::anyhow!(
388 "{:?} does not appear to be an email address",
389 email));
390 }
391 } else {
392 return Err(anyhow::anyhow!(
393 "{:?} does not appear to be an email address",
394 email));
395 }
396
397 // Now, iterate over all of the certifications of the target,
398 // and select the bindings where the User ID matches the email
399 // address.
400 let b = if let Some(kh) = kh.as_ref() {
401 let fprs = resolve_key_handle(kh);
402 fprs.into_iter().flat_map(|fpr| {
403 n.certified_userids_of(&fpr)
404 .into_iter()
405 .map(|userid| (fpr.clone(), Some(userid)))
406 .collect::<Vec<_>>()
407 .into_iter()
408 }).collect::<Vec<_>>()
409 } else {
410 n.lookup_synopses_by_email(&email)
411 .into_iter()
412 .map(|(fp, userid)| (fp, Some(userid)))
413 .collect()
414 };
415
416 let email_normalized = userid_check.email_normalized()
417 .expect("checked").expect("checked");
418 bindings.extend(
419 b.into_iter().filter_map(|(fingerprint, userid_other)| {
420 if let Some(email_other_normalized)
421 = userid_other.as_ref()
422 .and_then(|u| u.email_normalized().ok())
423 .flatten()
424 {
425 if email_normalized == email_other_normalized {
426 Some((fingerprint, userid_other.clone(),
427 false, vec![ i ]))
428 } else {
429 None
430 }
431 } else {
432 None
433 }
434 }));
435 }
436 QueryKind::UserIDBinding(kh, userid) => {
437 t!("Authenticating {}, {:?}", kh, userid);
438 for fpr in resolve_key_handle(kh) {
439 bindings.push((fpr, Some(UserID::from(&userid[..])),
440 false, vec![ i ]));
441 }
442 }
443 QueryKind::Domain(pattern) | QueryKind::Pattern(pattern) => {
444 let pattern_;
445 let (query_params, pattern)
446 = if let QueryKind::Domain(_) = query.kind
447 {
448 t!("Authenticating domain {}", pattern);
449
450 let domain = UserIDQueryParams::is_domain(pattern)?;
451 let mut query_params = UserIDQueryParams::new();
452 query_params.set_email(true)
453 .set_anchor_start(false);
454 pattern_ = format!("@{}", domain);
455
456 (query_params, &pattern_)
457 } else {
458 if pattern.is_empty() {
459 t!("Authenticating everything");
460 } else {
461 t!("Authenticating user IDs matching {:?}", pattern);
462 }
463
464 let mut query_params = UserIDQueryParams::new();
465 query_params
466 .set_email(false)
467 .set_anchor_start(false)
468 .set_anchor_end(false)
469 .set_ignore_case(true);
470
471 (query_params, pattern)
472 };
473
474 if ! pattern.is_empty() {
475 // If the pattern doesn't match anything, don't
476 // abort yet. There might be other queries.
477 if let Ok(matches)
478 = cert_store.select_userid(&query_params, pattern)
479 {
480 bindings.extend(
481 matches
482 .into_iter()
483 .flat_map(|cert| {
484 cert.userids()
485 .filter(|userid| {
486 t!("Checking {}, {}",
487 cert.fingerprint(),
488 String::from_utf8_lossy(userid.value()));
489
490 query_params.check(&userid, pattern)
491 })
492 .map(|userid| {
493 (cert.fingerprint(), Some(userid),
494 false, vec![ i ])
495 })
496 .collect::<Vec<_>>()
497 .into_iter()
498 }));
499 }
500 } else {
501 bindings.extend(
502 n.certified_userids()
503 .into_iter()
504 .map(|(fp, userid)| {
505 (fp, Some(userid), false, vec![ i ])
506 }));
507 }
508 }
509 QueryKind::All => {
510 // --all is always satisfied.
511 queries_satisfied[i] = true;
512
513 let mut certs = BTreeSet::new();
514 bindings.extend(
515 n.certified_userids()
516 .into_iter()
517 .map(|(fp, userid)| {
518 certs.insert(fp.clone());
519
520 (fp, Some(userid), false, vec![ i ])
521 }));
522
523 // Add certificates without user IDs.
524 let all_certs: BTreeSet<_> = n.iter_fingerprints().collect();
525 bindings.extend(
526 all_certs.difference(&certs).map(|fp| {
527 (fp.clone(), None, false, vec![ i ])
528 }));
529 }
530 }
531 }
532
533 // There may be multiple certifications of the same
534 // User ID. Dedup.
535 bindings.sort_by(
536 |(a_fpr, a_userid, _, _), (b_fpr, b_userid, _, _)|
537 {
538 a_fpr.cmp(b_fpr)
539 .then(a_userid.cmp(b_userid))
540 });
541 bindings.dedup_by(
542 |(a_fpr, a_userid, a_show, a_idx), (b_fpr, b_userid, b_show, b_idx)|
543 {
544 if a_fpr == b_fpr && a_userid == b_userid {
545 // debup removes a, so we merge into b.
546 b_idx.extend_from_slice(&a_idx[..]);
547 *b_show |= *a_show;
548 true
549 } else {
550 false
551 }
552 });
553 t!("Checking {} bindings", bindings.len());
554
555 // The number of matching bindings that we showed.
556 let mut bindings_authenticated = 0;
557
558 // The number of bindings that we skipped because the certificate
559 // or user ID was invalid / unusable.
560 let mut bindings_unusable = 0;
561
562 let mut output = ConciseHumanReadableOutputNetwork::new(
563 o, &sq, required_amount, show_paths);
564
565 // Look up the certificate, and return it if it is valid.
566 let check_cert = |fpr: &Fingerprint| -> Result<Cert> {
567 // Look up the certificate.
568 let kh = KeyHandle::from(fpr);
569 let lc = match cert_store.lookup_by_cert(&kh) {
570 Ok(certs) => {
571 assert_eq!(certs.len(), 1, "there can be only one");
572 certs.into_iter().next().unwrap()
573 }
574 Err(err) => {
575 // See if it is a subkey.
576 if let Some(StoreError::NotFound(_)) = err.downcast_ref() {
577 if let Ok(certs)
578 = cert_store.lookup_by_cert_or_subkey(&kh)
579 {
580 return Err(anyhow::anyhow!(
581 "{} appears to be a subkey of {}",
582 fpr,
583 certs.iter()
584 .map(|c| c.fingerprint().to_string())
585 .collect::<Vec<String>>()
586 .join(", ")));
587 }
588 }
589
590 return Err(err);
591 }
592 };
593
594 let cert = lc.to_cert()
595 .with_context(|| format!("{} is unusable", fpr))?;
596
597 // Check if the certificate is valid according to the current
598 // policy.
599 let vc = cert.with_policy(sq.policy, sq.time)
600 .with_context(|| format!("{} is unusable", fpr))?;
601
602 // Check if the certificate is live.
603 let _ = vc.alive()
604 .with_context(|| format!("{} is not live", fpr))?;
605
606 // Check that it is not revoked.
607 if let RevocationStatus::Revoked(sigs)
608 = cert.revocation_status(sq.policy, sq.time)
609 {
610 if let Some((reason, message))
611 = sigs[0].reason_for_revocation()
612 {
613 return Err(anyhow::anyhow!(
614 "{} is revoked: {}{}.",
615 cert.fingerprint(),
616 reason,
617 ui::Safe(message)));
618 } else {
619 return Err(anyhow::anyhow!(
620 "{} is revoked: unspecified reason.",
621 cert.fingerprint()));
622 }
623 }
624
625 Ok(cert.clone())
626 };
627
628 // Check that the user ID is valid.
629 let check_userid = |cert: &Cert, userid: &UserID| -> Result<()> {
630 if let Some(ua)
631 = cert.userids().find(|ua| ua.userid() == userid)
632 {
633 if let RevocationStatus::Revoked(sigs)
634 = ua.revocation_status(sq.policy, sq.time)
635 {
636 if let Some((reason, message))
637 = sigs[0].reason_for_revocation()
638 {
639 return Err(anyhow::anyhow!(
640 "{}, {} is revoked: {}{}.",
641 cert.fingerprint(),
642 userid,
643 reason,
644 ui::Safe(message)));
645 } else {
646 return Err(anyhow::anyhow!(
647 "{}, {} is revoked: unspecified reason.",
648 cert.fingerprint(), userid));
649 }
650 }
651 }
652
653 Ok(())
654 };
655
656 // bool: true if the lint is for the certificate (not the user ID).
657 let mut lints: Vec<(anyhow::Error, bool, &[usize])>
658 = Vec::with_capacity(queries.len());
659
660 for (fingerprint, userid, cert_authenticated, i) in bindings.iter() {
661 if let Some(userid) = userid {
662 let paths = if gossip {
663 n.gossip(fingerprint.clone(), userid.clone())
664 } else {
665 n.authenticate(
666 userid.clone(), fingerprint.clone(), required_amount)
667 };
668
669 let aggregated_amount = paths.amount();
670 t!("{}, {:?}: {}", fingerprint, userid, aggregated_amount);
671 let userid_authenticated = if aggregated_amount >= required_amount {
672 // We authenticated the binding!
673 true
674 } else if gossip && (aggregated_amount > 0 || unusable) {
675 // We're in gossip mode, show all bindings...
676 true
677 } else if gossip && aggregated_amount == 0 {
678 // ... as long as the certificate is valid...
679 let cert = match check_cert(&fingerprint) {
680 Err(err) => {
681 t!("Skipping {}: {}", fingerprint, err);
682 bindings_unusable += 1;
683 lints.push((err, true, &i));
684 continue;
685 }
686 Ok(cert) => cert
687 };
688
689 // ... and the user ID is not revoked.
690 if let Err(err) = check_userid(&cert, &userid)
691 {
692 t!("Skipping {}, {}: {}", fingerprint, userid, err);
693 if ! *cert_authenticated {
694 bindings_unusable += 1;
695 lints.push((err, false, &i));
696 continue;
697 }
698 false
699 } else {
700 true
701 }
702 } else if *cert_authenticated {
703 // The binding is not authenticated, but we should
704 // show the certificate if it is valid.
705 if let Err(err) = check_cert(&fingerprint) {
706 t!("Skipping {}: {}", fingerprint, err);
707 bindings_unusable += 1;
708 lints.push((err, true, &i));
709 continue;
710 }
711
712 false
713 } else {
714 // Don't show it.
715 t!("Failed to sufficiently authenticate the binding");
716
717 if aggregated_amount == 0 {
718 if let Err(err) = check_cert(&fingerprint) {
719 t!("{}: {}", fingerprint, err);
720 bindings_unusable += 1;
721 lints.push((err, true, &i));
722 } else {
723 if ! n.certified_userids_of(fingerprint)
724 .contains(userid)
725 {
726 lints.push((
727 anyhow::anyhow!(
728 "{:?} was never certified for {}",
729 String::from_utf8_lossy(userid.value()),
730 fingerprint),
731 false, &i));
732 }
733 }
734 }
735
736 continue;
737 };
738
739 output.add_cert(fingerprint)?;
740 if userid_authenticated {
741 let paths = paths.into_iter().collect::<Vec<(wot::Path, usize)>>();
742 output.add_paths(paths, fingerprint, userid, aggregated_amount)?;
743
744 bindings_authenticated += 1;
745 }
746 } else {
747 // A certificate with no User ID bindings.
748 if gossip || *cert_authenticated {
749 if ! unusable {
750 if let Err(err) = check_cert(fingerprint) {
751 t!("Skipping {}: {}", fingerprint, err);
752 bindings_unusable += 1;
753 lints.push((err, true, &i));
754 continue;
755 }
756 }
757
758 output.add_cert(fingerprint)?;
759 bindings_authenticated += 1;
760 } else {
761 t!("Skipping {}: no user IDs", fingerprint);
762 continue;
763 }
764 }
765
766 for i in i.into_iter() {
767 queries_satisfied[*i] = true;
768 }
769 }
770
771 output.finalize()?;
772
773 let mut unsatisfied = 0;
774 for (i, satisfied) in queries_satisfied.into_iter().enumerate() {
775 if satisfied {
776 continue;
777 }
778 unsatisfied += 1;
779
780 // We didn't show anything. Try to figure out what was wrong.
781 let query = &queries[i];
782
783 if context == AuthenticateContext::PKI {
784 if gossip {
785 qprintln!("No valid bindings match {}.",
786 query.argument.as_deref().unwrap_or("the query"));
787 } else {
788 qprintln!("No bindings matching {} could be authenticated.",
789 query.argument.as_deref().unwrap_or("the query"));
790 }
791 }
792
793 for (lint, for_cert, is) in lints.iter() {
794 if ! gossip && *for_cert {
795 use QueryKind::*;
796 match queries[i].kind {
797 AuthenticatedCert(_) | Cert(_)
798 | UserIDBinding(_, _) | EmailBinding(_, _) | All =>
799 {
800 ()
801 }
802 UserID(_) | Email(_) | Domain(_) | Pattern(_) => {
803 // It's a certificate-specific lint, but we're
804 // matching on user IDs. Skip it.
805 continue;
806 }
807 }
808 }
809 if is.contains(&i) {
810 qprintln!(initial_indent = " - ",
811 "Warning: {}", crate::one_line_error_chain(lint));
812 }
813 }
814 }
815
816 // See if the trust roots exist.
817 if unsatisfied > 0 && ! gossip && context == AuthenticateContext::PKI {
818 if n.roots().iter().all(|r| {
819 let fpr = r.fingerprint();
820 if let Err(err) = n.lookup_synopsis_by_fpr(&fpr) {
821 qprintln!("Looking up trust root ({}): {}.",
822 fpr, err);
823 true
824 } else {
825 false
826 }
827 })
828 {
829 qprintln!("Warning: No trust roots found.");
830 }
831 }
832
833 if context == AuthenticateContext::PKI {
834 if bindings.is_empty() {
835 // There are no matching bindings.
836
837 qprintln!("No valid bindings match the query.");
838
839 if queries.len() == 1 {
840 if let QueryKind::Pattern(pattern) = &queries[0].kind {
841 // Tell the user about `sq network fetch`.
842 sq.hint(format_args!(
843 "Try searching public directories:"))
844 .sq().arg("network").arg("search")
845 .arg(pattern)
846 .done();
847 }
848 } else if n.iter_fingerprints().next().is_none() {
849 qprintln!("Warning: The certificate store does not contain any \
850 certificates.");
851
852 if return_all {
853 sq.hint(format_args!(
854 "Consider creating a key for yourself:"))
855 .sq().arg("key").arg("generate")
856 .arg_value("--name", "your-name")
857 .arg_value("--email", "your-email-address")
858 .arg("--own-key")
859 .done();
860
861 sq.hint(format_args!(
862 "Consider importing other peoples' certificates:"))
863 .sq().arg("cert").arg("import")
864 .arg("a-cert-file.pgp")
865 .done();
866
867 sq.hint(format_args!(
868 "Try searching public directories for other peoples' \
869 certificates:"))
870 .sq().arg("network").arg("search")
871 .arg("some-mail-address")
872 .done();
873 }
874 }
875 } else if gossip {
876 // We are in gossip mode. Mention `sq pki link` as a way to
877 // mark bindings as authenticated.
878 if bindings_authenticated > 0 {
879 qprintln!("After checking that a user ID really belongs to \
880 a certificate, use `sq pki link add` to mark \
881 the binding as authenticated, or use \
882 `sq network search FINGERPRINT|EMAIL` to look for \
883 new certifications.");
884 } else {
885 qprintln!("No bindings are valid.");
886 }
887 }
888
889 if bindings.len() - bindings_authenticated > 0 {
890 // Some of the matching bindings were not shown. Tell the
891 // user about the `--gossip` option.
892 let bindings = bindings.len();
893 assert!(bindings > 0);
894 let bindings_not_authenticated
895 = bindings - bindings_authenticated - bindings_unusable;
896
897 if bindings == 1 {
898 qprintln!("1 binding found.");
899 } else {
900 qprintln!("{} bindings found.", bindings);
901 }
902
903 if bindings_unusable == 1 {
904 qprintln!("Skipped 1 binding, which is unusable.");
905 } else if bindings_unusable > 1 {
906 qprintln!("Skipped {} bindings, which are unusable.",
907 bindings_unusable);
908 }
909
910 if bindings_not_authenticated == 1 {
911 qprintln!("Skipped 1 binding, which could not be authenticated.");
912 qprintln!("Pass `--gossip` to see the unauthenticated binding.");
913 } else if bindings_not_authenticated > 1 {
914 qprintln!("Skipped {} bindings, which could not be authenticated.",
915 bindings_not_authenticated);
916 qprintln!("Pass `--gossip` to see the unauthenticated bindings.");
917 }
918 }
919 }
920
921 if unsatisfied == 1 {
922 if gossip {
923 if queries.len() == 1 {
924 Err(anyhow::anyhow!("No bindings match the query."))
925 } else {
926 Err(anyhow::anyhow!("No bindings match one of the queries."))
927 }
928 } else {
929 if queries.len() == 1 {
930 Err(anyhow::anyhow!(
931 "No bindings matching the query could be authenticated."))
932 } else {
933 Err(anyhow::anyhow!(
934 "No bindings matching one of the queries could be authenticated."))
935 }
936 }
937 } else if unsatisfied > 1 {
938 if gossip {
939 Err(anyhow::anyhow!("No bindings match {} of the queries.",
940 unsatisfied))
941 } else {
942 Err(anyhow::anyhow!(
943 "No bindings matching {} of the queries could be authenticated.",
944 unsatisfied))
945 }
946 } else {
947 Ok(())
948 }
949 }