Debian Codegraph @

src/commands/packet.rs

raw
1 use std::{
2 fs::File,
3 io::{self, Write},
4 };
5
6 use anyhow::Context as _;
7 use terminal_size::terminal_size;
8
9 use sequoia_openpgp as openpgp;
10 use openpgp::{
11 KeyHandle,
12 armor::{
13 Kind,
14 ReaderMode,
15 Writer,
16 },
17 packet::{Packet, Tag},
18 parse::{
19 Dearmor,
20 Parse,
21 PacketParserBuilder,
22 PacketParserResult,
23 },
24 serialize::SerializeInto,
25 };
26 use openpgp::serialize::stream::Message;
27
28 use crate::Sq;
29 use crate::Convert;
30 use crate::Result;
31 use crate::cli::packet::{
32 Command,
33 Subcommands,
34 SplitCommand,
35 JoinCommand,
36 };
37 use crate::cli::types::FileOrStdout;
38 use crate::cli::types::StdinWarning;
39 use crate::commands;
40 use crate::common::ui;
41 use crate::load_keys;
42 use crate::sq::TrustThreshold;
43
44 pub mod armor;
45 pub mod dearmor;
46 pub mod dump;
47
48 pub fn dispatch(sq: Sq, command: Command)
49 -> Result<()>
50 {
51 tracer!(TRACE, "packet::dispatch");
52 match command.subcommand {
53 Subcommands::Armor(command) =>
54 armor::dispatch(sq, command)?,
55 Subcommands::Dearmor(command) =>
56 dearmor::dispatch(sq, command)?,
57 Subcommands::Dump(command) => {
58 let mut input = if command.cert.is_empty() {
59 if let Some(path) = command.input.inner() {
60 if ! path.exists() &&
61 format!("{}", command.input).parse::<KeyHandle>().is_ok() {
62 weprintln!("The file {} does not exist, \
63 did you mean \"sq packet dump \
64 --cert-file {}\"?",
65 path.display(), path.display());
66 }
67 }
68
69 Box::new(command.input.open("OpenPGP packets")?)
70 as Box<dyn io::Read + Send + Sync>
71 } else {
72 let cert = sq.resolve_cert(&command.cert, TrustThreshold::Full)?.0;
73 let bytes = cert.as_tsk().to_vec()
74 .context("Serializing certificate")?;
75
76 Box::new(io::Cursor::new(bytes))
77 };
78
79 let output_type = command.output;
80 let mut output = output_type.create_unsafe(&sq)?;
81
82 let width = if let Some((width, _)) = terminal_size() {
83 Some(width.0.into())
84 } else {
85 None
86 };
87 let secrets =
88 load_keys(command.recipient_file.iter())?;
89 dump::dump(&sq,
90 secrets,
91 &mut input, &mut output,
92 command.mpis, command.hex,
93 command.session_key, width)?;
94 },
95
96 Subcommands::Decrypt(command) => {
97 let mut input = command.input.open("an encrypted message")?;
98 let mut output = command.output.create_pgp_safe(
99 &sq,
100 command.binary,
101 openpgp::armor::Kind::Message,
102 )?;
103
104 let secrets =
105 load_keys(command.secret_key_file.iter())?;
106 let session_keys = command.session_key;
107 commands::decrypt::decrypt_unwrap(
108 sq,
109 &mut input, &mut output,
110 secrets,
111 session_keys,
112 command.dump_session_key)?;
113 output.finalize()?;
114 },
115
116 Subcommands::Split(command) =>
117 split(sq, command)?,
118 Subcommands::Join(command) => {
119 join(sq, command)?;
120 }
121 }
122
123 Ok(())
124 }
125
126
127 pub fn split(sq: Sq, c: SplitCommand) -> Result<()>
128 {
129 let input = c.input.open("OpenPGP packets")?;
130
131 // If --binary is given, the user has to provide a prefix.
132 assert!(! c.binary || c.prefix.is_some(),
133 "clap failed to enforce --binary requiring --prefix");
134
135 // We either emit one stream, or open one file per packet.
136 let mut sink = match c.prefix {
137 Some(p) => Err(p),
138 None => Ok(
139 c.output
140 .unwrap_or_default()
141 .create_pgp_safe(&sq, true, Kind::SecretKey)?),
142 };
143
144 // We (ab)use the mapping feature to create byte-accurate dumps of
145 // nested packets.
146 let mut ppr =
147 openpgp::parse::PacketParserBuilder::from_buffered_reader(input)?
148 .buffer_unread_content()
149 .map(true).build()?;
150
151 fn join(pos: &[usize], delimiter: &str) -> String {
152 pos.iter().map(ToString::to_string).collect::<Vec<_>>().join(delimiter)
153 }
154
155 if let Ok(sink) = sink.as_mut() {
156 sink.write_all(b"\
157 # You can open this file in your preferred editor, rearrange and
158 # remove the packets, and add new ones. When you are happy, you
159 # can recombine the packets using sq packet join.
160
161 ")?;
162 }
163
164 let mut first = true;
165 while let PacketParserResult::Some(pp) = ppr {
166 if let Some(map) = pp.map() {
167 let mut sink: Box<dyn io::Write> = match &mut sink {
168 Ok(sink) => Box::new(sink),
169 Err(prefix) => {
170 // Construct the filename:
171 //
172 // PREFIX - PATH - [Unknown-]TAG
173
174 // Start with the prefix.
175 let mut filename = prefix.clone();
176
177 // Add the path.
178 filename.push("-");
179 filename.push(join(pp.path(), "-"));
180
181 // Add the tag.
182 filename.push("-");
183 filename.push(
184 pp.packet.kind().map(|_| "").unwrap_or("Unknown-"));
185 filename.push(
186 pp.packet.tag().to_string().replace(" ", "-"));
187
188 let sink = File::create(filename)
189 .context("Failed to create output file")?;
190 Box::new(sink)
191 }
192 };
193
194 if c.binary {
195 // Write all the bytes.
196 for field in map.iter() {
197 sink.write_all(field.as_bytes())?;
198 }
199 } else {
200 let mut headers = vec![
201 ("Comment", if let Some(i) = c.input.inner() {
202 format!(
203 "{}[{}]: {}", i.display(), join(pp.path(), "."),
204 pp.packet.tag())
205 } else {
206 format!(
207 "{}: {}", join(pp.path(), "."), pp.packet.tag())
208 }),
209 ];
210
211 match &pp.packet {
212 Packet::PKESK(p) => if let Some(r) = p.recipient() {
213 headers.push(
214 ("Comment", format!("Recipient: {}", r)));
215 },
216 Packet::PublicKey(k) => headers.push(
217 ("Comment", format!("Fingerprint: {}", k.fingerprint()))),
218 Packet::PublicSubkey(k) => headers.push(
219 ("Comment", format!("Fingerprint: {}", k.fingerprint()))),
220 Packet::SecretKey(k) => headers.push(
221 ("Comment", format!("Fingerprint: {}", k.fingerprint()))),
222 Packet::SecretSubkey(k) => headers.push(
223 ("Comment", format!("Fingerprint: {}", k.fingerprint()))),
224 Packet::Signature(s) => {
225 headers.push(("Comment", format!("Type: {}", s.typ())));
226 if let Some(t) = s.signature_creation_time() {
227 headers.push(("Comment", format!("Created: {}", t.convert())));
228 }
229 if let Some(i) = s.get_issuers().get(0) {
230 headers.push(
231 ("Comment", format!("Issuer: {}", i)));
232 if let Ok(cert) = sq.lookup_one(i, None, false) {
233 headers.push(
234 ("Comment",
235 format!("Issuer: {}",
236 sq.best_userid(&cert, true).display())));
237 }
238 }
239 },
240 Packet::UserID(u) => headers.push(
241 ("Comment", format!("UserID: {}", ui::Safe(u)))),
242 _ => (),
243 }
244
245 // Provide more structure to the human reader.
246 if ! first {
247 writeln!(sink)?;
248 writeln!(sink)?;
249 }
250
251 let mut writer = Writer::with_headers(
252 &mut sink, Kind::File, headers)?;
253
254 // Write all the bytes.
255 for field in map.iter() {
256 writer.write_all(field.as_bytes())?;
257 }
258 writer.finalize()?;
259 }
260
261 first = false;
262 }
263
264 ppr = pp.recurse()?.1;
265 }
266 Ok(())
267 }
268
269 /// Joins the given files.
270 pub fn join(sq: Sq, c: JoinCommand) -> Result<()> {
271 // Either we know what kind of armor we want to produce, or we
272 // need to detect it using the first packet we see.
273 let kind = c.kind.into();
274 let output = c.output.for_secrets();
275 let mut sink = if c.binary {
276 // No need for any auto-detection.
277 Some(output.create_pgp_safe(
278 &sq, true, openpgp::armor::Kind::File)?)
279 } else if let Some(kind) = kind {
280 Some(output.create_pgp_safe(&sq, false, kind)?)
281 } else {
282 None // Defer.
283 };
284
285 /// Writes a bit-accurate copy of all top-level packets in PPR to
286 /// OUTPUT.
287 fn copy<'a, 'b, 'pp>(sq: &Sq,
288 mut ppr: PacketParserResult<'pp>,
289 output: &'a FileOrStdout,
290 sink: &'b mut Option<Message<'a>>)
291 -> Result<PacketParserResult<'pp>> {
292 while let PacketParserResult::Some(pp) = ppr {
293 if sink.is_none() {
294 // Autodetect using the first packet.
295 let kind = match pp.packet.tag() {
296 Tag::Signature => openpgp::armor::Kind::Signature,
297 Tag::SecretKey => openpgp::armor::Kind::SecretKey,
298 Tag::PublicKey => openpgp::armor::Kind::PublicKey,
299 Tag::PKESK | Tag::SKESK | Tag::OnePassSig =>
300 openpgp::armor::Kind::Message,
301 _ => openpgp::armor::Kind::File,
302 };
303
304 *sink = Some(
305 output.create_pgp_safe(&sq, false, kind)?
306 );
307 }
308
309 // We (ab)use the mapping feature to create byte-accurate
310 // copies.
311 for field in pp.map().expect("must be mapped").iter() {
312 sink.as_mut().expect("initialized at this point")
313 .write_all(field.as_bytes())?;
314 }
315
316 ppr = pp.next()?.1;
317 }
318 Ok(ppr)
319 }
320
321 /// Writes a bit-accurate copy of all top-level packets in all
322 /// armored sections in the input to OUTPUT.
323 fn copy_all<'a, 'b>(sq: &Sq,
324 mut ppr: PacketParserResult,
325 output: &'a FileOrStdout,
326 sink: &'b mut Option<Message<'a>>)
327 -> Result<()>
328 {
329 // First, copy all the packets, armored or not.
330 ppr = copy(sq, ppr, output, sink)?;
331
332 loop {
333 // Now, the parser is exhausted, but we may find another
334 // armored blob. Note that this can only happen if the
335 // first set of packets was also armored.
336 match ppr {
337 PacketParserResult::Some(_) =>
338 unreachable!("copy exhausted the packet parser"),
339 PacketParserResult::EOF(eof) => {
340 // See if there is another armor block.
341 let reader = eof.into_reader();
342 ppr = match
343 PacketParserBuilder::from_buffered_reader(reader)
344 .and_then(
345 |builder| builder
346 .buffer_unread_content()
347 .map(true)
348 .dearmor(Dearmor::Enabled(
349 ReaderMode::Tolerant(None)))
350 .build())
351 {
352 Ok(ppr) => ppr,
353 Err(e) => {
354 // There isn't, or we encountered an error.
355 if let Some(e) = e.downcast_ref::<io::Error>() {
356 if e.kind() == io::ErrorKind::UnexpectedEof {
357 return Ok(());
358 }
359 }
360
361 return Err(e);
362 },
363 }
364 },
365 }
366
367 // We found another armor block, copy all the packets.
368 ppr = copy(sq, ppr, output, sink)?;
369 }
370 }
371
372 if !c.input.is_empty() {
373 for name in c.input {
374 let ppr =
375 openpgp::parse::PacketParserBuilder::from_file(name)?
376 .buffer_unread_content()
377 .map(true).build()?;
378 copy_all(&sq, ppr, &output, &mut sink)?;
379 }
380 } else {
381 let ppr =
382 openpgp::parse::PacketParserBuilder::from_reader(StdinWarning::openpgp())?
383 .buffer_unread_content()
384 .map(true).build()?;
385 copy_all(&sq, ppr, &output, &mut sink)?;
386 }
387
388 if sink.is_none() {
389 // We haven't written anything.
390 sink = Some(output.create_pgp_safe(
391 &sq, true, openpgp::armor::Kind::File)?);
392 }
393
394 sink.unwrap().finalize()?;
395 Ok(())
396 }