Debian Codegraph @

src/commands/inspect.rs

raw
1 use std::convert::TryFrom;
2 use std::fmt;
3 use std::io::{self, Read};
4 use std::path::Path;
5 use std::time::Duration;
6
7 use anyhow::Context;
8
9 use buffered_reader::{BufferedReader, Dup};
10
11 use sequoia_openpgp as openpgp;
12 use openpgp::{Fingerprint, KeyHandle, Packet, Result};
13 use openpgp::armor::ReaderMode;
14 use openpgp::cert::prelude::*;
15 use openpgp::packet::{
16 Signature,
17 key::PublicParts,
18 };
19 use openpgp::parse::{
20 Cookie,
21 Dearmor,
22 Parse,
23 PacketParserBuilder,
24 PacketParserResult,
25 };
26 use openpgp::policy::{Policy, HashAlgoSecurity};
27 use openpgp::packet::key::SecretKeyMaterial;
28 use openpgp::types::{
29 KeyFlags,
30 ReasonForRevocation,
31 SignatureType,
32 };
33 use openpgp::serialize::Serialize;
34
35 use crate::Convert;
36
37 use crate::Sq;
38 use crate::one_line_error_chain;
39 use crate::SECONDS_IN_YEAR;
40 use crate::SECONDS_IN_DAY;
41
42 use crate::cli::inspect;
43 use crate::cli::types::FileOrStdout;
44 use crate::commands::packet::dump::PacketDumper;
45 use crate::common::NULL_POLICY;
46 use crate::common::PreferredUserID;
47 use crate::common::ui;
48 use crate::sq::TrustThreshold;
49
50 /// Width of the largest key of any key, value pair we emit.
51 const WIDTH: usize = 17;
52
53 pub fn dispatch(mut sq: Sq, c: inspect::Command)
54 -> Result<()>
55 {
56 // sq inspect does not have --output, but commands::inspect does.
57 // Work around this mismatch by always creating a stdout output.
58 let output_type = FileOrStdout::default();
59 let output = &mut output_type.create_unsafe(&sq)?;
60
61 let print_certifications = c.certifications;
62
63 let input = c.input;
64 let dump_bad_signatures = c.dump_bad_signatures;
65
66 let mut bytes: Vec<u8> = Vec::new();
67 if c.certs.is_empty() {
68 if let Some(path) = input.inner() {
69 if ! path.exists() &&
70 format!("{}", input).parse::<KeyHandle>().is_ok()
71 {
72 weprintln!("The file {} does not exist, \
73 did you mean \"sq inspect --cert {}\"?",
74 input, input);
75 }
76 }
77
78 inspect(&mut sq, input.open("OpenPGP or autocrypt data")?,
79 Some(&input.to_string()), output,
80 print_certifications, dump_bad_signatures)?;
81 } else {
82 for cert in sq.resolve_certs_or_fail(&c.certs, TrustThreshold::Full)? {
83 // Include non-exportable signatures, etc.
84 cert.serialize(&mut bytes).context("Serializing certificate")?;
85 }
86
87 let br = buffered_reader::Memory::with_cookie(
88 &bytes, sequoia_openpgp::parse::Cookie::default());
89 inspect(&mut sq, br, None, output,
90 print_certifications, dump_bad_signatures)?;
91 }
92
93 Ok(())
94 }
95
96 /// Inspects OpenPGP data.
97 ///
98 /// The data is read from `input`. `input_filename` is the name of
99 /// the file, if available. This is only used for display purposes.
100 /// The output is written to `output`.
101 ///
102 /// If `print_certifications` is set, also shows information about
103 /// certifications.
104 pub fn inspect<'a, R>(sq: &mut Sq,
105 input: R,
106 input_filename: Option<&str>,
107 output: &mut Box<dyn std::io::Write + Send + Sync>,
108 print_certifications: bool,
109 dump_bad_signatures: bool)
110 -> Result<Kind>
111 where
112 R: BufferedReader<sequoia_openpgp::parse::Cookie> + 'a,
113 {
114 let mut ppr =
115 match openpgp::parse::PacketParser::from_buffered_reader(input)
116 {
117 Ok(pp) => pp,
118 Err(e) => if e.downcast_ref()
119 .map(|e: &io::Error| e.kind() == io::ErrorKind::UnexpectedEof)
120 .unwrap_or(false)
121 {
122 if let Some(input_filename) = input_filename {
123 write!(output, "{}: ", input_filename)?;
124 }
125
126 writeln!(output, "No OpenPGP data.")?;
127 return Ok(Kind::NotOpenPGP);
128 } else {
129 return Err(e);
130 }
131 };
132
133 let mut type_called = None; // Did we print the type yet?
134
135 loop {
136 if let Some(input_filename) = input_filename {
137 write!(output, "{}: ", input_filename)?;
138 }
139
140 let mut encrypted = false; // Is it an encrypted message?
141 let mut packets = Vec::new(); // Accumulator for packets.
142 let mut pkesks = Vec::new(); // Accumulator for PKESKs.
143 let mut n_skesks = 0; // Number of SKESKs.
144 let mut sigs = Vec::new(); // Accumulator for signatures.
145 let mut literal_prefix = Vec::new();
146
147 while let PacketParserResult::Some(mut pp) = ppr {
148 match pp.packet {
149 Packet::PublicKey(_) | Packet::SecretKey(_) => {
150 if pp.possible_cert().is_err()
151 && pp.possible_keyring().is_ok()
152 {
153 if type_called.is_none() {
154 writeln!(output, "OpenPGP Keyring.")?;
155 writeln!(output)?;
156 type_called = Some(Kind::Keyring);
157 }
158 let pp = openpgp::PacketPile::from(
159 std::mem::take(&mut packets));
160 let cert = openpgp::Cert::try_from(pp)?;
161 inspect_cert(
162 sq,
163 output,
164 &cert,
165 print_certifications,
166 dump_bad_signatures,
167 )?;
168 }
169 },
170 Packet::Literal(_) => {
171 pp.by_ref().take(40).read_to_end(&mut literal_prefix)?;
172 },
173 Packet::SEIP(_) => {
174 encrypted = true;
175 },
176 _ => (),
177 }
178
179 let possible_keyring = pp.possible_keyring().is_ok();
180 let (packet, ppr_) = pp.recurse()?;
181 ppr = ppr_;
182
183 match packet {
184 Packet::PKESK(p) => pkesks.push(p),
185 Packet::SKESK(_) => n_skesks += 1,
186 Packet::Signature(s) => if possible_keyring {
187 packets.push(Packet::Signature(s))
188 } else {
189 sigs.push(s)
190 },
191 _ => packets.push(packet),
192 }
193 }
194
195 if let PacketParserResult::EOF(eof) = ppr {
196 let is_message = eof.is_message();
197 let is_cert = eof.is_cert();
198 let is_keyring = eof.is_keyring();
199
200 // Now, the parser is exhausted, but we may find another
201 // armored blob. Note that this can only happen if the first
202 // set of packets was also armored.
203 let next_ppr =
204 PacketParserBuilder::from_buffered_reader(eof.into_reader())
205 .and_then(
206 |builder| builder
207 .dearmor(Dearmor::Enabled(
208 ReaderMode::Tolerant(None)))
209 .build());
210
211 if is_message.is_ok() {
212 type_called = if encrypted {
213 Some(Kind::EncryptedMessage)
214 } else {
215 Some(Kind::SignedMessage)
216 };
217
218 writeln!(output, "{}OpenPGP Message.",
219 match (encrypted, ! sigs.is_empty()) {
220 (false, false) => "",
221 (false, true) => "Signed ",
222 (true, false) => "Encrypted ",
223 (true, true) => "Encrypted and signed ",
224 })?;
225 writeln!(output)?;
226 if n_skesks > 0 {
227 writeln!(output, " Passwords: {}", n_skesks)?;
228 }
229 for pkesk in pkesks.iter() {
230 writeln!(output, " Recipient: {}",
231 pkesk.recipient().as_ref().map(ToString::to_string)
232 .unwrap_or_else(|| "<anonymous recipient>".into()))?;
233
234 let recipient = if let Some(r) = pkesk.recipient() {
235 r
236 } else {
237 continue;
238 };
239
240 // Lookup the certificate, if possible. Prefer a
241 // binding that is valid according to the current
242 // policy. Otherwise, fall back to the NULL policy.
243 if let Ok(certs) = sq.lookup(Some(&recipient),
244 None, true, true)
245 .or_else(|_| {
246 sq.lookup_with_policy(
247 Some(recipient),
248 None, true, true,
249 NULL_POLICY, sq.time)
250 })
251 {
252 if certs.len() == 1 {
253 writeln!(output, " Associated certificate:")?;
254 } else {
255 writeln!(output, " Associated certificates:")?;
256 }
257
258 for cert in certs {
259 writeln!(output, " {}",
260 cert.fingerprint())?;
261 writeln!(output, " {}",
262 sq.best_userid(&cert, true).display())?;
263 }
264 } else {
265 writeln!(output, " Associated certificate not available")?;
266 }
267 }
268 inspect_signatures(sq, output, &sigs)?;
269 if ! literal_prefix.is_empty() {
270 writeln!(output, " Data: {}{}",
271 ui::Safe(&literal_prefix),
272 if literal_prefix.len() == 40 { "..." } else { "" })?;
273 }
274
275 } else if is_cert.is_ok() || is_keyring.is_ok() {
276 let pp = openpgp::PacketPile::from(packets);
277 let cert = openpgp::Cert::try_from(pp)?;
278
279 type_called = if is_cert.is_ok() {
280 if cert.is_tsk() {
281 Some(Kind::Key)
282 } else {
283 Some(Kind::Cert)
284 }
285 } else {
286 Some(Kind::Keyring)
287 };
288
289 inspect_cert(sq, output, &cert, print_certifications,
290 dump_bad_signatures)?;
291 } else if packets.is_empty() && ! sigs.is_empty() {
292 if sigs.iter().all(is_revocation_sig) {
293 type_called = Some(Kind::RevocationCert);
294 writeln!(output, "Revocation Certificate{}.",
295 if sigs.len() > 1 { "s" } else { "" })?;
296 writeln!(output)?;
297 for sig in sigs {
298 inspect_bare_revocation(sq, output, &sig)?;
299 }
300 writeln!(output, " Note: \
301 Signatures have NOT been verified!")?;
302 } else {
303 type_called = Some(Kind::DetachedSig);
304 writeln!(output, "Detached signature{}.",
305 if sigs.len() > 1 { "s" } else { "" })?;
306 writeln!(output)?;
307 inspect_signatures(sq, output, &sigs)?;
308 }
309 } else if packets.is_empty() {
310 type_called = Some(Kind::NotOpenPGP);
311 writeln!(output, "No OpenPGP data.")?;
312 } else {
313 type_called = Some(Kind::Unknown);
314 writeln!(output, "Unknown sequence of OpenPGP packets.")?;
315 writeln!(output, " Message: {}", is_message.as_ref().unwrap_err())?;
316 writeln!(output, " Cert: {}", is_cert.as_ref().unwrap_err())?;
317 writeln!(output, " Keyring: {}", is_keyring.as_ref().unwrap_err())?;
318 writeln!(output)?;
319 if let Some(filename) = input_filename {
320 writeln!(output, "Hint: Try 'sq packet dump {}'",
321 filename)?;
322 }
323 }
324
325 // See if there is another armor block.
326 match next_ppr {
327 Ok(ppr_) => {
328 writeln!(output, "Note: There is another block of armored \
329 OpenPGP data.")?;
330
331 if is_message.is_ok() {
332 type_called = Some(Kind::NotOpenPGP);
333 writeln!(output, "Note: Data concatenated to a message is \
334 likely an error.")?;
335 } else if is_cert.is_ok() || is_keyring.is_ok() {
336 type_called = Some(Kind::Keyring);
337 writeln!(output, "Note: This is a non-standard extension \
338 to OpenPGP.")?;
339 }
340 writeln!(output)?;
341
342 ppr = ppr_;
343 continue;
344 },
345 Err(_) => break,
346 }
347 } else {
348 unreachable!()
349 }
350 }
351
352 Ok(type_called.unwrap_or(Kind::Unknown))
353 }
354
355 /// Returns true iff all signatures in the cert are revocation
356 /// signatures.
357 fn is_revocation_sig(s: &Signature) -> bool {
358 [
359 SignatureType::KeyRevocation,
360 SignatureType::SubkeyRevocation,
361 SignatureType::CertificationRevocation,
362 ].contains(&s.typ())
363 }
364
365 /// Returns true iff all signatures in the cert are revocation
366 /// signatures.
367 fn is_revocation_cert(c: &Cert) -> bool {
368 c.primary_key().signatures().all(|s| s.typ() == SignatureType::KeyRevocation)
369 && c.keys().subkeys().all(|skb| skb.signatures().all(
370 |s| s.typ() == SignatureType::SubkeyRevocation))
371 && c.userids().all(|uidb| uidb.signatures().all(
372 |s| s.typ() == SignatureType::CertificationRevocation))
373 }
374
375 fn inspect_cert(
376 sq: &mut Sq,
377 output: &mut dyn io::Write,
378 cert: &openpgp::Cert,
379 print_certifications: bool,
380 dump_bad_signatures: bool,
381 ) -> Result<()> {
382 if cert.is_tsk() {
383 writeln!(output, "Transferable Secret Key.")?;
384 } else if is_revocation_cert(&cert) {
385 writeln!(output, "Revocation Certificate.")?;
386 } else {
387 writeln!(output, "OpenPGP Certificate.")?;
388 }
389 writeln!(output)?;
390 writeln!(output, "{:>WIDTH$}: {}", "Fingerprint", cert.fingerprint())?;
391 inspect_revocation(output, cert.revocation_status(sq.policy, sq.time))?;
392 inspect_key(
393 sq,
394 output,
395 cert.keys().next().unwrap(),
396 print_certifications,
397 )?;
398 writeln!(output)?;
399
400 for skb in cert.keys().subkeys() {
401 writeln!(output, "{:>WIDTH$}: {}", "Subkey", skb.key().fingerprint())?;
402 inspect_revocation(output, skb.revocation_status(sq.policy, sq.time))?;
403 match skb.binding_signature(sq.policy, sq.time) {
404 Ok(sig) => {
405 if let Err(e) = sig.signature_alive(sq.time, Duration::new(0, 0)) {
406 print_error_chain(output, &e)?;
407 }
408 }
409 Err(e) => print_error_chain(output, &e)?,
410 }
411 inspect_key(
412 sq,
413 output,
414 skb.into(),
415 print_certifications,
416 )?;
417 writeln!(output)?;
418 }
419
420 fn print_error_chain(output: &mut dyn io::Write, err: &anyhow::Error)
421 -> Result<()> {
422 writeln!(output, "{:>WIDTH$} Invalid: {}", "", err)?;
423 for cause in err.chain().skip(1) {
424 writeln!(output, "{:>WIDTH$} because: {}", "", cause)?;
425 }
426 Ok(())
427 }
428
429 for uidb in cert.userids() {
430 writeln!(output, "{:>WIDTH$}: {}", "UserID", uidb.userid())?;
431 inspect_revocation(output, uidb.revocation_status(sq.policy, sq.time))?;
432 match uidb.binding_signature(sq.policy, sq.time) {
433 Ok(sig) => {
434 if let Err(e) = sig.signature_alive(sq.time, Duration::new(0, 0)) {
435 print_error_chain(output, &e)?;
436 }
437 }
438 Err(e) => print_error_chain(output, &e)?,
439 }
440 inspect_certifications(sq, output,
441 uidb.certifications(),
442 print_certifications)?;
443 writeln!(output)?;
444 }
445
446 for uab in cert.user_attributes() {
447 writeln!(output, "{:>WIDTH$}: {:?}", "User attribute",
448 uab.user_attribute())?;
449 inspect_revocation(output, uab.revocation_status(sq.policy, sq.time))?;
450 match uab.binding_signature(sq.policy, sq.time) {
451 Ok(sig) => {
452 if let Err(e) = sig.signature_alive(sq.time, Duration::new(0, 0)) {
453 print_error_chain(output, &e)?;
454 }
455 }
456 Err(e) => print_error_chain(output, &e)?,
457 }
458 inspect_certifications(sq, output,
459 uab.certifications(),
460 print_certifications)?;
461 writeln!(output)?;
462 }
463
464 for ub in cert.unknowns() {
465 writeln!(output, "{:>WIDTH$}: {:?}", "Unknown component",
466 ub.unknown())?;
467 match ub.binding_signature(sq.policy, sq.time) {
468 Ok(sig) => {
469 if let Err(e) = sig.signature_alive(sq.time, Duration::new(0, 0)) {
470 print_error_chain(output, &e)?;
471 }
472 }
473 Err(e) => print_error_chain(output, &e)?,
474 }
475 inspect_certifications(sq, output,
476 ub.certifications(),
477 print_certifications)?;
478 writeln!(output)?;
479 }
480
481 if cert.bad_signatures().next().is_some() {
482 if dump_bad_signatures {
483 let width = terminal_size::terminal_size()
484 .map(|(w, _)| w.0.into());
485
486 let pd = PacketDumper::new(sq, width.unwrap_or(80), false);
487 for bad in cert.bad_signatures() {
488 writeln!(output, "{:>WIDTH$}:", "Bad Signature")?;
489 pd.dump_signature(output, &format!("{:>WIDTH$}", ""), bad)?;
490 }
491 } else {
492 writeln!(output, "{:>WIDTH$}: {}, use --dump-bad-signatures to list",
493 "Bad Signatures", cert.bad_signatures().count())?;
494 }
495 }
496
497 Ok(())
498 }
499
500 fn inspect_key(
501 sq: &mut Sq,
502 output: &mut dyn io::Write,
503 ka: ErasedKeyAmalgamation<PublicParts>,
504 print_certifications: bool,
505 ) -> Result<()> {
506 let key = ka.key();
507 let bundle = ka.bundle();
508
509 let vka = match ka.with_policy(sq.policy, sq.time) {
510 Ok(vka) => {
511 if let Err(e) = vka.alive() {
512 writeln!(output, "{:>WIDTH$} Invalid: {}", "",
513 one_line_error_chain(&e))?;
514 }
515 Some(vka)
516 },
517 Err(e) => {
518 writeln!(output, "{:>WIDTH$} Invalid: {}", "",
519 one_line_error_chain(&e))?;
520 None
521 },
522 };
523
524 writeln!(output, "{:>WIDTH$}: {}", "Public-key algo", key.pk_algo())?;
525 if let Some(bits) = key.mpis().bits() {
526 writeln!(output, "{:>WIDTH$}: {} bits", "Public-key size", bits)?;
527 }
528 if let Some(secret) = key.optional_secret() {
529 writeln!(output, "{:>WIDTH$}: {}", "Secret key",
530 if let SecretKeyMaterial::Unencrypted(_) = secret {
531 "Unencrypted"
532 } else {
533 "Encrypted"
534 })?;
535 }
536 writeln!(output, "{:>WIDTH$}: {}", "Creation time",
537 key.creation_time().convert())?;
538 if let Some(vka) = vka {
539 if let Some(expires) = vka.key_validity_period() {
540 let expiration_time = key.creation_time() + expires;
541 writeln!(output, "{:>WIDTH$}: {} (creation time + {})",
542 "Expiration time",
543 expiration_time.convert(),
544 expires.convert())?;
545 }
546
547 if let Some(flags) = vka.key_flags().and_then(inspect_key_flags) {
548 writeln!(output, "{:>WIDTH$}: {}", "Key flags", flags)?;
549 }
550 }
551 inspect_certifications(sq, output,
552 bundle.certifications(),
553 print_certifications)?;
554
555 Ok(())
556 }
557
558 /// Prints the revocation reasons.
559 fn print_reasons(output: &mut dyn io::Write,
560 third_party: bool, sigs: &[&Signature])
561 -> Result<()> {
562 for sig in sigs {
563 let (reason, message) = sig.reason_for_revocation()
564 .map(|(r, m)| (r, Some(m)))
565 .unwrap_or((ReasonForRevocation::Unspecified, None));
566
567 writeln!(output, "{:>WIDTH$} - {}", "", reason)?;
568 writeln!(output, "{:>WIDTH$} On: {}", "",
569 sig.signature_creation_time()
570 .expect("valid sigs have one").convert())?;
571 if third_party {
572 writeln!(output, "{:>WIDTH$} Issued by{}", "",
573 if let Some(issuer)
574 = sig.get_issuers().into_iter().next()
575 {
576 format!(": {}", issuer)
577 } else {
578 " an unknown certificate".into()
579 })?;
580 }
581 if let Some(msg) = message {
582 writeln!(output, "{:>WIDTH$} Message: {}", "",
583 ui::Safe(msg))?;
584 }
585 }
586 Ok(())
587 }
588
589 fn inspect_revocation(output: &mut dyn io::Write,
590 revoked: openpgp::types::RevocationStatus)
591 -> Result<()> {
592 use openpgp::types::RevocationStatus::*;
593
594 match revoked {
595 Revoked(sigs) => {
596 writeln!(output, "{:>WIDTH$} Revoked:", "")?;
597 print_reasons(output, false, &sigs)?;
598 },
599 CouldBe(sigs) => {
600 writeln!(output, "{:>WIDTH$} Possibly revoked:", "")?;
601 print_reasons(output, true, &sigs)?;
602 },
603 NotAsFarAsWeKnow => (),
604 }
605
606 Ok(())
607 }
608
609 fn inspect_bare_revocation(sq: &mut Sq,
610 output: &mut dyn io::Write, sig: &Signature)
611 -> Result<()> {
612 inspect_issuers(sq, output, &sig)?;
613 writeln!(output, "{:>WIDTH$} Possible revocation:", "")?;
614 print_reasons(output, false, &[sig])?;
615 writeln!(output)?;
616 Ok(())
617 }
618
619 fn inspect_key_flags(flags: openpgp::types::KeyFlags) -> Option<String> {
620 let mut capabilities = Vec::new();
621 if flags.for_certification() {
622 capabilities.push("certification")
623 }
624 if flags.for_signing() {
625 capabilities.push("signing")
626 }
627 if flags.for_authentication() {
628 capabilities.push("authentication")
629 }
630 if flags.for_transport_encryption() {
631 capabilities.push("transport encryption")
632 }
633 if flags.for_storage_encryption() {
634 capabilities.push("data-at-rest encryption")
635 }
636 if flags.is_group_key() {
637 capabilities.push("group key")
638 }
639 if flags.is_split_key() {
640 capabilities.push("split key")
641 }
642
643 if !capabilities.is_empty() {
644 Some(capabilities.join(", "))
645 } else {
646 None
647 }
648 }
649
650 fn inspect_signatures(sq: &mut Sq,
651 output: &mut dyn io::Write,
652 sigs: &[openpgp::packet::Signature]) -> Result<()> {
653 use openpgp::types::SignatureType::*;
654 for sig in sigs {
655 match sig.typ() {
656 Binary | Text => (),
657 signature_type =>
658 writeln!(output, "{:>WIDTH$}: {}", "Kind", signature_type)?,
659 }
660
661 inspect_issuers(sq, output, &sig)?;
662 }
663 if ! sigs.is_empty() {
664 writeln!(output, "{:>WIDTH$}: {}", "Note",
665 "Signatures have NOT been verified!")?;
666 }
667
668 Ok(())
669 }
670
671 fn inspect_issuers(sq: &mut Sq,
672 output: &mut dyn io::Write,
673 sig: &Signature) -> Result<()> {
674 emit_issuers(sq, |id| match id {
675 Ok((kh, uid)) => {
676 writeln!(output, "{:>WIDTH$}: {}", "Alleged signer", kh)?;
677 writeln!(output, "{:>WIDTH$} {}", "", uid.display())?;
678 Ok(())
679 },
680 Err((kh, _, _)) => {
681 writeln!(output, "{:>WIDTH$}: {}", "Alleged signer",
682 "signer's cert not found")?;
683 writeln!(output, "{:>WIDTH$} {}", "", kh)?;
684 writeln!(output, "{:>WIDTH$} {}", "", "(signature subkey)")?;
685 Ok(())
686 },
687 }, sig)
688 }
689
690 fn emit_issuers<F>(sq: &mut Sq, mut emit: F, sig: &Signature)
691 -> Result<()>
692 where
693 F: FnMut(std::result::Result<(Fingerprint, PreferredUserID),
694 (KeyHandle, PreferredUserID, anyhow::Error)>)
695 -> Result<()>,
696 {
697 let for_signing = KeyFlags::empty().set_signing();
698
699 let mut fps: Vec<_> = sig.issuer_fingerprints().collect();
700 fps.sort();
701 fps.dedup();
702 let khs: Vec<KeyHandle> = fps.into_iter().map(|fp| fp.into()).collect();
703 for kh in khs.iter() {
704 match sq.best_userid_for(kh, for_signing.clone(), true) {
705 (puid, Ok(cert)) => emit(Ok((cert.fingerprint(), puid)))?,
706 (puid, Err(e)) => emit(Err((kh.clone(), puid, e)))?,
707 }
708 }
709
710 let mut keyids: Vec<_> = sig.issuers().collect();
711 keyids.sort();
712 keyids.dedup();
713 for keyid in keyids {
714 let keyid = keyid.into();
715 if ! khs.iter().any(|kh| kh.aliases(&keyid)) {
716 match sq.best_userid_for(&keyid, for_signing.clone(), true) {
717 (puid, Ok(cert)) => emit(Ok((cert.fingerprint(), puid)))?,
718 (puid, Err(e)) => emit(Err((keyid, puid, e)))?,
719 }
720 }
721 }
722
723 Ok(())
724 }
725
726 fn inspect_certifications<'a, A>(sq: &mut Sq,
727 output: &mut dyn io::Write,
728 certs: A,
729 print_certifications: bool)
730 -> Result<()>
731 where A: std::iter::Iterator<Item=&'a openpgp::packet::Signature>
732 {
733 if print_certifications {
734 let mut emit_warning = false;
735 for sig in certs {
736 let time = if let Some(time) = sig.signature_creation_time() {
737 chrono::DateTime::<chrono::offset::Utc>::from(time)
738 } else {
739 // A signature must have a signature creation time
740 // subpacket to be valid. This signature is not
741 // valid, so skip it.
742 continue;
743 };
744
745 emit_warning = true;
746
747 writeln!(output, "{:>WIDTH$}: Creation time: {}", "Certification",
748 time)?;
749
750 if let Some(e) = sig.signature_expiration_time() {
751 let e = chrono::DateTime::<chrono::offset::Utc>::from(e);
752 let diff = e - time;
753 let years = diff.num_seconds() / (SECONDS_IN_YEAR as i64);
754 let rest = diff.num_seconds() - years * (SECONDS_IN_YEAR as i64);
755 let days = rest / (SECONDS_IN_DAY as i64);
756 let rest = rest - days * (SECONDS_IN_DAY as i64);
757
758 writeln!(output, "{:>WIDTH$} Expiration time: {} (after {}{}{}{}{})",
759 "",
760 e,
761 match years {
762 0 => "".into(),
763 1 => format!("{} year", years),
764 _ => format!("{} years", years),
765 },
766 if years != 0 && days != 0 { ", " } else { "" },
767 match days {
768 0 => "".into(),
769 1 => format!("{} day", days),
770 _ => format!("{} days", days),
771 },
772 if years == 0 && days != 0 && rest != 0 { ", " } else { "" },
773 if years == 0 {
774 match rest {
775 0 => "".into(),
776 1 => format!("{} second", rest),
777 _ => format!("{} seconds", rest),
778 }
779 } else {
780 "".into()
781 })?;
782 }
783
784 if let Some((depth, amount)) = sig.trust_signature() {
785 writeln!(output, "{:>WIDTH$} Trust depth: {}", "",
786 depth)?;
787 writeln!(output, "{:>WIDTH$} Trust amount: {}", "",
788 amount)?;
789 }
790 for re in sig.regular_expressions() {
791 if let Ok(re) = String::from_utf8(re.to_vec()) {
792 writeln!(output, "{:>WIDTH$} Regular expression: {}", "",
793 ui::Safe(re))?;
794 } else {
795 writeln!(output,
796 "{:>WIDTH$} Regular expression (invalid UTF-8): {}",
797 "",
798 ui::Safe(re))?;
799 }
800 }
801
802 emit_issuers(sq, |id| match id {
803 Ok((kh, uid)) => {
804 writeln!(output, "{:>WIDTH$} Alleged certifier: {}",
805 "", kh)?;
806 writeln!(output, "{:>WIDTH$} {}", "", uid.display())?;
807 Ok(())
808 },
809 Err((kh, _, _)) => {
810 writeln!(output, "{:>WIDTH$} Alleged certifier: {}",
811 "", "signer's cert not found")?;
812 writeln!(output, "{:>WIDTH$} {}", "", kh)?;
813 writeln!(output, "{:>WIDTH$} {}", "", "(signature subkey)")?;
814 Ok(())
815 },
816 }, sig)?;
817
818 writeln!(output, "{:>WIDTH$} Hash algorithm: {}",
819 "", sig.hash_algo())?;
820 if let Err(err) = sq.policy.signature(
821 sig, HashAlgoSecurity::CollisionResistance)
822 {
823 writeln!(output,
824 "{:>WIDTH$} Certification is not valid according to \
825 the current policy:", "")?;
826 writeln!(output, "{:>WIDTH$} {}", "",
827 one_line_error_chain(&err))?;
828 }
829 }
830 if emit_warning {
831 writeln!(output,
832 "{:>WIDTH$}: Certifications have NOT been verified!",
833 "Note")?;
834 }
835 } else {
836 let count = certs.count();
837 if count > 0 {
838 writeln!(output, "{:>WIDTH$}: {}, use --certifications to list",
839 "Certifications", count)?;
840 }
841 }
842
843 Ok(())
844 }
845
846 /// Describes the data that `inspect` inspected.
847 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
848 pub enum Kind {
849 /// A certificate.
850 Cert,
851
852 /// A key.
853 Key,
854
855 /// A keyring.
856 Keyring,
857
858 /// A signed message.
859 SignedMessage,
860
861 /// An encrypted message.
862 EncryptedMessage,
863
864 /// A detached signature.
865 DetachedSig,
866
867 /// A revocation certificate.
868 RevocationCert,
869
870 /// Unknown packet sequence.
871 Unknown,
872
873 /// Data that could not be parsed as OpenPGP packets.
874 NotOpenPGP,
875 }
876
877 impl fmt::Display for Kind {
878 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
879 match self {
880 Kind::Cert =>
881 f.write_str("a certificate"),
882
883 Kind::Key =>
884 f.write_str("a key"),
885
886 Kind::Keyring =>
887 f.write_str("a keyring"),
888
889 Kind::SignedMessage =>
890 f.write_str("a signed message"),
891
892 Kind::EncryptedMessage =>
893 f.write_str("an encrypted message"),
894
895 Kind::DetachedSig =>
896 f.write_str("a detached signature"),
897
898 Kind::RevocationCert =>
899 f.write_str("a revocation certificate"),
900
901 Kind::Unknown =>
902 f.write_str("an unknown packet sequence"),
903
904 Kind::NotOpenPGP =>
905 f.write_str("non-OpenPGP data"),
906 }
907 }
908 }
909
910 impl Kind {
911 /// Identifies OpenPGP data.
912 ///
913 /// Returns the kind and the original reader without any data
914 /// consumed.
915 pub fn identify<'a, T>(sq: &mut Sq, input: T)
916 -> Result<(Kind, Box<dyn BufferedReader<Cookie> + 'a>)>
917 where
918 T: BufferedReader<Cookie> + 'a,
919 {
920 let mut sink: Box<dyn io::Write + Send + Sync> =
921 Box::new(io::Sink::default());
922 let mut dup = Dup::with_cookie(input, Default::default());
923 let kind = inspect(sq, &mut dup, None, &mut sink, false, false)?;
924 Ok((kind, dup.into_boxed().into_inner().unwrap()))
925 }
926
927 /// Checks that `self` matches `expected`, or prints hints on what
928 /// to do instead and returns an error.
929 pub fn expect_or_else(&self,
930 sq: &Sq,
931 command: &str,
932 expected: Kind,
933 input_arg: &str,
934 input_path: Option<&Path>)
935 -> Result<()>
936 {
937 if self != &expected {
938 let input_path_text =
939 input_path.as_ref().map(|p| p.display().to_string())
940 .unwrap_or_else(|| "stdin".into());
941 let input_path_arg =
942 input_path.map(|p| p.display().to_string())
943 .unwrap_or_else(|| "-".into());
944
945 let msg = format!(
946 "Expected {} for {}, but {} is {}.",
947 expected, input_arg, input_path_text, self);
948 let mut hint = sq.hint(format_args!("{}", msg));
949
950 match self {
951 Kind::Cert => {
952 if command == "verify" {
953 hint = hint.hint(format_args!(
954 "To verify a message or signature using {}:",
955 input_path_text))
956 .sq().arg("verify")
957 .arg_value("--signer-file", &input_path_arg)
958 .done();
959 }
960
961 if command == "decrypt" {
962 hint = hint.hint(format_args!(
963 "To verify a message using {}:",
964 input_path_text))
965 .sq().arg("decrypt")
966 .arg_value("--signer-file", &input_path_arg)
967 .done();
968 }
969
970 hint.hint(format_args!(
971 "To import the cert {}:", input_path_text))
972 .sq().arg("cert").arg("import")
973 .arg(&input_path_arg)
974 .done();
975 },
976
977 Kind::Key => {
978 if command == "verify" {
979 hint = hint.hint(format_args!(
980 "To verify a message or signature using {}:",
981 input_path_text))
982 .sq().arg("verify")
983 .arg_value("--signer-file", &input_path_arg)
984 .done();
985 }
986
987 if command == "decrypt" {
988 hint = hint.hint(format_args!(
989 "To verify the signature on an encrypted message \
990 using {}:",
991 input_path_text))
992 .sq().arg("decrypt")
993 .arg_value("--signer-file", &input_path_arg)
994 .done();
995
996 hint = hint.hint(format_args!(
997 "To decrypt an encrypted message using {}:",
998 input_path_text))
999 .sq().arg("decrypt")
1000 .arg_value("--recipient-file", &input_path_arg)
1001 .done();
1002 }
1003
1004 hint.hint(format_args!(
1005 "To import the key {}:", input_path_text))
1006 .sq().arg("key").arg("import")
1007 .arg(&input_path_arg)
1008 .done();
1009 },
1010
1011 Kind::Keyring => {
1012 hint.hint(format_args!(
1013 "To import the certificates in {}:", input_path_text))
1014 .sq().arg("cert").arg("import")
1015 .arg(&input_path_arg)
1016 .done();
1017 },
1018
1019 Kind::SignedMessage => {
1020 hint.hint(format_args!(
1021 "To verify a signed message:"))
1022 .sq().arg("verify")
1023 .arg(&input_path_arg)
1024 .done();
1025 },
1026
1027 Kind::EncryptedMessage => {
1028 hint.hint(format_args!(
1029 "To decrypt an encrypted message:"))
1030 .sq().arg("decrypt")
1031 .arg(input_path_arg)
1032 .done();
1033 },
1034
1035 Kind::DetachedSig => {
1036 hint.hint(format_args!(
1037 "To verify the detached signature {}:",
1038 input_path_text))
1039 .sq().arg("verify")
1040 .arg_value("--signature-file", &input_path_arg)
1041 .arg("the-data-file")
1042 .done();
1043 },
1044
1045 Kind::RevocationCert => {
1046 hint.hint(format_args!(
1047 "To import the revocation certificate {}:",
1048 input_path_text))
1049 .sq().arg("cert").arg("import")
1050 .arg(&input_path_arg)
1051 .done();
1052 },
1053
1054 Kind::Unknown => {
1055 hint.hint(format_args!(
1056 "To inspect the packet sequence in {}:",
1057 input_path_text))
1058 .sq().arg("packet").arg("dump")
1059 .arg(&input_path_arg)
1060 .done();
1061 },
1062
1063 Kind::NotOpenPGP => {
1064 if command == "verify" {
1065 hint.hint(format_args!(
1066 "To verify the detached signature \
1067 over the data in {}:", input_path_text))
1068 .sq().arg("verify")
1069 .arg_value("--signature-file", "the-signature-file")
1070 .arg(&input_path_arg)
1071 .done();
1072 }
1073 },
1074 }
1075
1076 Err(anyhow::anyhow!("{}", msg))
1077 } else {
1078 Ok(())
1079 }
1080 }
1081 }