1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
|
use failure::{self, ResultExt};
use std::fs;
use std::io;
use std::path::PathBuf;
use tempfile::NamedTempFile;
extern crate sequoia_openpgp as openpgp;
use crate::openpgp::armor;
use crate::openpgp::crypto;
use crate::openpgp::{Packet, Result};
use crate::openpgp::packet::Signature;
use crate::openpgp::parse::{
Parse,
PacketParserResult,
};
use crate::openpgp::serialize::Serialize;
use crate::openpgp::serialize::stream::{
Message, Signer, LiteralWriter,
};
use crate::create_or_stdout;
pub fn sign(input: &mut io::Read, output_path: Option<&str>,
secrets: Vec<openpgp::TPK>, detached: bool, binary: bool,
append: bool, notarize: bool, force: bool)
-> Result<()> {
match (detached, append|notarize) {
(_, false) | (true, true) =>
sign_data(input, output_path, secrets, detached, binary, append,
force),
(false, true) =>
sign_message(input, output_path, secrets, binary, notarize, force),
}
}
fn sign_data(input: &mut io::Read, output_path: Option<&str>,
secrets: Vec<openpgp::TPK>, detached: bool, binary: bool,
append: bool, force: bool)
-> Result<()> {
let (mut output, prepend_sigs, tmp_path):
(Box<io::Write>, Vec<Signature>, Option<PathBuf>) =
if detached && append && output_path.is_some() {
// First, read the existing signatures.
let mut sigs = Vec::new();
let mut ppr =
openpgp::parse::PacketParser::from_file(output_path.unwrap())?;
while let PacketParserResult::Some(pp) = ppr {
let (packet, ppr_tmp) = pp.recurse()?;
ppr = ppr_tmp;
match packet {
Packet::Signature(sig) => sigs.push(sig),
p => return Err(
failure::err_msg(
format!("{} in detached signature", p.tag()))
.context("Invalid detached signature").into()),
}
}
// Then, create a temporary file to write to. If we are
// successful with adding our signature(s), we rename the
// file replacing the old one.
let tmp_file = NamedTempFile::new_in(
PathBuf::from(output_path.unwrap()).parent()
.unwrap_or(&PathBuf::from(".")))?;
let tmp_path = tmp_file.path().into();
(Box::new(tmp_file), sigs, Some(tmp_path))
} else {
(create_or_stdout(output_path, force)?, Vec::new(), None)
};
let mut output = if ! binary {
Box::new(armor::Writer::new(&mut output,
if detached {
armor::Kind::Signature
} else {
armor::Kind::Message
},
&[])?)
} else {
output
};
let mut keypairs = super::get_signing_keys(&secrets)?;
let signers = keypairs.iter_mut()
.map(|s| -> &mut dyn crypto::Signer<_> { s })
.collect();
// When extending a detached signature, prepend any existing
// signatures first.
for sig in prepend_sigs.into_iter() {
Packet::Signature(sig).serialize(&mut output)?;
}
// Stream an OpenPGP message.
let sink = Message::new(output);
let signer = if detached {
Signer::detached(sink, signers, None)
} else {
Signer::new(sink, signers, None)
}.context("Failed to create signer")?;
let mut writer = if detached {
// Detached signatures do not need a literal data packet, just
// hash the data as is.
signer
} else {
// We want to wrap the data in a literal data packet.
LiteralWriter::new(signer, None, None, None)
.context("Failed to create literal writer")?
};
// Finally, copy stdin to our writer stack to sign the data.
io::copy(input, &mut writer)
.context("Failed to sign")?;
writer.finalize()
.context("Failed to sign")?;
if let Some(path) = tmp_path {
// Atomically replace the old file.
fs::rename(path,
output_path.expect("must be Some if tmp_path is Some"))?;
}
Ok(())
}
fn sign_message(input: &mut io::Read, output_path: Option<&str>,
secrets: Vec<openpgp::TPK>, binary: bool, notarize: bool,
force: bool)
-> Result<()> {
let mut output = create_or_stdout(output_path, force)?;
let output = if ! binary {
Box::new(armor::Writer::new(&mut output,
armor::Kind::Message,
&[])?)
} else {
output
};
let mut keypairs = super::get_signing_keys(&secrets)?;
// We need to create the signers here, so that we can take() them
// once in the parsing loop. We cannot create the references in
// the loop, because the borrow checker does not understand that
// it happens only once.
let mut signers = Some(keypairs.iter_mut()
.map(|s| -> &mut dyn crypto::Signer<_> { s })
.collect::<Vec<&mut dyn crypto::Signer<_>>>());
let mut sink = Message::new(output);
// Create a parser for the message to be notarized.
let mut ppr
= openpgp::parse::PacketParser::from_reader(input)
.context("Failed to build parser")?;
// Once we see a signature, we can no longer strip compression.
let mut seen_signature = false;
#[derive(PartialEq, Eq, Debug)]
enum State {
InFirstSigGroup,
AfterFirstSigGroup,
Signing {
// Counts how many signatures are being notarized. If
// this drops to zero, we pop the signer from the stack.
signature_count: isize,
}
|