Debian Codegraph @

src/commands/sign.rs

raw
1 use anyhow::Context as _;
2 use std::fs;
3 use std::io;
4 use std::path::PathBuf;
5 use tempfile::NamedTempFile;
6
7 use buffered_reader::BufferedReader;
8
9 use sequoia_openpgp as openpgp;
10 use openpgp::armor;
11 use openpgp::crypto;
12 use openpgp::{Packet, Result};
13 use openpgp::packet::prelude::*;
14 use openpgp::packet::signature::subpacket::NotationData;
15 use openpgp::parse::{
16 Cookie,
17 Parse,
18 PacketParserResult,
19 };
20 use openpgp::serialize::Serialize;
21 use openpgp::serialize::stream::{
22 Message, Armorer, Signer, LiteralWriter,
23 };
24 use openpgp::types::SignatureType;
25
26
27 use crate::Sq;
28
29 use crate::cli;
30 use crate::cli::sign::Mode;
31 use crate::cli::types::FileOrStdin;
32 use crate::cli::types::FileOrStdout;
33 use crate::sq::TrustThreshold;
34
35 mod merge_signatures;
36 use merge_signatures::merge_signatures;
37
38 pub fn dispatch(sq: Sq, command: cli::sign::Command) -> Result<()> {
39 tracer!(TRACE, "sign::dispatch");
40
41 let mut input = command.input.open("the data to sign")?;
42 let output = &command.output;
43 let detached = &command.detached;
44 let binary = command.binary;
45 let append = command.append;
46 let notarize = command.notarize;
47 if notarize {
48 return Err(anyhow::anyhow!("Notarizing messages is not supported."));
49 }
50
51 let signers =
52 sq.resolve_certs_or_fail(&command.signers, TrustThreshold::Full)?;
53 let signers = sq.get_signing_keys(&signers, None)?;
54 if signers.is_empty() && command.merge.is_none() {
55 return Err(anyhow::anyhow!("No signing keys found"));
56 }
57
58 let notations = command.signature_notations.parse()?;
59
60 if let Some(merge) = command.merge {
61 let output = output.create_pgp_safe(
62 &sq,
63 binary,
64 armor::Kind::Message,
65 )?;
66 let data: FileOrStdin = merge.into();
67 let mut input2 = data.open("OpenPGP signatures")?;
68 return merge_signatures(&mut input, &mut input2, output);
69 }
70
71 if command.cleartext {
72 let output = output.create_safe(&sq)?;
73 clearsign(sq, input, output, signers, &notations)?;
74 } else {
75 sign(sq,
76 &mut input,
77 detached.as_ref().unwrap_or(output),
78 signers,
79 command.mode,
80 detached.is_some(),
81 binary,
82 append,
83 notarize,
84 &notations)?;
85 }
86
87 Ok(())
88 }
89
90 pub fn sign<'a, 'store, 'rstore>(
91 sq: Sq<'store, 'rstore>,
92 input: &'a mut (dyn BufferedReader<Cookie> + Sync + Send),
93 output: &'a FileOrStdout,
94 signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>,
95 mode: Mode,
96 detached: bool,
97 binary: bool,
98 append: bool,
99 notarize: bool,
100 notations: &'a [(bool, NotationData)])
101 -> Result<()>
102 {
103 match (detached, append|notarize) {
104 (_, false) | (true, true) =>
105 sign_data(sq,
106 input,
107 output,
108 signers,
109 mode,
110 detached,
111 binary,
112 append,
113 notations),
114 (false, true) =>
115 sign_message(sq,
116 input,
117 output,
118 signers,
119 mode,
120 binary,
121 notarize,
122 notations),
123 }
124 }
125
126 fn sign_data<'a, 'store, 'rstore>(
127 sq: Sq<'store, 'rstore>,
128 input: &'a mut (dyn BufferedReader<Cookie> + Sync + Send),
129 output_path: &'a FileOrStdout,
130 mut signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>,
131 mode: Mode,
132 detached: bool,
133 binary: bool,
134 append: bool,
135 notations: &'a [(bool, NotationData)])
136 -> Result<()>
137 {
138 let (mut output, prepend_sigs, tmp_path):
139 (Box<dyn io::Write + Sync + Send>, Vec<Signature>, Option<PathBuf>) =
140 if detached && append && output_path.path().is_some() {
141 let output_path = output_path.path().unwrap();
142 // First, read the existing signatures.
143 let mut sigs = Vec::new();
144 let mut ppr =
145 openpgp::parse::PacketParser::from_file(output_path)?;
146
147 while let PacketParserResult::Some(pp) = ppr {
148 let (packet, ppr_tmp) = pp.recurse()?;
149 ppr = ppr_tmp;
150
151 match packet {
152 Packet::Signature(sig) => sigs.push(sig),
153 p => return Err(
154 anyhow::anyhow!(
155 format!("{} in detached signature", p.tag()))
156 .context("Invalid detached signature")),
157 }
158 }
159
160 // Then, create a temporary file to write to. If we are
161 // successful with adding our signature(s), we rename the
162 // file replacing the old one.
163 let tmp_file = NamedTempFile::new_in(
164 PathBuf::from(output_path).parent()
165 .unwrap_or(&PathBuf::from(".")))?;
166 let tmp_path = tmp_file.path().into();
167 (Box::new(tmp_file), sigs, Some(tmp_path))
168 } else {
169 (output_path.create_safe(&sq)?, Vec::new(), None)
170 };
171
172 // Stream an OpenPGP message.
173 // The sink may be a NamedTempFile. Carefully keep a reference so
174 // that we can rename it.
175 let mut message = Message::new(&mut output);
176 if ! binary {
177 message = Armorer::new(message)
178 .kind(if detached {
179 armor::Kind::Signature
180 } else {
181 armor::Kind::Message
182 })
183 .build()?;
184 }
185
186 // When extending a detached signature, prepend any existing
187 // signatures first.
188 for sig in prepend_sigs.into_iter() {
189 Packet::Signature(sig).serialize(&mut message)?;
190 }
191
192 let mut builder = SignatureBuilder::new(mode.into());
193 for (critical, n) in notations.iter() {
194 builder = builder.add_notation(
195 n.name(),
196 n.value(),
197 Some(n.flags().clone()),
198 *critical)?;
199 }
200
201 let mut signer = Signer::with_template(
202 message,
203 signers.pop().unwrap().1,
204 builder)?;
205 signer = signer.creation_time(sq.time);
206 for s in signers {
207 signer = signer.add_signer(s.1)?;
208 }
209 if detached {
210 signer = signer.detached();
211 }
212 let signer = signer.build().context("Failed to create signer")?;
213
214 let mut writer = if detached {
215 // Detached signatures do not need a literal data packet, just
216 // hash the data as is.
217 signer
218 } else {
219 // We want to wrap the data in a literal data packet.
220 LiteralWriter::new(signer).build()
221 .context("Failed to create literal writer")?
222 };
223
224 // Finally, copy stdin to our writer stack to sign the data.
225 input.copy(&mut writer)
226 .context("Failed to sign")?;
227
228 writer.finalize()
229 .context("Failed to sign")?;
230
231 if let Some(path) = tmp_path {
232 // Atomically replace the old file.
233 fs::rename(
234 path,
235 output_path.path().expect("must be Some if tmp_path is Some"),
236 )?;
237 }
238 Ok(())
239 }
240
241 fn sign_message<'a, 'store, 'rstore>(
242 sq: Sq<'store, 'rstore>,
243 input: &'a mut (dyn BufferedReader<Cookie> + Sync + Send),
244 output: &'a FileOrStdout,
245 signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>,
246 mode: Mode,
247 binary: bool,
248 notarize: bool,
249 notations: &'a [(bool, NotationData)])
250 -> Result<()>
251 {
252 let mut output = output.create_pgp_safe(
253 &sq,
254 binary,
255 armor::Kind::Message,
256 )?;
257 sign_message_(sq,
258 input,
259 signers,
260 mode,
261 notarize,
262 notations,
263 &mut output)?;
264 output.finalize()?;
265 Ok(())
266 }
267
268 fn sign_message_<'a, 'store, 'rstore>(
269 sq: Sq<'store, 'rstore>,
270 input: &'a mut (dyn BufferedReader<Cookie> + Sync + Send),
271 mut signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>,
272 mode: Mode,
273 notarize: bool,
274 notations: &'a [(bool, NotationData)],
275 output: &mut (dyn io::Write + Sync + Send))
276 -> Result<()>
277 {
278 let mut sink = Message::new(output);
279
280 // Create a parser for the message to be notarized.
281 let mut ppr
282 = openpgp::parse::PacketParser::from_reader(input)
283 .context("Failed to build parser")?;
284
285 // Once we see a signature, we can no longer strip compression.
286 let mut seen_signature = false;
287 #[derive(PartialEq, Eq, Debug)]
288 enum State {
289 InFirstSigGroup,
290 AfterFirstSigGroup,
291 Signing {
292 // Counts how many signatures are being notarized. If
293 // this drops to zero, we pop the signer from the stack.
294 signature_count: isize,
295 },
296 Done,
297 }
298 let mut state =
299 if ! notarize {
300 State::InFirstSigGroup
301 } else {
302 // Pretend we have passed the first signature group so
303 // that we put our signature first.
304 State::AfterFirstSigGroup
305 };
306
307 while let PacketParserResult::Some(mut pp) = ppr {
308 if let Err(err) = pp.possible_message() {
309 return Err(err.context("Malformed OpenPGP message"));
310 }
311
312 match pp.packet {
313 Packet::PKESK(_) | Packet::SKESK(_) =>
314 return Err(anyhow::anyhow!(
315 "Signing encrypted data is not implemented")),
316
317 Packet::Literal(_) =>
318 if let State::InFirstSigGroup = state {
319 // Cope with messages that have no signatures, or
320 // with a ops packet without the last flag.
321 state = State::AfterFirstSigGroup;
322 },
323
324 // To implement this, we'd need to stream the
325 // compressed data packet inclusive framing, but
326 // currently the partial body filter transparently
327 // removes the framing.
328 //
329 // If you do implement this, there is a half-disabled test
330 // in tests/sq-sign.rs.
331 Packet::CompressedData(_) if seen_signature =>
332 return Err(anyhow::anyhow!(
333 "Signing a compress-then-sign message is not implemented")),
334
335 _ => (),
336 }
337
338 match state {
339 State::AfterFirstSigGroup => {
340 // After the first signature group, we push the signer
341 // onto the writer stack.
342 let mut builder = SignatureBuilder::new(mode.into());
343 for (critical, n) in notations.iter() {
344 builder = builder.add_notation(
345 n.name(),
346 n.value(),
347 Some(n.flags().clone()),
348 *critical)?;
349 }
350
351 let mut signer = Signer::with_template(
352 sink, signers.pop().unwrap().1, builder)?;
353 signer = signer.creation_time(sq.time);
354 for s in signers.drain(..) {
355 signer = signer.add_signer(s.1)?;
356 }
357 sink = signer.build().context("Failed to create signer")?;
358 state = State::Signing { signature_count: 0, };
359 },
360
361 State::Signing { signature_count } if signature_count == 0 => {
362 // All signatures that are being notarized are
363 // written, pop the signer from the writer stack.
364 sink = sink.finalize_one()
365 .context("Failed to sign data")?
366 .unwrap();
367 state = State::Done;
368 },
369
370 _ => (),
371 }
372
373 if let Packet::Literal(_) = pp.packet {
374 let l = if let Packet::Literal(l) = pp.packet.clone() {
375 l
376 } else {
377 unreachable!()
378 };
379 // Create a literal writer to wrap the data in a literal
380 // message packet.
381 let mut literal = LiteralWriter::new(sink).format(l.format());
382 if let Some(f) = l.filename() {
383 literal = literal.filename(f)?;
384 }
385 if let Some(d) = l.date() {
386 literal = literal.date(d)?;
387 }
388
389 let mut literal = literal.build()
390 .context("Failed to create literal writer")?;
391
392 // Finally, just copy all the data.
393 pp.copy(&mut literal)
394 .context("Failed to sign data")?;
395
396 // Pop the literal writer.
397 sink = literal.finalize_one()
398 .context("Failed to sign data")?
399 .unwrap();
400 }
401
402 let (packet, ppr_tmp) = if seen_signature {
403 // Once we see a signature, we can no longer strip
404 // compression.
405 pp.next()
406 } else {
407 pp.recurse()
408 }.context("Parsing failed")?;
409 ppr = ppr_tmp;
410
411 match packet {
412 Packet::OnePassSig(mut ops) => {
413 let was_last = ops.last();
414 match state {
415 State::InFirstSigGroup => {
416 // We want to append our signature here, hence
417 // we set last to false.
418 ops.set_last(false);
419
420 if was_last {
421 // The signature group ends here.
422 state = State::AfterFirstSigGroup;
423 }
424 },
425
426 State::Signing { ref mut signature_count } =>
427 *signature_count += 1,
428
429 _ => (),
430 }
431
432 Packet::OnePassSig(ops).serialize(&mut sink)?;
433 seen_signature = true;
434 },
435
436 Packet::Signature(sig) => {
437 Packet::Signature(sig).serialize(&mut sink)
438 .context("Failed to serialize")?;
439 if let State::Signing { ref mut signature_count } = state {
440 *signature_count -= 1;
441 }
442 },
443 _ => (),
444 }
445 }
446
447 if let PacketParserResult::EOF(eof) = ppr {
448 if let Err(err) = eof.is_message() {
449 return Err(err.context("Malformed OpenPGP message"));
450 }
451 } else {
452 unreachable!()
453 }
454
455 match state {
456 State::Signing { signature_count } => {
457 assert_eq!(signature_count, 0);
458 sink.finalize()
459 .context("Failed to sign data")?;
460 },
461 State::Done => (),
462 _ => panic!("Unexpected state: {:?}", state),
463 }
464
465 Ok(())
466 }
467
468 pub fn clearsign(sq: Sq,
469 mut input: impl BufferedReader<Cookie> + Sync + Send,
470 mut output: impl io::Write + Sync + Send,
471 mut signers: Vec<(openpgp::Cert, Box<dyn crypto::Signer + Send + Sync>)>,
472 notations: &[(bool, NotationData)])
473 -> Result<()>
474 {
475 // Prepare a signature template.
476 let mut builder = SignatureBuilder::new(SignatureType::Text);
477 for (critical, n) in notations.iter() {
478 builder = builder.add_notation(
479 n.name(),
480 n.value(),
481 Some(n.flags().clone()),
482 *critical)?;
483 }
484
485 let message = Message::new(&mut output);
486 let mut signer = Signer::with_template(
487 message, signers.pop().unwrap().1, builder)?
488 .cleartext();
489 signer = signer.creation_time(sq.time);
490 for s in signers {
491 signer = signer.add_signer(s.1)?;
492 }
493 let mut message = signer.build().context("Failed to create signer")?;
494
495 // Finally, copy stdin to our writer stack to sign the data.
496 input.copy(&mut message)
497 .context("Failed to sign")?;
498
499 message.finalize()
500 .context("Failed to sign")?;
501
502 Ok(())
503 }