Debian Codegraph @

src/commands/key/list.rs

raw
1 use std::{
2 cmp::Ordering,
3 collections::{BTreeMap, BTreeSet, HashSet},
4 fmt,
5 time::SystemTime,
6 };
7
8 use sequoia_openpgp::{
9 Cert,
10 Fingerprint,
11 KeyHandle,
12 cert::amalgamation::ValidAmalgamation,
13 cert::amalgamation::ValidateAmalgamation,
14 packet::{Key, key, UserID},
15 types::RevocationStatus,
16 };
17
18 use sequoia_keystore as keystore;
19 use keystore::Protection;
20
21 use crate::Convert;
22 use crate::PreferredUserID;
23 use crate::Result;
24 use crate::Sq;
25 use crate::Time;
26 use crate::cli::types::cert_designator;
27 use crate::cli;
28 use crate::common::NULL_POLICY;
29 use crate::common::ui;
30 use crate::sq::TrustThreshold;
31
32 /// Keys may either be grouped into a certificate or be bare.
33 ///
34 /// We define `Ord` and `Eq`, but only consider fingerprints. This
35 /// data structure is meant as a key in a `BTreeMap`.
36 #[derive(Debug)]
37 enum Association {
38 /// Keys grouped into a certificate.
39 Bound(Cert),
40
41 /// Bare keys.
42 Bare(Key<key::PublicParts, key::UnspecifiedRole>),
43 }
44
45 impl Association {
46 /// Returns the associated certificate, if any.
47 pub fn cert(&self) -> Option<&Cert> {
48 match self {
49 Association::Bound(c) => Some(c),
50 Association::Bare(_) => None
51 }
52 }
53
54 /// Returns the primary or bare key.
55 pub fn key(&self) -> &Key<key::PublicParts, key::UnspecifiedRole> {
56 match self {
57 Association::Bound(c) => c.primary_key().key().into(),
58 Association::Bare(k) => k,
59 }
60 }
61 }
62
63 impl PartialOrd for Association {
64 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
65 match (self, other) {
66 (Association::Bound(a), Association::Bound(b)) =>
67 a.fingerprint().partial_cmp(&b.fingerprint()),
68 (Association::Bound(_), Association::Bare(_)) =>
69 Some(Ordering::Less),
70 (Association::Bare(_), Association::Bound(_)) =>
71 Some(Ordering::Greater),
72 (Association::Bare(a), Association::Bare(b)) =>
73 a.fingerprint().partial_cmp(&b.fingerprint()),
74 }
75 }
76 }
77
78 impl Ord for Association {
79 fn cmp(&self, other: &Self) -> Ordering {
80 self.partial_cmp(other).expect("total")
81 }
82 }
83
84 impl PartialEq for Association {
85 fn eq(&self, other: &Self) -> bool {
86 self.cmp(other) == Ordering::Equal
87 }
88 }
89
90 impl Eq for Association {}
91
92 /// A location in the key store.
93 ///
94 /// A key may reside at different locations, and its availability and
95 /// protection status are per location.
96 #[derive(Debug, Clone, PartialEq, Eq)]
97 struct Location {
98 backend: String,
99 device: String,
100 available: bool,
101 protection: &'static str,
102 }
103
104 impl fmt::Display for Location {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 write!(f, "@{}/{}: {}, {}",
107 self.backend,
108 self.device,
109 if self.available {
110 "available"
111 } else {
112 "not available"
113 },
114 self.protection,
115 )
116 }
117 }
118
119 /// Metadata associated with a key, notably its locations.
120 #[derive(Debug, Clone, PartialEq, Eq)]
121 struct KeyInfo {
122 key: Key<key::PublicParts, key::UnspecifiedRole>,
123 locations: Vec<Location>,
124 signing_capable: bool,
125 decryption_capable: bool,
126 }
127
128 impl KeyInfo {
129 /// Returns a human-readable description describing how the key
130 /// can be used.
131 pub fn usable_for(&self) -> &'static str {
132 match (self.signing_capable, self.decryption_capable) {
133 (true, true) => "for signing and decryption",
134 (true, false) => "for signing",
135 (false, true) => "for decryption",
136 (false, false) => "unusable",
137 }
138 }
139 }
140
141 /// Returns information about a key.
142 ///
143 /// If key is `None`, then returns information about the certificate.
144 ///
145 /// The information that is returned is:
146 ///
147 /// - If the key is revoked, that it was revoked and why
148 /// - If the key is invalid, that it is invalid
149 fn key_validity(sq: &Sq, cert: &Cert, key: Option<&Fingerprint>) -> Vec<String> {
150 let revoked = |rs| {
151 if let RevocationStatus::Revoked(sigs) = rs {
152 let sig = sigs[0];
153 let mut reason_;
154 let reason = if let Some((reason, message))
155 = sig.reason_for_revocation()
156 {
157 // Be careful to quote the message it is
158 // controlled by the certificate holder.
159 reason_ = reason.to_string();
160 if ! message.is_empty() {
161 reason_.push_str(": ");
162 reason_.push_str(&ui::Safe(message).to_string());
163 }
164 &reason_
165 } else {
166 "no reason specified"
167 };
168
169 Some(format!(
170 "revoked on {}, {}",
171 sig.signature_creation_time()
172 .unwrap_or(std::time::UNIX_EPOCH)
173 .convert(),
174 reason))
175 } else {
176 None
177 }
178 };
179
180 let mut info = Vec::new();
181
182 if let Some(key) = key {
183 let ka = cert.keys().subkeys().find(|ka| &ka.key().fingerprint() == key)
184 .expect("key is associated with the certificate");
185
186 match ka.clone().with_policy(sq.policy, sq.time) {
187 Ok(ka) => {
188 if let Some(revoked) = revoked(ka.revocation_status()) {
189 info.push(revoked)
190 }
191
192 if let Some(t) = ka.key_expiration_time() {
193 if t < SystemTime::now() {
194 info.push(
195 format!("expired {}",
196 Time::try_from(t)
197 .expect("is an OpenPGP timestamp")))
198 } else {
199 info.push(
200 format!("will expire {}",
201 Time::try_from(t)
202 .expect("is an OpenPGP timestamp")))
203 }
204 }
205 }
206 Err(err) => {
207 if let Some(revoked)
208 = revoked(ka.revocation_status(sq.policy, sq.time))
209 {
210 info.push(revoked);
211 }
212
213 // Only print that it is invalid if the cert is valid.
214 // If the cert is invalid, then we already printed the
215 // information when showing the primary key.
216 if let Ok(_) = cert.with_policy(sq.policy, sq.time) {
217 info.push(format!(
218 "not valid: {}",
219 crate::one_line_error_chain(err)));
220 }
221 }
222 }
223 } else {
224 match cert.with_policy(sq.policy, sq.time) {
225 Ok(vc) => {
226 if let Some(revoked) = revoked(vc.revocation_status()) {
227 info.push(revoked)
228 }
229
230 if let Some(t) = vc.primary_key().key_expiration_time() {
231 if t < SystemTime::now() {
232 info.push(
233 format!("expired {}",
234 Time::try_from(t)
235 .expect("is an OpenPGP timestamp")))
236 } else {
237 info.push(
238 format!("will expire {}",
239 Time::try_from(t)
240 .expect("is an OpenPGP timestamp")))
241 }
242 }
243 }
244 Err(err) => {
245 if let Some(revoked)
246 = revoked(cert.revocation_status(sq.policy, sq.time))
247 {
248 info.push(revoked);
249 }
250
251 info.push(format!(
252 "not valid: {}",
253 crate::one_line_error_chain(err)));
254 }
255 }
256 }
257 info
258 }
259
260 pub fn list(sq: Sq, mut cmd: cli::key::list::Command) -> Result<()> {
261 let o = &mut std::io::stdout();
262
263 // Start and connect to the keystore.
264 let ks = sq.key_store_or_else()?;
265 let mut ks = ks.lock().unwrap();
266
267 if let Some(pattern) = cmd.pattern {
268 let mut d = None;
269 if let Ok(kh) = pattern.parse::<KeyHandle>() {
270 if matches!(kh, KeyHandle::Fingerprint(Fingerprint::Unknown { .. })) {
271 let hex = pattern.chars()
272 .map(|c| {
273 if c == ' ' { 0 } else { 1 }
274 })
275 .sum::<usize>();
276
277 if hex >= 16 {
278 weprintln!("Warning: {} looks like a fingerprint or key ID, \
279 but its invalid. Treating it as a text pattern.",
280 pattern);
281 }
282 } else {
283 d = Some(cert_designator::CertDesignator::Cert(kh));
284 }
285 };
286
287 cmd.certs.push(d.unwrap_or_else(|| {
288 cert_designator::CertDesignator::Grep(pattern)
289 }));
290 }
291
292 // First, collect information by iterating over the device tree.
293 //
294 // We want to display the information later grouped by OpenPGP
295 // certificate, and the key store doesn't provide that view.
296 let mut the_keys: BTreeMap<Association, BTreeMap<Fingerprint, KeyInfo>> =
297 Default::default();
298
299 // Keep track of whether we displayed something so that we can
300 // insert empty lines to provide some visual structure.
301 let mut dirty = false;
302
303 // Iterate over the tree. We only emit information about
304 // backends (and devices) that have no keys, as this may be
305 // information relevant for tracking down problems, and makes
306 // backends discoverable.
307 let mut backends = ks.backends()?;
308 for backend in &mut backends {
309 let devices = backend.devices()?;
310 if devices.len() == 0 {
311 wwriteln!(stream=o, initial_indent = " - ",
312 "Backend {} has no keys.",
313 backend.id()?);
314 dirty = true;
315 }
316
317 for mut device in devices {
318 let keys = device.keys()?;
319 if keys.len() == 0 {
320 wwriteln!(stream=o, initial_indent = " - ",
321 "Device {}/{} has no keys.",
322 backend.id()?, device.id()?);
323 dirty = true;
324 }
325
326 for mut key in keys.into_iter() {
327 let fpr = KeyHandle::from(key.fingerprint());
328
329 let location = Location {
330 backend: backend.id()?,
331 device: device.id()?,
332 available: key.available().unwrap_or(false),
333 protection: match key.locked() {
334 Ok(Protection::Unlocked) => "unlocked",
335 Ok(_) => "locked",
336 Err(_) => "unknown protection",
337 },
338 };
339
340 let associations = if let Ok(certs)
341 = sq.lookup(vec![&fpr], None, true, true)
342 {
343 certs.into_iter().map(|c| Association::Bound(c)).collect()
344 } else {
345 vec![Association::Bare(key.public_key().clone())]
346 };
347
348 for a in associations {
349 the_keys.entry(a).or_default()
350 .entry(key.fingerprint())
351 .or_insert_with(|| KeyInfo {
352 key: key.public_key().clone(),
353 locations: Vec::new(),
354 signing_capable:
355 key.signing_capable().unwrap_or(false),
356 decryption_capable:
357 key.decryption_capable().unwrap_or(false),
358 })
359 .locations.push(location.clone());
360 }
361 }
362 }
363 }
364
365 // Look up the certs. As we now know what keys we have, we can
366 // hand a filter to Sq::resolve_certs_filter to only look up keys.
367 let certs = if cmd.certs.is_empty() {
368 None
369 } else {
370 let have_keys: BTreeSet<_> =
371 the_keys.keys().map(|a| a.key().fingerprint()).collect();
372
373 // We use a trust threshold of YOLO, because these are not
374 // actually certificate designators, but filters.
375 let (certs, errors) = sq.resolve_certs_filter(
376 &cmd.certs, TrustThreshold::YOLO,
377 &mut |_, cert| {
378 let fp = cert.fingerprint();
379 have_keys.contains(&fp)
380 .then_some(())
381 .ok_or(anyhow::anyhow!("{} has no secret key material", fp))
382 })?;
383
384 for error in &errors {
385 crate::print_error_chain(error);
386 }
387 if ! errors.is_empty() {
388 return Err(anyhow::anyhow!("Failed to resolve keys"));
389 }
390
391 Some(certs
392 .into_iter()
393 .map(|c| c.fingerprint())
394 .collect::<BTreeSet<_>>())
395 };
396
397 // Now display the keys grouped by OpenPGP certificates.
398
399 let q = sq.wot_query();
400 let q = q.map(|q| q.build()).ok();
401 let authenticate = |cert: &Cert, userid: &UserID|
402 -> (usize, PreferredUserID)
403 {
404 if let Some(q) = q.as_ref() {
405 let paths = q.authenticate(
406 userid, &cert.fingerprint(), sequoia_wot::FULLY_TRUSTED);
407 let amount = paths.amount();
408 (amount, PreferredUserID::from_userid(userid.clone(), amount))
409 } else {
410 (0, PreferredUserID::from_userid(userid.clone(), 0))
411 }
412 };
413
414 for (association, keys) in the_keys.iter() {
415 if let Some(c) = &certs {
416 // Skip the keys the user is not interested in.
417 if ! c.contains(&association.key().fingerprint()) {
418 continue;
419 }
420 }
421
422 if dirty {
423 wwriteln!(stream=o);
424 }
425 dirty = true;
426
427 // Emit metadata.
428 wwriteln!(stream=o, initial_indent = " - ",
429 "{}", association.key().fingerprint());
430
431 // Show the user IDs that can be authenticated or are self signed.
432 if let Some(cert) = association.cert() {
433 // If we have any valid self signed user IDs, prefer
434 // those. Otherwise, fallback to those valid under the
435 // NULL policy. They won't be considered authenticated,
436 // but at least we'll show something.
437 let self_signed: HashSet<UserID> = if let Ok(vc)
438 = cert.with_policy(sq.policy, sq.time)
439 {
440 HashSet::from_iter(vc.userids().map(|ua| ua.userid()).cloned())
441 } else if let Ok(vc)
442 = cert.with_policy(NULL_POLICY, sq.time)
443 {
444 HashSet::from_iter(vc.userids().map(|ua| ua.userid()).cloned())
445 } else {
446 Default::default()
447 };
448
449 let mut userids = Vec::with_capacity(cert.userids().count());
450 for ua in cert.userids() {
451 let revoked = if let RevocationStatus::Revoked(_)
452 = ua.revocation_status(sq.policy, sq.time)
453 {
454 true
455 } else {
456 false
457 };
458
459 let self_signed = self_signed.contains(&ua.userid());
460
461 let (amount, userid) = authenticate(cert, ua.userid());
462 if amount > 0 || self_signed {
463 userids.push((revoked, amount, self_signed, userid));
464 }
465 }
466
467 if userids.is_empty() {
468 wwriteln!(stream=o, initial_indent = " - ", "no user IDs");
469 } else {
470 let userid_count = userids.len();
471 if userid_count > 1 {
472 wwriteln!(stream=o, initial_indent = " - ", "user IDs:");
473 }
474
475 userids.sort_by(
476 |(a_revoked, a_amount, a_self_signed, a_userid),
477 (b_revoked, b_amount, b_self_signed, b_userid) |
478 {
479 a_revoked.cmp(b_revoked)
480 .then(a_amount.cmp(b_amount).reverse())
481 .then(a_self_signed.cmp(b_self_signed))
482 .then(a_userid.cmp(b_userid))
483 });
484 for (revoked, amount, self_signed, userid)
485 in userids.into_iter()
486 {
487 if amount > 0 || self_signed {
488 if userid_count == 1 {
489 wwriteln!(stream=o, initial_indent = " - ", "user ID: {}{}",
490 userid.display(),
491 if revoked { " revoked" } else { "" });
492 } else {
493 wwriteln!(stream=o, initial_indent = " - ", "{}{}",
494 userid.display(),
495 if revoked { " revoked" } else { "" });
496 }
497 }
498 }
499 }
500 }
501 wwriteln!(stream=o, initial_indent = " - ", "created {}",
502 association.key().creation_time().convert());
503
504 if let Some(cert) = association.cert() {
505 for info in key_validity(&sq, cert, None).into_iter() {
506 wwriteln!(stream=o, initial_indent = " - ", "{}", info);
507 }
508 }
509
510 // Primary key information, if any.
511 if let Some(primary) = keys.get(&association.key().fingerprint()) {
512 wwriteln!(stream=o, initial_indent = " - ", "usable {}", primary.usable_for());
513 for loc in &primary.locations {
514 wwriteln!(stream=o, initial_indent = " - ", "{}", loc);
515 }
516 }
517
518 // Subkey information, if any.
519 for (i, (fp, key)) in keys.iter()
520 .filter(|(fp, _)| **fp != association.key().fingerprint())
521 .enumerate()
522 {
523 if i == 0 {
524 wwriteln!(stream=o);
525 }
526
527 wwriteln!(stream=o, initial_indent = " - ", "{}", fp);
528 wwriteln!(stream=o, initial_indent = " - ", "created {}",
529 key.key.creation_time().convert());
530
531 if let Some(cert) = association.cert() {
532 for info in key_validity(&sq, cert, Some(fp)).into_iter() {
533 wwriteln!(stream=o, initial_indent = " - ", "{}", info);
534 }
535 }
536
537 wwriteln!(stream=o, initial_indent = " - ", "usable {}", key.usable_for());
538 for loc in &key.locations {
539 wwriteln!(stream=o, initial_indent = " - ", "{}", loc);
540 }
541 }
542 }
543
544 // Add some helpful guidance if there aren't any keys.
545 if the_keys.is_empty() {
546 let mut hint = sq.hint(format_args!(
547 "There are no secret keys."));
548
549 if sq.key_store_path.is_some()
550 || ! sq.home.as_ref()
551 .map(|h| h.is_default_location()).unwrap_or(false)
552 {
553 hint = hint.hint(format_args!(
554 "The non-default key store location {} is selected \
555 using the `{}` option. Consider using the default \
556 key store location to access your keys.",
557 sq.key_store_path()?.unwrap().display(),
558 if sq.key_store_path.is_some() {
559 "--key-store"
560 } else {
561 "--home"
562 }));
563 }
564
565 hint.hint(format_args!(
566 "Consider generating a new key like so:"))
567 .sq().arg("key").arg("generate").arg("--own-key")
568 .arg_value("--name", "Juliet Capulet")
569 .arg_value("--email", "[email protected]")
570 .done()
571 .hint(format_args!(
572 "Or, you can import an existing key:"))
573 .sq().arg("key").arg("import")
574 .arg("juliets-secret-key.pgp")
575 .done();
576
577 sq.hint(format_args!(
578 "Sequoia calls public keys 'certificates'. \
579 Perhaps you meant to list known certificates, \
580 which can be done using:"))
581 .sq().arg("cert").arg("list").done();
582 }
583
584 Ok(())
585 }