Debian Codegraph @

src/commands/keyring.rs

raw
1 use std::{
2 collections::btree_map::{BTreeMap, Entry},
3 fs::File,
4 io,
5 path::PathBuf,
6 };
7 use std::ops::Deref;
8 use anyhow::Context;
9
10 use sequoia_openpgp as openpgp;
11 use openpgp::{
12 Result,
13 armor,
14 cert::{
15 Cert,
16 CertParser,
17 },
18 Fingerprint,
19 KeyHandle,
20 KeyID,
21 packet::{
22 Packet,
23 UserID,
24 UserAttribute,
25 Key,
26 Signature,
27 Tag,
28 key,
29 },
30 parse::{
31 PacketParser,
32 PacketParserResult,
33 },
34 parse::Parse,
35 serialize::Serialize,
36 };
37
38 use crate::{
39 Sq,
40 Model,
41 cli::types::FileOrStdout,
42 output::KeyringListItem,
43 };
44
45 use crate::cli::keyring;
46 use crate::cli::types::StdinWarning;
47
48 pub fn dispatch(sq: Sq, c: keyring::Command) -> Result<()> {
49 use keyring::Subcommands::*;
50 match c.subcommand {
51 Filter(command) => {
52 let any_uid_predicates =
53 ! command.userid.is_empty()
54 || !command.name.is_empty()
55 || !command.email.is_empty()
56 || !command.domain.is_empty();
57 let uid_predicate = |uid: &UserID| {
58 let mut keep = false;
59
60 for userid in &command.userid {
61 keep |= uid.value() == userid.as_bytes();
62 }
63
64 for name in &command.name {
65 keep |= uid
66 .name().unwrap_or(None)
67 .map(|n| n == name)
68 .unwrap_or(false);
69 }
70
71 for email in &command.email {
72 keep |= uid
73 .email().unwrap_or(None)
74 .map(|n| n == email)
75 .unwrap_or(false);
76 }
77
78 for domain in &command.domain {
79 keep |= uid
80 .email().unwrap_or(None)
81 .map(|n| n.ends_with(&format!("@{}", domain)))
82 .unwrap_or(false);
83 }
84
85 keep
86 };
87
88 let any_ua_predicates = false;
89 let ua_predicate = |_ua: &UserAttribute| false;
90
91 let any_cert_predicates = ! command.cert.is_empty();
92 let cert_predicate = |key: &Key<_, key::PrimaryRole>| {
93 let mut keep = false;
94
95 for handle in &command.cert {
96 keep |= handle.aliases(key.key_handle());
97 }
98
99 keep
100 };
101
102 let any_key_predicates = ! command.key.is_empty();
103 let key_predicate = |key: &Key<_, key::SubordinateRole>| {
104 let mut keep = false;
105
106 for handle in &command.key {
107 keep |= handle.aliases(key.key_handle());
108 }
109
110 keep
111 };
112
113 let filter_fn = |c: Cert| -> Option<Cert> {
114 if ! (any_uid_predicates
115 || any_ua_predicates
116 || any_cert_predicates
117 || any_key_predicates) {
118 // If there are no filters, pass it through.
119 Some(c)
120 } else if ! (c.userids().any(|c| uid_predicate(c.userid()))
121 || c.user_attributes().any(|c| ua_predicate(c.user_attribute()))
122 || cert_predicate(c.primary_key().key())
123 || key_predicate(c.primary_key().key().role_as_subordinate())
124 || c.keys().subkeys().any(|c| key_predicate(c.key()))) {
125 None
126 } else if command.prune_certs {
127 let c = c
128 .retain_userids(|c| {
129 ! any_uid_predicates || uid_predicate(c.userid())
130 })
131 .retain_user_attributes(|c| {
132 ! any_ua_predicates || ua_predicate(c.user_attribute())
133 })
134 .retain_subkeys(|c| {
135 ! any_key_predicates || key_predicate(c.key())
136 });
137 if (c.userids().next().is_none()
138 && c.user_attributes().next().is_none()
139 && c.keys().subkeys().next().is_none())
140 || ((any_key_predicates
141 && c.keys().subkeys().next().is_none())
142 && (any_cert_predicates
143 && ! cert_predicate(c.primary_key().key())))
144 {
145 // We stripped all components, omit this cert.
146 None
147 } else {
148 Some(c)
149 }
150 } else {
151 Some(c)
152 }
153 };
154
155 filter(&sq, command.input, command.output, filter_fn,
156 false, command.to_certificate)
157 },
158 Merge(c) =>
159 merge(&sq, c.input, c.output, false),
160 List(c) => {
161 let mut input = c.input.open("OpenPGP certificates")?;
162 list(sq, &mut input, c.all_userids)
163 },
164 Split(c) => {
165 let mut input = c.input.open("OpenPGP certificates")?;
166 let prefix =
167 // The prefix is either specified explicitly...
168 c.prefix.unwrap_or(
169 // ... or we derive it from the input file...
170 c.input.and_then(|x| {
171 // (but only use the filename)
172 x.file_name().map(|f|
173 String::from(f.to_string_lossy())
174 )
175 })
176 // ... or we use a generic prefix...
177 .unwrap_or_else(|| String::from("output"))
178 // ... finally, add a hyphen to the derived prefix.
179 + "-");
180 split(&mut input, &prefix, false)
181 },
182 }
183 }
184
185 /// Joins certificates and keyrings into a keyring, applying a filter.
186 fn filter<F>(sq: &Sq, inputs: Vec<PathBuf>, output: FileOrStdout,
187 mut filter: F,
188 binary: bool,
189 to_certificate: bool)
190 -> Result<()>
191 where F: FnMut(Cert) -> Option<Cert>,
192 {
193 let mut certs = Vec::new();
194
195 if !inputs.is_empty() {
196 for name in inputs {
197 for cert in CertParser::from_file(name.deref())? {
198 match cert {
199 Ok(c) => certs.push(c),
200 Err(e) =>
201 weprintln!("Malformed certificate in keyring {}: {}",
202 name.display(), e),
203 }
204 }
205 }
206 } else {
207 for cert in CertParser::from_reader(StdinWarning::certs())? {
208 match cert {
209 Ok(c) => certs.push(c),
210 Err(e) =>
211 weprintln!("Malformed certificate in keyring: {}", e),
212 }
213 }
214 }
215
216 let mut output = output.for_secrets().create_pgp_safe(
217 &sq,
218 binary,
219 if ! to_certificate && certs.iter().any(|c| c.is_tsk()) {
220 armor::Kind::SecretKey
221 } else {
222 armor::Kind::PublicKey
223 },
224 )?;
225
226 for cert in certs {
227 if let Some(cert) = filter(cert) {
228 if to_certificate {
229 cert.serialize(&mut output)?;
230 } else {
231 cert.as_tsk().serialize(&mut output)?;
232 }
233 }
234 }
235 output.finalize()?;
236
237 Ok(())
238 }
239
240 /// Lists certs in a keyring.
241 fn list(sq: Sq,
242 input: &mut (dyn io::Read + Sync + Send),
243 list_all_uids: bool)
244 -> Result<()>
245 {
246 let mut certs = vec![];
247 let iter = CertParser::from_reader(input)?
248 .map(|item| KeyringListItem::from_cert_with_sq(item, &sq));
249 for item in iter {
250 certs.push(item);
251 }
252 let list = Model::keyring_list(certs, list_all_uids)?;
253 list.write(&mut std::io::stdout())?;
254 Ok(())
255 }
256
257 /// Splits a keyring into individual certs.
258 fn split(input: &mut (dyn io::Read + Sync + Send), prefix: &str, binary: bool)
259 -> Result<()> {
260 for (i, cert) in CertParser::from_reader(input)?.enumerate() {
261 let (filename, cert) = match cert {
262 Ok(cert) => {
263 let filename = format!(
264 "{}{}-{:X}",
265 prefix,
266 i,
267 cert.fingerprint());
268 (filename, Ok(cert))
269 },
270 Err(mut e) => if let Some(openpgp::Error::UnsupportedCert(m, p)) =
271 e.downcast_mut::<openpgp::Error>()
272 {
273 // We didn't understand the cert. But, we can still
274 // write it out!
275 let filename = format!(
276 "{}{}-{}",
277 prefix,
278 i,
279 to_filename_fragment(m).unwrap_or_else(|| "unknown".to_string()));
280 (filename, Err(std::mem::take(p)))
281 } else {
282 return Err(e.context("Malformed certificate in keyring"));
283 },
284 };
285
286 // Try to be more helpful by including the first userid in the
287 // filename.
288 let mut sink = if let Some(f) = cert.as_ref().ok()
289 .and_then(|cert| cert.userids().next())
290 .and_then(|uid| uid.userid().email().unwrap_or(None).map(|e| e.to_string()))
291 .and_then(to_filename_fragment)
292 {
293 let filename_email = format!("{}-{}", filename, f);
294 if let Ok(s) = File::create(filename_email) {
295 s
296 } else {
297 // Degrade gracefully in case our sanitization
298 // produced an invalid filename on this system.
299 File::create(&filename)
300 .context(format!("Writing cert to {:?} failed", filename))?
301 }
302 } else {
303 File::create(&filename)
304 .context(format!("Writing cert to {:?} failed", filename))?
305 };
306
307 if binary {
308 match cert {
309 Ok(cert) => cert.as_tsk().serialize(&mut sink)?,
310 Err(packets) => for p in packets {
311 p.serialize(&mut sink)?;
312 },
313 }
314 } else {
315 let is_tsk = match &cert {
316 Ok(cert) => cert.is_tsk(),
317 Err(packets) => packets.iter().any(
318 |p| p.tag() == Tag::SecretKey || p.tag() == Tag::SecretSubkey),
319 };
320
321 use sequoia_openpgp::serialize::stream::{Message, Armorer};
322 let message = Message::new(sink);
323 let mut message = Armorer::new(message)
324 .kind(if is_tsk {
325 armor::Kind::SecretKey
326 } else {
327 armor::Kind::PublicKey
328 })
329 .build()?;
330 match cert {
331 Ok(cert) => cert.as_tsk().serialize(&mut message)?,
332 Err(packets) => for p in packets {
333 p.serialize(&mut message)?;
334 },
335 }
336 message.finalize()?;
337 }
338 }
339 Ok(())
340 }
341
342 /// Merge multiple keyrings.
343 fn merge(sq: &Sq, inputs: Vec<PathBuf>, output: FileOrStdout,
344 binary: bool)
345 -> Result<()>
346 {
347 let mut certs: BTreeMap<Fingerprint, Option<Cert>> = BTreeMap::new();
348 let mut revocations: Vec<(Signature, String)> = Vec::new();
349
350 let inputs: Box<dyn Iterator<Item = _>> = if inputs.is_empty() {
351 Box::new(std::iter::once(
352 ("stdin".to_string(),
353 PacketParser::from_reader(StdinWarning::certs()))))
354 } else {
355 Box::new(
356 inputs.into_iter()
357 .map(|name| {
358 (name.display().to_string(),
359 PacketParser::from_file(&name))
360 }))
361 };
362
363 for (name, result) in inputs {
364 let parser = result.with_context(|| format!("Opening {}", name))?;
365
366 // First see if we have a bare revocation certificate.
367 let mut is_sig = false;
368 if let PacketParserResult::Some(ref pp) = parser {
369 if let Packet::Signature(_) = pp.packet {
370 is_sig = true;
371 }
372 }
373 if is_sig {
374 // The first packet is a sig. Make sure it is *only* a
375 // sig.
376 let sig = if let PacketParserResult::Some(pp) = parser {
377 let (packet, next_ppr) = pp.next()?;
378
379 let sig = if let Packet::Signature(sig) = packet {
380 sig
381 } else {
382 return Err(anyhow::anyhow!(
383 "{}: Not a revocation certificate: got a {}.",
384 name, packet.tag()));
385 };
386
387 if let PacketParserResult::Some(_) = next_ppr {
388 return Err(anyhow::anyhow!(
389 "{}: Not a revocation certificate: \
390 got more than one packet.",
391 name));
392 }
393
394 sig
395 } else {
396 return Err(anyhow::anyhow!(
397 "{}: Not a bare revocation certificate.",
398 name));
399 };
400
401 revocations.push((sig.clone(), name));
402 continue;
403 }
404
405 // Parse it like its a keyring.
406 for cert in CertParser::from(parser) {
407 let cert = cert.context(
408 format!("Read a malformed certificate from {:?}", name))?;
409 match certs.entry(cert.fingerprint()) {
410 e @ Entry::Vacant(_) => {
411 e.or_insert(Some(cert));
412 }
413 Entry::Occupied(mut e) => {
414 let e = e.get_mut();
415 let curr = e.take().unwrap();
416 *e = Some(curr.merge_public_and_secret(cert)
417 .expect("Same certificate"));
418 }
419 }
420 }
421 }
422
423 if ! revocations.is_empty() {
424 // A map from key ID to fingerprint.
425 //
426 // This doesn't deal with colliding key IDs, but second
427 // pre-images are not feasible, so this isn't a problem in
428 // practice.
429 let by_keyid: BTreeMap<KeyID, Fingerprint>
430 = BTreeMap::from_iter(certs.values().filter_map(|cert| {
431 cert.as_ref().map(|cert| {
432 (cert.keyid(), cert.fingerprint())
433 })
434 }));
435
436 let mut die = false;
437 let mut missing = Vec::new();
438
439 'next_rev: for (sig, name) in revocations {
440 let issuers = sig.get_issuers();
441
442 let mut bad = None;
443
444 for issuer in issuers.iter() {
445 let cert = match issuer {
446 KeyHandle::Fingerprint(fpr) => {
447 certs.get_mut(fpr)
448 }
449 KeyHandle::KeyID(keyid) => {
450 by_keyid.get(keyid)
451 .and_then(|fpr| certs.get_mut(fpr))
452 }
453 };
454
455 let cert = if let Some(Some(cert)) = cert {
456 cert
457 } else {
458 continue;
459 };
460
461 match sig.clone().verify_primary_key_revocation(
462 cert.primary_key().key(),
463 cert.primary_key().key())
464 {
465 Ok(()) => {
466 *cert = cert.clone().insert_packets(sig.clone())?.0;
467 continue 'next_rev;
468 }
469 Err(err) => {
470 bad = Some((issuer, name.clone(), err));
471 }
472 }
473 }
474
475 if let Some((_sig, name, err)) = bad {
476 weprintln!("Could not add revocation certificate from {} \
477 to certificate: {}",
478 name, err);
479 die = true;
480 } else {
481 missing.push((issuers[0].clone(), name.clone()));
482 die = true;
483 }
484 }
485
486 match missing.as_slice() {
487 [] => (),
488 [(issuer, name)] => {
489 weprintln!("Couldn't merge revocation certificate \
490 from {}: missing {}.",
491 name, issuer);
492 }
493 _ => {
494 weprintln!("Couldn't some merge revocation certificates:");
495 for (issuer, name) in missing.into_iter() {
496 weprintln!(" - {}: missing {}",
497 name, issuer);
498 }
499 }
500 }
501
502 if die {
503 return Err(anyhow::anyhow!(
504 "Failed to merge some revocation certificates"));
505 }
506 }
507
508 let mut output = output.for_secrets().create_pgp_safe(
509 &sq,
510 binary,
511 if certs.values().any(|c| c.as_ref().map(Cert::is_tsk).unwrap_or(false))
512 {
513 armor::Kind::SecretKey
514 } else {
515 armor::Kind::PublicKey
516 },
517 )?;
518
519 for cert in certs.values().filter_map(|v| v.as_ref()) {
520 cert.as_tsk().serialize(&mut output)?;
521 }
522 output.finalize()?;
523
524 Ok(())
525 }
526
527 /// Sanitizes a string to a safe filename fragment.
528 fn to_filename_fragment<S: AsRef<str>>(s: S) -> Option<String> {
529 let mut r = String::with_capacity(s.as_ref().len());
530
531 s.as_ref().chars().filter_map(|c| match c {
532 '/' | ':' | '\\' => None,
533 c if c.is_ascii_whitespace() => None,
534 c if c.is_ascii() => Some(c),
535 _ => None,
536 }).for_each(|c| r.push(c));
537
538 if !r.is_empty() {
539 Some(r)
540 } else {
541 None
542 }
543 }