Debian Codegraph @

src/commands/packet/dump.rs

raw ◀ ▶
1 Debian patch touch this file
1 use std::io::{self, Read};
2
3 use sequoia_openpgp as openpgp;
4 use openpgp::KeyHandle;
5 use openpgp::armor::ReaderMode;
6 use self::openpgp::fmt::hex;
7 use self::openpgp::crypto::mpi;
8 use self::openpgp::{Cert, Packet, Result};
9 use self::openpgp::packet;
10 use self::openpgp::packet::prelude::*;
11 use self::openpgp::packet::header::CTB;
12 use self::openpgp::packet::{Header, header::BodyLength, Signature};
13 use self::openpgp::packet::signature::subpacket::{Subpacket, SubpacketValue};
14 use self::openpgp::crypto::S2K;
15 use self::openpgp::parse::{
16 Dearmor,
17 Parse,
18 PacketParserBuilder,
19 PacketParserResult,
20 map::Map,
21 stream::DecryptionHelper,
22 };
23
24 use crate::Convert;
25 use crate::cli::types::SessionKey;
26 use crate::common::ui;
27 use crate::Sq;
28
29 #[derive(Debug)]
30 pub enum Kind {
31 Message {
32 #[allow(dead_code)]
33 encrypted: bool,
34 },
35 Keyring,
36 Cert,
37 Unknown,
38 }
39
40 #[allow(clippy::redundant_pattern_matching)]
41 pub fn dump<W>(sq: &crate::Sq,
42 secrets: Vec<Cert>,
43 input: &mut (dyn io::Read + Sync + Send),
44 output: &mut dyn io::Write,
45 mpis: bool, hex: bool,
46 session_keys: Vec<SessionKey>,
47 width: W)
48 -> Result<Kind>
49 where W: Into<Option<usize>>
50 {
51 let mut ppr
52 = self::openpgp::parse::PacketParserBuilder::from_reader(input)?;
53
54 // To produce hex dumps, we need to enable mapping, but also turn
55 // on buffering. This makes sure that the map contains the whole
56 // packet content, even if it has not been parsed (such as when
57 // encountering unknown or junk pseudo packets).
58 if hex {
59 ppr = ppr.map(true).buffer_unread_content();
60 }
61
62 let mut ppr = ppr.build()?;
63
64 let width = width.into().unwrap_or(80);
65 let mut first_armor_block = true;
66 let mut is_keyring = true;
67 let mut helper = crate::commands::decrypt::Helper::new(
68 &sq, 0, Vec::new(), secrets, session_keys.clone(), false);
69
70 loop {
71 let mut dumper = PacketDumper::new(sq, width, mpis);
72 let mut message_encrypted = false;
73 let mut pkesks = vec![];
74 let mut skesks = vec![];
75
76 while let PacketParserResult::Some(mut pp) = ppr {
77 let additional_fields = match pp.packet {
78 Packet::PKESK(ref p) => {
79 pkesks.push(p.clone());
80 vec![]
81 },
82 Packet::SKESK(ref p) => {
83 skesks.push(p.clone());
84 vec![]
85 },
86 Packet::Literal(_) => {
87 let mut prefix = vec![0; 40];
88 let n = pp.read(&mut prefix)?;
89 vec![
90 format!("Content: {}{}",
91 ui::Safe(&prefix[..n]),
92 if n == prefix.len() { "..." } else { "" }),
93 ]
94 },
95 Packet::SEIP(ref s) => {
96 message_encrypted = true;
97
98 let mut success = false;
99 let mut fields = Vec::new();
100 let sym_algo_hint = if let SEIP::V2(s2) = s {
101 Some(s2.symmetric_algo())
102 } else {
103 None
104 };
105
106 let mut decryption_proxy = |algo, secret: &_| {
107 // Take the algo from the SEIPDv2 packet over
108 // the dummy one from the SKESK5 packet.
109 let result = pp.decrypt(algo, secret);
110 if let Ok(_) = result {
111 fields.push(
112 format!("Session key: {}", &hex::encode(secret)));
113 let algo = sym_algo_hint.or(algo)
114 .expect("we know either or");
115 fields.push(format!("Symmetric algo: {}", algo));
116 fields.push("Decryption successful".into());
117 success = true;
118 true
119 } else {
120 false
121 }
122 };
123
124 if let Err(e) = helper.decrypt(&pkesks[..], &skesks[..],
125 sym_algo_hint, &mut decryption_proxy)
126 {
127 for algo in session_keys.iter()
128 .filter_map(|sk| sk.symmetric_algo)
129 {
130 fields.push(format!(
131 "Indicated Symmetric algo: {}", algo));
132 }
133 fields.push(format!("Decryption failed: {}", e));
134 }
135 fields
136 },
137 _ => Vec::new(),
138 };
139
140 let header = pp.header().clone();
141 let map = pp.take_map();
142
143 let recursion_depth = pp.recursion_depth();
144 let packet = pp.packet.clone();
145
146 dumper.packet(output, recursion_depth as usize,
147 header, packet, map, additional_fields)?;
148
149 let (_, ppr_) = match pp.recurse() {
150 Ok(v) => Ok(v),
151 Err(e) => {
152 let _ = dumper.flush(output);
153 Err(e)
154 },
155 }?;
156 ppr = ppr_;
157 }
158
159 dumper.flush(output)?;
160
161 if let PacketParserResult::EOF(eof) = ppr {
162 let is_message = eof.is_message().is_ok() && first_armor_block;
163 let is_cert = eof.is_cert().is_ok() && first_armor_block;
164 is_keyring &= eof.is_keyring().is_ok();
165 first_armor_block = false;
166
167 // Now, the parser is exhausted, but we may find another
168 // armored blob. Note that this can only happen if the first
169 // set of packets was also armored.
170 match PacketParserBuilder::from_buffered_reader(eof.into_reader())
171 .and_then(
172 |builder| builder
173 .dearmor(Dearmor::Enabled(
174 ReaderMode::Tolerant(None)))
175 .build())
176 {
177 Ok(ppr_) => {
178 writeln!(output, "Note: There is another block of armored \
179 OpenPGP data.")?;
180
181 if is_message {
182 writeln!(output, "Note: Data concatenated to a message is \
183 likely an error.")?;
184 } else if is_cert || is_keyring {
185 writeln!(output, "Note: This is a non-standard extension \
186 to OpenPGP.")?;
187 }
188 writeln!(output)?;
189
190 ppr = ppr_;
191 continue;
192 },
193 Err(_) => break if is_message {
194 Ok(Kind::Message {
195 encrypted: message_encrypted,
196 })
197 } else if is_cert {
198 Ok(Kind::Cert)
199 } else if is_keyring {
200 Ok(Kind::Keyring)
201 } else {
202 Ok(Kind::Unknown)
203 }
204 }
205 } else {
206 unreachable!()
207 }
208 }
209 }
210
211 struct Node {
212 header: Header,
213 packet: Packet,
214 map: Option<Map>,
215 additional_fields: Vec<String>,
216 children: Vec<Node>,
217 }
218
219 impl Node {
220 fn new(header: Header, packet: Packet, map: Option<Map>,
221 additional_fields: Vec<String>) -> Self {
222 Node {
223 header,
224 packet,
225 map,
226 additional_fields,
227 children: Vec::new(),
228 }
229 }
230
231 fn append(&mut self, depth: usize, node: Node) {
232 if depth == 0 {
233 self.children.push(node);
234 } else {
235 self.children.iter_mut().last().unwrap().append(depth - 1, node);
236 }
237 }
238 }
239
240 pub struct PacketDumper<'a, 'b, 'c> {
241 sq: &'a Sq<'b, 'c>,
242 width: usize,
243 mpis: bool,
244 root: Option<Node>,
245 }
246
247 impl<'a, 'b, 'c> PacketDumper<'a, 'b, 'c> {
248 pub fn new(sq: &'a Sq<'b, 'c>, width: usize, mpis: bool) -> Self {
249 PacketDumper {
250 sq,
251 width,
252 mpis,
253 root: None,
254 }
255 }
256
257 pub fn packet(&mut self, output: &mut dyn io::Write, depth: usize,
258 header: Header, p: Packet, map: Option<Map>,
259 additional_fields: Vec<String>)
260 -> Result<()> {
261 let node = Node::new(header, p, map, additional_fields);
262 if self.root.is_none() {
263 assert_eq!(depth, 0);
264 self.root = Some(node);
265 } else if depth == 0 {
266 let root = self.root.take().unwrap();
267 self.dump_tree(output, "", &root)?;
268 self.root = Some(node);
269 } else {
270 self.root.as_mut().unwrap().append(depth - 1, node);
271 }
272 Ok(())
273 }
274
275 pub fn flush(&self, output: &mut dyn io::Write) -> Result<()> {
276 if let Some(root) = self.root.as_ref() {
277 self.dump_tree(output, "", root)?;
278 }
279 Ok(())
280 }
281
282 fn dump_tree(&self, output: &mut dyn io::Write, indent: &str, node: &Node)
283 -> Result<()> {
284 let indent_node =
285 format!("{}{} ", indent,
286 if node.children.is_empty() { " " } else { "│" });
287 self.dump_packet(output, &indent_node, Some(&node.header), &node.packet,
288 node.map.as_ref(), &node.additional_fields)?;
289 if node.children.is_empty() {
290 return Ok(());
291 }
292
293 let last = node.children.len() - 1;
294 for (i, child) in node.children.iter().enumerate() {
295 let is_last = i == last;
296 write!(output, "{}{}── ", indent,
297 if is_last { "└" } else { "├" })?;
298 let indent_child =
299 format!("{}{} ", indent,
300 if is_last { " " } else { "│" });
301 self.dump_tree(output, &indent_child, child)?;
302 }
303 Ok(())
304 }
305
306 fn dump_packet(&self, mut output: &mut dyn io::Write, i: &str,
307 header: Option<&Header>, p: &Packet, map: Option<&Map>,
308 additional_fields: &Vec<String>)
309 -> Result<()> {
310 use self::openpgp::Packet::*;
311
312 if let Some(tag) = p.kind() {
313 write!(output, "{}", tag)?;
314 } else {
315 write!(output, "Unknown or Unsupported Packet")?;
316 }
317
318 if let Some(h) = header {
319 write!(output, ", {} CTB, {}{}",
320 if let CTB::Old(_) = h.ctb() { "old" } else { "new" },
321 if let Some(map) = map {
322 format!("{} header bytes + ",
323 map.iter().take(2).map(|f| f.as_bytes().len())
324 .sum::<usize>())
325 } else {
326 // XXX: Mapping is disabled. No can do for
327 // now. Once we save the header in
328 // packet::Common, we can use this instead of
329 // relying on the map.
330 "".into()
331 },
332 match h.length() {
333 BodyLength::Full(n) =>
334 format!("{} bytes", n),
335 BodyLength::Partial(n) =>
336 format!("partial length, {} bytes in first chunk", n),
337 BodyLength::Indeterminate =>
338 "indeterminate length".into(),
339 })?;
340 }
341 writeln!(output)?;
342
343 #[allow(deprecated)]
344 match p {
345 Unknown(ref u) => {
346 writeln!(output, "{} Tag: {}", i, u.tag())?;
347 writeln!(output, "{} Error: {}", i, u.error())?;
348 },
349
350 PublicKey(ref k) => self.dump_key(output, i, k)?,
351 PublicSubkey(ref k) => self.dump_key(output, i, k)?,
352 SecretKey(ref k) => self.dump_key(output, i, k)?,
353 SecretSubkey(ref k) => self.dump_key(output, i, k)?,
354
355 Signature(s) => self.dump_signature(output, i, s)?,
356
357 OnePassSig(ref o) => {
358 writeln!(output, "{} Version: {}", i, o.version())?;
359 writeln!(output, "{} Type: {}", i, o.typ())?;
360 writeln!(output, "{} Pk algo: {}", i, o.pk_algo())?;
361 writeln!(output, "{} Hash algo: {}", i, o.hash_algo())?;
362 writeln!(output, "{} Issuer: {}", i, o.issuer())?;
363 if let packet::OnePassSig::V6(o) = o {
364 writeln!(output, "{} Salt: {}", i, hex::encode(o.salt()))?;
365 }
366 writeln!(output, "{} Last: {}", i, o.last())?;
367 },
368
369 Trust(ref p) => {
370 writeln!(output, "{} Value:", i)?;
371 let mut hd = hex::Dumper::new(
372 &mut output,
373 self.indentation_for_hexdump(&format!("{} ", i), 16));
374 hd.write_ascii(p.value())?;
375 },
376
377 UserID(ref u) => {
378 writeln!(output, "{} Value: {}", i,
379 ui::Safe(u.value()))?;
380 },
381
382 UserAttribute(ref u) => {
383 use self::openpgp::packet::user_attribute::{Subpacket, Image};
384 use openpgp::serialize::MarshalInto;
385
386 for subpacket in u.subpackets() {
387 match subpacket {
388 Ok(Subpacket::Image(image)) => match image {
389 Image::JPEG(data) =>
390 writeln!(output, "{} JPEG: {} bytes", i,
391 data.len())?,
392 Image::Private(n, data) =>
393 writeln!(output,
394 "{} Private image({}): {} bytes", i,
395 n, data.len())?,
396 Image::Unknown(n, data) =>
397 writeln!(output,
398 "{} Unknown image({}): {} bytes", i,
399 n, data.len())?,
400 _ =>
401 writeln!(output,
402 "{} Unknown image: {} bytes", i,
403 image.serialized_len())?,
404 },
405 Ok(Subpacket::Unknown(n, data)) =>
406 writeln!(output,
407 "{} Unknown subpacket({}): {} bytes", i,
408 n, data.len())?,
409 Ok(u) =>
410 writeln!(output,
411 "{} Unknown subpacket: {} bytes", i,
412 u.serialized_len())?,
413 Err(e) =>
414 writeln!(output,
415 "{} Invalid subpacket encoding: {}", i,
416 e)?,
417 }
418 }
419 },
420
421 Marker(_) => {
422 },
423
424 Literal(ref l) => {
425 writeln!(output, "{} Format: {}", i, l.format())?;
426 if let Some(filename) = l.filename() {
427 writeln!(output, "{} Filename: {}", i,
428 ui::Safe(filename))?;
429 }
430 if let Some(timestamp) = l.date() {
431 writeln!(output, "{} Timestamp: {}", i,
432 timestamp.convert())?;
433 }
434 },
435
436 CompressedData(ref c) => {
437 writeln!(output, "{} Algorithm: {}", i, c.algo())?;
438 },
439
440 PKESK(ref p) => {
441 writeln!(output, "{} Version: {}", i, p.version())?;
442 writeln!(output, "{} Recipient: {}", i,
443 p.recipient().as_ref().map(ToString::to_string)
444 .unwrap_or_else(|| "<anonymous recipient>".into()))?;
445 writeln!(output, "{} Pk algo: {}", i, p.pk_algo())?;
446 if self.mpis {
447 writeln!(output, "{}", i)?;
448 writeln!(output, "{} Encrypted session key:", i)?;
449
450 let ii = format!("{} ", i);
451 match p.esk() {
452 mpi::Ciphertext::X25519 { e, key } =>
453 self.dump_mpis(output, &ii,
454 &[&e[..], key],
455 &["e", "key"])?,
456 mpi::Ciphertext::X448 { e, key } =>
457 self.dump_mpis(output, &ii,
458 &[&e[..], key],
459 &["e", "key"])?,
460 mpi::Ciphertext::RSA { c } =>
461 self.dump_mpis(output, &ii,
462 &[c.value()],
463 &["c"])?,
464 mpi::Ciphertext::ElGamal { e, c } =>
465 self.dump_mpis(output, &ii,
466 &[e.value(), c.value()],
467 &["e", "c"])?,
468 mpi::Ciphertext::ECDH { e, key } =>
469 self.dump_mpis(output, &ii,
470 &[e.value(), key],
471 &["e", "key"])?,
472 mpi::Ciphertext::Unknown { mpis, rest } => {
473 let keys: Vec<String> =
474 (0..mpis.len()).map(
475 |i| format!("mpi{}", i)).collect();
476 self.dump_mpis(
477 output, &ii,
478 &mpis.iter().map(|m| {
479 m.value().iter().as_slice()
480 }).collect::<Vec<_>>()[..],
481 &keys.iter().map(|k| k.as_str())
482 .collect::<Vec<_>>()[..],
483 )?;
484
485 self.dump_mpis(output, &ii, &[rest], &["rest"])?;
486 },
487
488 // crypto::mpi::Ciphertext is non-exhaustive.
489 u => writeln!(output, "{}Unknown variant: {:?}", ii, u)?,
490 }
491 }
492 },
493
494 SKESK(ref s) => {
495 writeln!(output, "{} Version: {}", i, s.version())?;
496 match s {
497 self::openpgp::packet::SKESK::V4(ref s) => {
498 writeln!(output, "{} Symmetric algo: {}", i,
499 s.symmetric_algo())?;
500 write!(output, "{} S2K: ", i)?;
501 self.dump_s2k(output, i, s.s2k())?;
502 if let Ok(Some(esk)) = s.esk() {
503 writeln!(output, "{} ESK: {}", i,
504 hex::encode(esk))?;
505 }
506 },
507
508 self::openpgp::packet::SKESK::V6(ref s) => {
509 writeln!(output, "{} Symmetric algo: {}", i,
510 s.symmetric_algo())?;
511 writeln!(output, "{} AEAD: {}", i,
512 s.aead_algo())?;
513 write!(output, "{} S2K: ", i)?;
514 self.dump_s2k(output, i, s.s2k())?;
515 writeln!(output, "{} IV: {}", i,
516 hex::encode(s.aead_iv()))?;
517 writeln!(output, "{} ESK: {}", i,
518 hex::encode(s.esk()))?;
519 },
520
521 // SKESK is non-exhaustive.
522 u => writeln!(output, "{} Unknown variant: {:?}", i, u)?,
523 }
524 },
525
526 SEIP(ref s) => {
527 writeln!(output, "{} Version: {}", i, s.version())?;
528 match s {
529 packet::SEIP::V1(_) => (),
530 packet::SEIP::V2(s) => {
531 writeln!(output, "{} Symmetric algo: {}", i, s.symmetric_algo())?;
532 writeln!(output, "{} AEAD algo: {}", i, s.aead())?;
533 writeln!(output, "{} Chunk size: {}", i, s.chunk_size())?;
534 writeln!(output, "{} Salt: {}", i, hex::encode(s.salt()))?;
535 },
536 _ => (),
537 }
538 },
539
540 MDC(ref m) => {
541 writeln!(output, "{} Digest: {}",
542 i, hex::encode(m.digest()))?;
543 writeln!(output, "{} Computed digest: {}",
544 i, hex::encode(m.computed_digest()))?;
545 writeln!(output, "{} Valid: {}",
546 i, m.valid())?;
547 },
548
549 Padding(_) => {
550 // Nothing to do.
551 }
552
553 // openpgp::Packet is non-exhaustive.
554 u => writeln!(output, "{} Unknown variant: {:?}", i, u)?,
555 }
556
557 for field in additional_fields {
558 writeln!(output, "{} {}", i, field)?;
559 }
560
561 writeln!(output, "{}", i)?;
562
563 if let Some(map) = map {
564 if map.iter().next().is_none() {
565 // There is no data, we cannot dump anything.
566 return Ok(());
567 }
568
569 let mut hd = hex::Dumper::new(output, self.indentation_for_hexdump(
570 i, map.iter()
571 .map(|f| if f.name() == "body" { 16 } else { f.name().len() })
572 .max()
573 .expect("we checked that there is one entry")));
574
575 for field in map.iter() {
576 if field.name() == "body" {
577 hd.write_ascii(field.as_bytes())?;
578 } else {
579 hd.write(field.as_bytes(), field.name())?;
580 }
581 }
582
583 let output = hd.into_inner();
584 writeln!(output, "{}", i)?;
585 }
586
587 Ok(())
588 }
589
590 /// Dumps the given key packet.
591 fn dump_key<P, R>(&self, output: &mut dyn io::Write, i: &str,
592 k: &Key<P, R>)
593 -> Result<()>
594 where
595 P: key::KeyParts,
596 R: key::KeyRole,
597 {
598 self.dump_key_internal(
599 output, i, k.parts_as_unspecified().role_as_unspecified())
600 }
601
602 /// Dumps the given key packet, prevents monomorphization of this
603 /// big function.
604 fn dump_key_internal(&self, output: &mut dyn io::Write, i: &str,
605 k: &Key<key::UnspecifiedParts, key::UnspecifiedRole>)
606 -> Result<()>
607 {
608 writeln!(output, "{} Version: {}", i, k.version())?;
609 writeln!(output, "{} Creation time: {}", i,
610 k.creation_time().convert())?;
611 writeln!(output, "{} Pk algo: {}", i, k.pk_algo())?;
612 if let Some(bits) = k.mpis().bits() {
613 writeln!(output, "{} Pk size: {} bits", i, bits)?;
614 }
615 writeln!(output, "{} Fingerprint: {}", i, k.fingerprint())?;
616 writeln!(output, "{} KeyID: {}", i, k.keyid())?;
617 if self.mpis {
618 writeln!(output, "{}", i)?;
619 writeln!(output, "{} Public Key:", i)?;
620
621 let ii = format!("{} ", i);
622 match k.mpis() {
623 mpi::PublicKey::X25519 { u } =>
624 self.dump_mpis(output, &ii, &[u], &["u"])?,
625 mpi::PublicKey::X448 { u } =>
626 self.dump_mpis(output, &ii, &[&u[..]], &["u"])?,
627 mpi::PublicKey::Ed25519 { a } =>
628 self.dump_mpis(output, &ii, &[a], &["a"])?,
629 mpi::PublicKey::Ed448 { a } =>
630 self.dump_mpis(output, &ii, &[&a[..]], &["a"])?,
631 mpi::PublicKey::RSA { e, n } =>
632 self.dump_mpis(output, &ii,
633 &[e.value(), n.value()],
634 &["e", "n"])?,
635 mpi::PublicKey::DSA { p, q, g, y } =>
636 self.dump_mpis(output, &ii,
637 &[p.value(), q.value(), g.value(),
638 y.value()],
639 &["p", "q", "g", "y"])?,
640 mpi::PublicKey::ElGamal { p, g, y } =>
641 self.dump_mpis(output, &ii,
642 &[p.value(), g.value(), y.value()],
643 &["p", "g", "y"])?,
644 mpi::PublicKey::EdDSA { curve, q } => {
645 writeln!(output, "{} Curve: {}", ii, curve)?;
646 self.dump_mpis(output, &ii, &[q.value()], &["q"])?;
647 },
648 mpi::PublicKey::ECDSA { curve, q } => {
649 writeln!(output, "{} Curve: {}", ii, curve)?;
650 self.dump_mpis(output, &ii, &[q.value()], &["q"])?;
651 },
652 mpi::PublicKey::ECDH { curve, q, hash, sym } => {
653 writeln!(output, "{} Curve: {}", ii, curve)?;
654 writeln!(output, "{} KDF hash algo: {}", ii, hash)?;
655 writeln!(output, "{} KEK symmetric algo: {}", ii,
656 sym)?;
657 self.dump_mpis(output, &ii, &[q.value()], &["q"])?;
658 },
659 mpi::PublicKey::Unknown { mpis, rest } => {
660 let keys: Vec<String> =
661 (0..mpis.len()).map(
662 |i| format!("mpi{}", i)).collect();
663 self.dump_mpis(
664 output, &ii,
665 &mpis.iter().map(|m| {
666 m.value().iter().as_slice()
667 }).collect::<Vec<_>>()[..],
668 &keys.iter().map(|k| k.as_str())
669 .collect::<Vec<_>>()[..],
670 )?;
671
672 self.dump_mpis(output, &ii, &[&rest[..]], &["rest"])?;
673 },
674
675 // crypto::mpi:Publickey is non-exhaustive
676 u => writeln!(output, "{}Unknown variant: {:?}", ii, u)?,
677 }
678 }
679
680 if let Some(secrets) = k.optional_secret() {
681 writeln!(output, "{}", i)?;
682 writeln!(output, "{} Secret Key:", i)?;
683
684 let ii = format!("{} ", i);
685 match secrets {
686 SecretKeyMaterial::Unencrypted(ref u) => {
687 writeln!(output, "{}", i)?;
688 writeln!(output, "{} Unencrypted", ii)?;
689 if self.mpis {
690 u.map(|mpis| -> Result<()> {
691 match mpis
692 {
693 mpi::SecretKeyMaterial::X25519 { x } =>
694 self.dump_mpis(output, &ii,
695 &[x], &["x"])?,
696 mpi::SecretKeyMaterial::X448 { x } =>
697 self.dump_mpis(output, &ii,
698 &[&x[..]], &["x"])?,
699 mpi::SecretKeyMaterial::Ed25519 { x } =>
700 self.dump_mpis(output, &ii,
701 &[x], &["x"])?,
702 mpi::SecretKeyMaterial::Ed448 { x } =>
703 self.dump_mpis(output, &ii,
704 &[&x[..]], &["x"])?,
705 mpi::SecretKeyMaterial::RSA { d, p, q, u } =>
706 self.dump_mpis(output, &ii,
707 &[d.value(), p.value(),
708 q.value(), u.value()],
709 &["d", "p", "q", "u"])?,
710 mpi::SecretKeyMaterial::DSA { x } =>
711 self.dump_mpis(output, &ii, &[x.value()],
712 &["x"])?,
713 mpi::SecretKeyMaterial::ElGamal { x } =>
714 self.dump_mpis(output, &ii, &[x.value()],
715 &["x"])?,
716 mpi::SecretKeyMaterial::EdDSA { scalar } =>
717 self.dump_mpis(output, &ii,
718 &[scalar.value()],
719 &["scalar"])?,
720 mpi::SecretKeyMaterial::ECDSA { scalar } =>
721 self.dump_mpis(output, &ii,
722 &[scalar.value()],
723 &["scalar"])?,
724 mpi::SecretKeyMaterial::ECDH { scalar } =>
725 self.dump_mpis(output, &ii,
726 &[scalar.value()],
727 &["scalar"])?,
728 mpi::SecretKeyMaterial::Unknown { mpis, rest } => {
729 let keys: Vec<String> =
730 (0..mpis.len()).map(
731 |i| format!("mpi{}", i)).collect();
732 self.dump_mpis(
733 output, &ii,
734 &mpis.iter().map(|m| {
735 m.value().iter().as_slice()
736 }).collect::<Vec<_>>()[..],
737 &keys.iter().map(|k| k.as_str())
738 .collect::<Vec<_>>()[..],
739 )?;
740
741 self.dump_mpis(output, &ii, &[rest],
742 &["rest"])?;
743 },
744
745 // crypto::mpi::SecretKeyMaterial is non-exhaustive.
746 u => writeln!(output, "{}Unknown variant: {:?}", ii, u)?,
747 }
748 Ok(())
749 })?;
750 }
751 }
752 SecretKeyMaterial::Encrypted(ref e) => {
753 writeln!(output, "{}", i)?;
754 writeln!(output, "{} Encrypted", ii)?;
755 write!(output, "{} S2K: ", ii)?;
756 self.dump_s2k(output, &ii, e.s2k())?;
757 writeln!(output, "{} Sym. algo: {}", ii,
758 e.algo())?;
759 if self.mpis {
760 if let Ok(ciphertext) = e.ciphertext() {
761 self.dump_mpis(output, &ii, &[ciphertext],
762 &["ciphertext"])?;
763 }
764 }
765 },
766 }
767 }
768
769 Ok(())
770 }
771
772 pub fn dump_signature(&self, output: &mut dyn io::Write, i: &str,
773 s: &Signature)
774 -> Result<()>
775 {
776 writeln!(output, "{} Version: {}", i, s.version())?;
777 writeln!(output, "{} Type: {}", i, s.typ())?;
778 writeln!(output, "{} Pk algo: {}", i, s.pk_algo())?;
779 writeln!(output, "{} Hash algo: {}", i, s.hash_algo())?;
780 if s.hashed_area().iter().count() > 0 {
781 writeln!(output, "{} Hashed area:", i)?;
782 for pkt in s.hashed_area().iter() {
783 self.dump_subpacket(output, i, pkt, s)?;
784 }
785 }
786 if s.unhashed_area().iter().count() > 0 {
787 writeln!(output, "{} Unhashed area:", i)?;
788 for pkt in s.unhashed_area().iter() {
789 self.dump_subpacket(output, i, pkt, s)?;
790 }
791 }
792 writeln!(output, "{} Digest prefix: {}", i,
793 hex::encode(s.digest_prefix()))?;
794 if let packet::Signature::V6(s) = s {
795 writeln!(output, "{} Salt: {}", i, hex::encode(s.salt()))?;
796 }
797 write!(output, "{} Level: {} ", i, s.level())?;
798 match s.level() {
799 0 => writeln!(output, "(signature over data)")?,
800 1 => writeln!(output, "(notarization over signatures \
801 level 0 and data)")?,
802 n => writeln!(output, "(notarization over signatures \
803 level <= {} and data)", n - 1)?,
804 }
805 if self.mpis {
806 writeln!(output, "{}", i)?;
807 writeln!(output, "{} Signature:", i)?;
808
809 let ii = format!("{} ", i);
810 match s.mpis() {
811 mpi::Signature::Ed25519 { s } =>
812 self.dump_mpis(output, &ii, &[&s[..]], &["s"])?,
813 mpi::Signature::Ed448 { s } =>
814 self.dump_mpis(output, &ii, &[&s[..]], &["s"])?,
815 mpi::Signature::RSA { s } =>
816 self.dump_mpis(output, &ii,
817 &[s.value()],
818 &["s"])?,
819 mpi::Signature::DSA { r, s } =>
820 self.dump_mpis(output, &ii,
821 &[r.value(), s.value()],
822 &["r", "s"])?,
823 mpi::Signature::ElGamal { r, s } =>
824 self.dump_mpis(output, &ii,
825 &[r.value(), s.value()],
826 &["r", "s"])?,
827 mpi::Signature::EdDSA { r, s } =>
828 self.dump_mpis(output, &ii,
829 &[r.value(), s.value()],
830 &["r", "s"])?,
831 mpi::Signature::ECDSA { r, s } =>
832 self.dump_mpis(output, &ii,
833 &[r.value(), s.value()],
834 &["r", "s"])?,
835 mpi::Signature::Unknown { mpis, rest } => {
836 let keys: Vec<String> =
837 (0..mpis.len()).map(
838 |i| format!("mpi{}", i)).collect();
839 self.dump_mpis(
840 output, &ii,
841 &mpis.iter().map(|m| {
842 m.value().iter().as_slice()
843 }).collect::<Vec<_>>()[..],
844 &keys.iter().map(|k| k.as_str())
845 .collect::<Vec<_>>()[..],
846 )?;
847
848 self.dump_mpis(output, &ii, &[&rest[..]], &["rest"])?;
849 },
850
851 // crypto::mpi::Signature is non-exhaustive.
852 u => writeln!(output, "{}Unknown variant: {:?}", ii, u)?,
853 }
854 }
855
856 Ok(())
857 }
858
859 fn dump_subpacket(&self, output: &mut dyn io::Write, i: &str,
860 s: &Subpacket, sig: &Signature)
861 -> Result<()> {
862 use self::SubpacketValue::*;
863
864 let hexdump_unknown = |output: &mut dyn io::Write, buf| -> Result<()> {
865 let mut hd = hex::Dumper::new(output, self.indentation_for_hexdump(
866 &format!("{} ", i), 0));
867 hd.write_labeled(buf, |_, _| None)?;
868 Ok(())
869 };
870
871 #[allow(deprecated)]
872 match s.value() {
873 Unknown { body, .. } => {
874 writeln!(output, "{} {:?}{}:", i, s.tag(),
875 if s.critical() { " (critical)" } else { "" })?;
876 hexdump_unknown(output, body.as_slice())?;
877 },
878 SignatureCreationTime(t) =>
879 write!(output, "{} Signature creation time: {}", i,
880 (*t).convert())?,
881 SignatureExpirationTime(t) =>
882 write!(output, "{} Signature expiration time: {} ({})",
883 i, t.convert(),
884 if let Some(creation) = sig.signature_creation_time() {
•885 let t : std::time::SystemTime = (creation + <openpgp::types::Duration as Into<std::time::Duration>>::into((*t)));
886 t.convert().to_string()
887 } else {
888 " (no Signature Creation Time subpacket)".into()
889 })?,
890 ExportableCertification(e) =>
891 write!(output, "{} Exportable certification: {}", i, e)?,
892 TrustSignature{level, trust} =>
893 write!(output, "{} Trust signature: level {} trust {}", i,
894 level, trust)?,
895 RegularExpression(ref r) =>
896 write!(output, "{} Regular expression: {}", i,
897 ui::Safe(r))?,
898 Revocable(r) =>
899 write!(output, "{} Revocable: {}", i, r)?,
900 KeyExpirationTime(t) =>
901 write!(output, "{} Key expiration time: {}", i,
902 t.convert())?,
903 PreferredSymmetricAlgorithms(ref c) =>
904 write!(output, "{} Symmetric algo preferences: {}", i,
905 c.iter().map(|c| format!("{:?}", c))
906 .collect::<Vec<String>>().join(", "))?,
907 RevocationKey(rk) => {
908 let (pk_algo, fp) = rk.revoker();
909 write!(output,
910 "{} Revocation key: {}/{}", i,
911 fp, pk_algo)?;
912 if rk.sensitive() {
913 write!(output, ", sensitive")?;
914 }
915 },
916 Issuer(ref is) => {
917 let (userid, cert)
918 = self.sq.best_userid_for(&KeyHandle::from(is), None, true);
919 write!(output, "{} Issuer: {}", i, is)?;
920 if cert.is_ok() {
921 writeln!(output)?;
922 write!(output, "{} {}", i, userid.display())?;
923 }
924 }
925 NotationData(n) => if n.flags().human_readable() {
926 write!(output, "{} Notation: {}", i, ui::Safe(n))?;
927 if s.critical() {
928 write!(output, " (critical)")?;
929 }
930 writeln!(output)?;
931 } else {
932 write!(output, "{} Notation: {}", i, ui::Safe(n.name()))?;
933 let flags = format!("{:?}", n.flags());
934 if ! flags.is_empty() {
935 write!(output, "{}", flags)?;
936 }
937 if s.critical() {
938 write!(output, " (critical)")?;
939 }
940 writeln!(output)?;
941 hexdump_unknown(output, n.value())?;
942 },
943 PreferredHashAlgorithms(ref h) =>
944 write!(output, "{} Hash preferences: {}", i,
945 h.iter().map(|h| format!("{:?}", h))
946 .collect::<Vec<String>>().join(", "))?,
947 PreferredCompressionAlgorithms(ref c) =>
948 write!(output, "{} Compression preferences: {}", i,
949 c.iter().map(|c| format!("{:?}", c))
950 .collect::<Vec<String>>().join(", "))?,
951 KeyServerPreferences(ref p) =>
952 write!(output, "{} Keyserver preferences: {:?}", i, p)?,
953 PreferredKeyServer(ref k) =>
954 write!(output, "{} Preferred keyserver: {}", i,
955 ui::Safe(k))?,
956 PrimaryUserID(p) =>
957 write!(output, "{} Primary User ID: {}", i, p)?,
958 PolicyURI(ref p) =>
959 write!(output, "{} Policy URI: {}", i, ui::Safe(p))?,
960 KeyFlags(ref k) =>
961 write!(output, "{} Key flags: {:?}", i, k)?,
962 SignersUserID(ref u) =>
963 write!(output, "{} Signer's User ID: {}", i,
964 ui::Safe(u))?,
965 ReasonForRevocation{code, ref reason} => {
966 write!(output, "{} Reason for revocation: {}{}{}", i, code,
967 if reason.len() > 0 { ", " } else { "" },
968 ui::Safe(reason))?
969 }
970 Features(ref f) =>
971 write!(output, "{} Features: {:?}", i, f)?,
972 SignatureTarget{pk_algo, hash_algo, ref digest} =>
973 write!(output, "{} Signature target: {}, {}, {}", i,
974 pk_algo, hash_algo, hex::encode(digest))?,
975 EmbeddedSignature(_) =>
976 // Embedded signature is dumped below.
977 write!(output, "{} Embedded signature: ", i)?,
978 IssuerFingerprint(ref fp) => {
979 let (userid, cert)
980 = self.sq.best_userid_for(&KeyHandle::from(fp), None, true);
981 write!(output, "{} Issuer Fingerprint: {}", i, fp)?;
982 if cert.is_ok() {
983 writeln!(output)?;
984 write!(output, "{} {}", i, userid.display())?;
985 }
986 }
987
988 IntendedRecipient(ref fp) =>
989 write!(output, "{} Intended Recipient: {}", i, fp)?,
990 ApprovedCertifications(digests) => {
991 write!(output, "{} Approved Certifications:", i)?;
992 if digests.is_empty() {
993 writeln!(output, " None")?;
994 } else {
995 writeln!(output)?;
996 for d in digests {
997 writeln!(output, "{} {}", i, hex::encode(d))?;
998 }
999 }
1000 },
1001 PreferredAEADCiphersuites(p) =>
1002 write!(output, "{} AEAD preferences: {}", i,
1003 p.iter().map(|(symm, aead)|
1004 format!("{:?}+{:?}", symm, aead))
1005 .collect::<Vec<String>>().join(", "))?,
1006
1007 // SubpacketValue is non-exhaustive.
1008 u => writeln!(output, "{} Unknown variant: {:?}", i, u)?,
1009 }
1010
1011 match s.value() {
1012 Unknown { .. } => (),
1013 NotationData { .. } => (),
1014 EmbeddedSignature(ref sig) => {
1015 if s.critical() {
1016 write!(output, " (critical)")?;
1017 }
1018 writeln!(output)?;
1019 let indent = format!("{} ", i);
1020 write!(output, "{}", indent)?;
1021 self.dump_signature(output, &indent, sig)?;
1022 },
1023 _ => {
1024 if s.critical() {
1025 write!(output, " (critical)")?;
1026 }
1027 writeln!(output)?;
1028 }
1029 }
1030
1031 Ok(())
1032 }
1033
1034 fn dump_s2k(&self, output: &mut dyn io::Write, i: &str, s2k: &S2K)
1035 -> Result<()> {
1036 use self::S2K::*;
1037 #[allow(deprecated)]
1038 match s2k {
1039 Implicit => {
1040 writeln!(output, "Implicit")?;
1041 },
1042 Simple { hash } => {
1043 writeln!(output, "Simple")?;
1044 writeln!(output, "{} Hash: {}", i, hash)?;
1045 },
1046 Salted { hash, ref salt } => {
1047 writeln!(output, "Salted")?;
1048 writeln!(output, "{} Hash: {}", i, hash)?;
1049 writeln!(output, "{} Salt: {}", i, hex::encode(salt))?;
1050 },
1051 Iterated { hash, ref salt, hash_bytes } => {
1052 writeln!(output, "Iterated")?;
1053 writeln!(output, "{} Hash: {}", i, hash)?;
1054 writeln!(output, "{} Salt: {}", i, hex::encode(salt))?;
1055 writeln!(output, "{} Hash bytes: {}", i, hash_bytes)?;
1056 },
1057 Argon2 { salt, t, p, m } => {
1058 writeln!(output, "Argon2")?;
1059 writeln!(output, "{} Salt: {}", i, hex::encode(salt))?;
1060 writeln!(output, "{} Passes: {}", i, t)?;
1061 writeln!(output, "{} Parallelism: {}", i, p)?;
1062 writeln!(output, "{} Memory: {} ({} KiB)", i, m,
1063 2usize.pow((*m).into()))?;
1064 },
1065 Private { tag, parameters } => {
1066 writeln!(output, "Private")?;
1067 writeln!(output, "{} Tag: {}", i, tag)?;
1068 if let Some(p) = parameters.as_ref() {
1069 writeln!(output, "{} Parameters: {:?}", i, p)?;
1070 }
1071 },
1072 Unknown { tag, parameters } => {
1073 writeln!(output, "Unknown")?;
1074 writeln!(output, "{} Tag: {}", i, tag)?;
1075 if let Some(p) = parameters.as_ref() {
1076 writeln!(output, "{} Parameters: {:?}", i, p)?;
1077 }
1078 },
1079
1080 // S2K is non-exhaustive
1081 u => writeln!(output, "{} Unknown variant: {:?}", i, u)?,
1082 }
1083 Ok(())
1084 }
1085
1086 fn dump_mpis(&self, output: &mut dyn io::Write, i: &str,
1087 chunks: &[&[u8]], keys: &[&str]) -> Result<()> {
1088 assert_eq!(chunks.len(), keys.len());
1089 if chunks.is_empty() {
1090 return Ok(());
1091 }
1092
1093 let max_key_len = keys.iter().map(|k| k.len()).max().unwrap();
1094
1095 for (chunk, key) in chunks.iter().zip(keys.iter()) {
1096 writeln!(output, "{}", i)?;
1097 let mut hd = hex::Dumper::new(
1098 Vec::new(), self.indentation_for_hexdump(i, max_key_len));
1099 hd.write(*chunk, *key)?;
1100 output.write_all(&hd.into_inner())?;
1101 }
1102
1103 Ok(())
1104 }
1105
1106 /// Returns indentation for hex dumps.
1107 ///
1108 /// Returns a prefix of `i` so that a hexdump with labels no
1109 /// longer than `max_label_len` will fit into the target width.
1110 fn indentation_for_hexdump(&self, i: &str, max_label_len: usize) -> String {
1111 let amount = ::std::cmp::max(
1112 0,
1113 ::std::cmp::min(
1114 self.width as isize
1115 - 63 // Length of address, hex digits, and whitespace.
1116 - max_label_len as isize,
1117 i.len() as isize),
1118 ) as usize;
1119
1120 format!("{} ", &i.chars().take(amount).collect::<String>())
1121 }
1122
1123
1124 }