Debian Codegraph @

src/commands/key/rotate.rs

raw
1 use std::cell::RefCell;
2 use std::collections::BTreeMap;
3 use std::collections::btree_map::Entry;
4 use std::sync::Arc;
5
6 use chrono::DateTime;
7 use chrono::Utc;
8
9 use anyhow::Context;
10
11 use sequoia_openpgp as openpgp;
12 use openpgp::Cert;
13 use openpgp::Fingerprint;
14 use openpgp::Packet;
15 use openpgp::Result;
16 use openpgp::armor::Kind;
17 use openpgp::armor::Writer;
18 use openpgp::cert::CertBuilder;
19 use openpgp::cert::CertRevocationBuilder;
20 use openpgp::cert::amalgamation::ValidAmalgamation;
21 use openpgp::crypto::Password;
22 use openpgp::packet::signature::SignatureBuilder;
23 use openpgp::serialize::Serialize;
24 use openpgp::types::KeyFlags;
25 use openpgp::types::ReasonForRevocation;
26 use openpgp::types::RevocationStatus;
27 use openpgp::types::SignatureType;
28
29 use sequoia_cert_store as cert_store;
30 use cert_store::StoreUpdate;
31
32 use crate::Sq;
33 use crate::cli::types::Expiration;
34 use crate::cli::types::FileOrStdout;
35 use crate::cli::types::TrustAmount;
36 use crate::cli;
37 use crate::commands::inspect::inspect;
38 use crate::common::key::certify_generated;
39 use crate::common::password;
40 use crate::common::pki::list::summarize_certification;
41 use crate::common::pki::replay::replay;
42 use crate::common::ui;
43 use crate::output::import::ImportStatus;
44 use crate::sq::TrustThreshold;
45
46 pub fn dispatch(
47 mut sq: Sq,
48 command: cli::key::rotate::Command,
49 ) -> Result<()> {
50 let o = &mut std::io::stderr();
51
52 if command.output.as_ref().map(|s| s.is_stdout()).unwrap_or(false)
53 && command.rev_cert.as_ref().map(|s| s.is_stdout()).unwrap_or(false)
54 {
55 return Err(anyhow::anyhow!(
56 "--output and --rev-cert must not both be stdout"));
57 }
58
59 if command.output.is_none() {
60 // We're going to save the output to the certificate store and
61 // the key store. Make sure they are enabled.
62 sq.cert_store_or_else()?;
63 sq.key_store_or_else()?;
64 }
65
66 let mut old_cert = sq.resolve_cert(&command.cert, TrustThreshold::Full)?.0;
67 let old_vc = old_cert.with_policy(sq.policy, sq.time)?;
68
69 // Common key flags. If this is a shared key, mark it as such.
70 assert!(! (command.own_key && command.shared_key));
71 let key_flags_template = if command.own_key {
72 KeyFlags::empty()
73 } else if command.shared_key {
74 KeyFlags::empty().set_group_key()
75 } else {
76 if old_vc.keys().any(|ka| {
77 ka.key_flags().map(|kf| kf.is_group_key()).unwrap_or(false)
78 }) {
79 KeyFlags::empty().set_group_key()
80 } else {
81 KeyFlags::empty()
82 }
83 };
84
85 let mut builder = CertBuilder::new();
86
87 let userids = old_vc.userids()
88 .filter_map(|ua| {
89 if let RevocationStatus::Revoked(_) = ua.revocation_status() {
90 // Skip revoked user IDs.
91 None
92 } else {
93 Some(ua.userid().clone())
94 }
95 })
96 .collect::<Vec<_>>();
97
98 if userids.is_empty() {
99 wwriteln!(stream = o,
100 "{} has no non-revoked self-signed user IDs, \
101 using direct key signature",
102 old_vc.fingerprint());
103 } else {
104 for userid in &userids {
105 builder = builder.add_userid(userid.clone());
106 }
107 }
108
109 // Creation time.
110 builder = builder.set_creation_time(sq.time);
111
112 // Expiration.
113 builder = builder.set_validity_period(
114 command
115 .expiration
116 .as_duration(DateTime::<Utc>::from(sq.time))?
117 );
118
119 // Cipher Suite
120 builder = builder.set_cipher_suite(
121 sq.config.cipher_suite(&command.cipher_suite,
122 command.cipher_suite_source));
123
124 // Profile. XXX: Currently, this is not actionable.
125 let _profile = sq.config.key_generate_profile(
126 &command.profile, command.profile_source);
127
128 // Primary key capabilities.
129 builder = builder.set_primary_key_flags(
130 key_flags_template.clone().set_certification());
131
132 // Get everything the old certificate could do.
133 let mut old_cert_key_flags = KeyFlags::certification();
134 for ka in old_vc.keys() {
135 // We consider the key flags even if the subkey is revoked or
136 // expired.
137 if let Some(kf) = ka.key_flags() {
138 old_cert_key_flags = &old_cert_key_flags | &kf
139 }
140 }
141
142 // Signing Capability
143 match (command.can_sign, command.cannot_sign) {
144 (true, false) => {
145 builder = builder.add_subkey(
146 key_flags_template.clone().set_signing(),
147 None, None);
148 }
149 (false, true) => { /* no signing subkey */ }
150 (true, true) => {
151 return Err(anyhow::anyhow!(
152 "Conflicting arguments --can-sign and --cannot-sign"
153 ));
154 }
155 (false, false) => {
156 if old_cert_key_flags.for_signing() {
157 builder = builder.add_subkey(
158 key_flags_template.clone().set_signing(),
159 None, None);
160 } else {
161 // No signing subkey.
162 }
163 }
164 }
165
166 // Authentication Capability
167 match (command.can_authenticate, command.cannot_authenticate) {
168 (true, false) => {
169 builder = builder.add_subkey(
170 key_flags_template.clone().set_authentication(),
171 None, None);
172 }
173 (false, true) => { /* no authentication subkey */ }
174 (true, true) => {
175 return Err(anyhow::anyhow!(
176 "Conflicting arguments --can-authenticate and \
177 --cannot-authenticate"
178 ));
179 }
180 (false, false) => {
181 if old_cert_key_flags.for_authentication() {
182 builder = builder.add_subkey(
183 key_flags_template.clone().set_authentication(),
184 None, None);
185 } else {
186 // No authentication subkey.
187 }
188 }
189 }
190
191 // Encryption Capability
192 use cli::types::EncryptPurpose::*;
193 match (command.can_encrypt, command.cannot_encrypt) {
194 (Some(Universal), false) => {
195 builder = builder.add_subkey(
196 key_flags_template.clone()
197 .set_transport_encryption()
198 .set_storage_encryption(),
199 None, None);
200 }
201 (Some(Storage), false) => {
202 builder = builder.add_subkey(
203 key_flags_template.clone().set_storage_encryption(),
204 None, None);
205 }
206 (Some(Transport), false) => {
207 builder = builder.add_subkey(
208 key_flags_template.clone().set_transport_encryption(),
209 None, None);
210 }
211 (None, true) => { /* no encryption subkey */ }
212 (Some(_), true) => {
213 return Err(anyhow::anyhow!(
214 "Conflicting arguments --can-encrypt and \
215 --cannot-encrypt"
216 ));
217 }
218 (None, false) => {
219 let mut enc = KeyFlags::empty();
220 if old_cert_key_flags.for_storage_encryption() {
221 enc = enc.set_storage_encryption()
222 }
223 if old_cert_key_flags.for_transport_encryption() {
224 enc = enc.set_transport_encryption()
225 }
226 if enc != KeyFlags::empty() {
227 builder = builder.add_subkey(
228 &key_flags_template | &enc,
229 None, None);
230 } else {
231 // No encryption subkey.
232 }
233 }
234 }
235
236 if let Some(password_file) = command.new_password_file {
237 let password: Password = std::fs::read(&password_file)
238 .with_context(|| {
239 format!("Reading {}", password_file.display())
240 })?.into();
241 sq.cache_password(password.clone());
242 builder = builder.set_password(Some(password));
243 } else if ! command.without_password {
244 let password
245 = password::prompt_for_new_or_none(&sq, "the new key")?;
246 if let Some(password) = password.as_ref() {
247 sq.cache_password(password.clone());
248 }
249 builder = builder.set_password(password);
250 }
251
252 let on_keystore = command.output.is_none();
253
254 // Generate the key
255 let gen = || {
256 builder.generate()
257 };
258
259 let (mut cert, rev);
260
261 let rev_path = if let Some(rev_cert) = command.rev_cert {
262 (cert, rev) = gen()?;
263
264 rev_cert
265 } else if on_keystore {
266 if let Some(home) = &sq.home {
267 let dir = home.data_dir(sequoia_directories::Component::Other(
268 "revocation-certificates".into()));
269 std::fs::create_dir_all(&dir)
270 .with_context(|| {
271 format!("While creating {}", dir.display())
272 })?;
273
274 (cert, rev) = gen()?;
275 FileOrStdout::new(
276 Some(dir.join(format!("{}-revocation.pgp",
277 cert.fingerprint()))))
278 } else {
279 return Err(anyhow::anyhow!(
280 "Missing arguments: --rev-cert is mandatory if --home=none is \
281 given."
282 ));
283 }
284 } else {
285 return Err(anyhow::anyhow!(
286 "Missing arguments: --rev-cert is mandatory if --output is \
287 given."
288 ));
289 };
290
291 // Certificates that need to be updated.
292 let mut updates: BTreeMap<Fingerprint, Cert> = BTreeMap::new();
293 let mut update = |cert: Cert| -> Result<()> {
294 match updates.entry(cert.fingerprint()) {
295 Entry::Occupied(oe) => {
296 let c = oe.into_mut();
297 *c = c.clone().merge_public(cert)?;
298 }
299 Entry::Vacant(vc) => {
300 vc.insert(cert);
301 }
302 }
303
304 Ok(())
305 };
306
307
308 // Cross sign.
309 wwriteln!(stream = o);
310 wwriteln!(stream = o,
311 "Cross signing the old and new certificates.");
312
313 let mut old_cert_signer = sq.get_certification_key(&old_cert, None)?;
314 let mut cert_signer = sq.get_certification_key(&cert, None)?;
315
316 let mut builder
317 = SignatureBuilder::new(SignatureType::GenericCertification)
318 .set_signature_creation_time(sq.time)?;
319 builder = builder.set_trust_signature(255, 120)?;
320
321 let mut old_cert_updates = Vec::new();
322 let mut new_cert_updates = Vec::new();
323
324 for userid in userids.iter() {
325 // Old authorizes new.
326 let sig = builder.clone().sign_userid_binding(
327 &mut old_cert_signer,
328 cert.primary_key().key(),
329 &userid)
330 .with_context(|| {
331 format!("Creating certification for {}, {}",
332 cert.fingerprint(),
333 ui::Safe(String::from_utf8_lossy(userid.value())))
334 })?;
335
336 new_cert_updates.extend([
337 Packet::from(userid.clone()),
338 sig.into(),
339 ]);
340
341 // New authorizes old.
342 let sig = builder.clone().sign_userid_binding(
343 &mut cert_signer,
344 old_cert.primary_key().key(),
345 &userid)
346 .with_context(|| {
347 format!("Creating certification for {}, {}",
348 old_cert.fingerprint(),
349 ui::Safe(String::from_utf8_lossy(userid.value())))
350 })?;
351
352 old_cert_updates.extend([
353 Packet::from(userid.clone()),
354 sig.into(),
355 ]);
356 }
357
358 if ! old_cert_updates.is_empty() {
359 old_cert = old_cert.insert_packets(old_cert_updates)?.0;
360 update(old_cert.clone())?;
361
362 cert = cert.insert_packets(new_cert_updates)?.0;
363 update(cert.clone())?;
364 }
365
366 // Replay the trust root -> cert onto the new certificate.
367 let trust_root = sq.local_trust_root()?;
368 let trust_root = trust_root.to_cert()?;
369 let mut trust_root_signer = sq.get_certification_key(trust_root, None)?;
370
371 if ! command.own_key && ! command.shared_key {
372 wwriteln!(stream = o);
373 wwriteln!(stream = o,
374 "Replaying the old certificate's links:");
375
376 let mut packets = Vec::new();
377
378 for ua in old_cert.userids() {
379 for sig in ua.active_certifications_by_key(
380 sq.policy,
381 sq.time,
382 trust_root.primary_key().key())
383 {
384 wwriteln!(stream = o, indent=" ",
385 "Copying link for {}:",
386 ui::Safe(String::from_utf8_lossy(
387 ua.userid().value())));
388 summarize_certification(o, " ", &sig, true)?;
389
390 let builder: SignatureBuilder = sig.clone().into();
391 let builder = builder.set_signature_creation_time(sq.time)?;
392
393 let sig = builder.sign_userid_binding(
394 &mut trust_root_signer,
395 cert.primary_key().key(),
396 &ua.userid())
397 .with_context(|| {
398 format!("Creating link for {}, {}",
399 cert.fingerprint(),
400 ui::Safe(String::from_utf8_lossy(
401 ua.userid().value())))
402 })?;
403
404 packets.extend([
405 Packet::from(ua.userid().clone()),
406 sig.into(),
407 ]);
408 }
409 }
410
411 if packets.is_empty() {
412 wwriteln!(stream = o, indent = " ",
413 "The certificate was never linked.");
414 } else {
415 cert = cert.insert_packets(packets)?.0;
416 update(cert.clone())?;
417 }
418 }
419
420 // Replay the certifications that old cert made.
421 wwriteln!(stream = o);
422 wwriteln!(stream = o,
423 "Replaying certifications made by the old certificate:");
424 for cert in replay(&sq, o, " ",
425 RefCell::new(old_cert.clone()),
426 &cert, Some(&mut cert_signer), None)?
427 .into_iter()
428 {
429 update(cert)?;
430 }
431
432
433 if let Expiration::Timestamp(retire_at) = command.retire_in.value() {
434 // Retire the old certificate.
435 wwriteln!(stream = o);
436
437 let retire_at = retire_at.to_system_time(sq.time)?;
438 let retire_at_str = chrono::DateTime::<chrono::Utc>::from(retire_at)
439 .format("%Y‑%m‑%d %H:%M:%S")
440 .to_string();
441
442 wwriteln!(stream = o,
443 "Retiring the old certificate as of {}.",
444 retire_at_str);
445
446 let mut rev = CertRevocationBuilder::new()
447 .set_reason_for_revocation(
448 ReasonForRevocation::KeyRetired,
449 format!("This certificate has been retired, and is \
450 replaced by {}.",
451 cert.fingerprint())
452 .as_bytes())?;
453 rev = rev.set_signature_creation_time(retire_at)?;
454 let rev = rev.build(&mut old_cert_signer, &old_cert, None)?;
455 update(old_cert.insert_packets(rev)?.0)?;
456 }
457
458 let headers = cert.armor_headers();
459
460 // write out rev cert
461 {
462 let mut headers: Vec<_> = headers
463 .iter()
464 .map(|value| ("Comment", value.as_str()))
465 .collect();
466 headers.insert(0, ("Comment", "Revocation certificate for"));
467
468 let w = rev_path.create_safe(&sq)?;
469 let mut w = Writer::with_headers(w, Kind::PublicKey, headers)?;
470 Packet::from(cert.primary_key().key().clone()).serialize(&mut w)?;
471 Packet::Signature(rev).serialize(&mut w)?;
472 w.finalize()?;
473 }
474
475 // write out key and the updates.
476 {
477 let headers: Vec<_> = headers
478 .iter()
479 .map(|value| ("Comment", value.as_str()))
480 .collect();
481
482 match command.output {
483 Some(ref output_file) => {
484 // Write the key to a file or to stdout.
485 let w = output_file.clone().for_secrets()
486 .create_safe(&sq)?;
487 let mut w = Writer::with_headers(w, Kind::SecretKey, headers)?;
488 cert.as_tsk().serialize(&mut w)?;
489 for (_fpr, cert) in updates.iter() {
490 cert.serialize(&mut w)?;
491 }
492 w.finalize()?;
493 }
494 None => {
495 // write the key to the key store
496
497 // Certify the key with a per-host shadow CA if there
498 // are any user IDs to certify.
499 let have_userids = cert.userids().next().is_some();
500 if have_userids {
501 cert = certify_generated(&mut sq, &cert)?;
502 }
503
504 match sq.import_key(cert.clone(), &mut Default::default())
505 .map(|(key_status, _cert_status)| key_status)
506 {
507 Ok(ImportStatus::New) => { /* success */ }
508 Ok(ImportStatus::Unchanged) => {
509 panic!(
510 "The new key is identical to an existing one; this \
511 should never happen");
512 }
513 Ok(ImportStatus::Updated) => {
514 panic!(
515 "The new key collides with an existing one; this \
516 should never happen")
517 }
518 Err(err) => {
519 return Err(anyhow::anyhow!(
520 "Failed saving to the store: {}", err))
521 }
522 }
523
524 // If the user provided `--own-key` or `--shared-key`,
525 // certify the user IDs using the local trust root.
526 // (If they didn't then already replayed the local
527 // trust root's certifications of the certificate.)
528 if command.own_key && have_userids {
529 // Mark all user IDs as authenticated, and mark
530 // the key as a trusted introducer.
531 crate::common::pki::certify::certify(
532 o,
533 &sq,
534 false, // Recreate.
535 &trust_root,
536 &cert,
537 &userids.into_iter().map(Into::into)
538 .collect::<Vec<_>>(),
539 true, // User-supplied user IDs.
540 &[(TrustAmount::Full, Expiration::Never)],
541 // Make it an unconstrained trusted introducer.
542 u8::MAX, // Trust depth.
543 &[][..], // Domain.
544 &[][..], // Regex.
545 true, // Local.
546 false, // Non-revocable.
547 &[][..], // Notations.
548 None, // Output.
549 false, // Binary.
550 )?;
551 } else if command.shared_key && have_userids {
552 // Mark all user IDs as authenticated.
553 crate::common::pki::certify::certify(
554 o,
555 &sq,
556 false, // Recreate.
557 &trust_root,
558 &cert,
559 &userids.into_iter().map(Into::into)
560 .collect::<Vec<_>>(),
561 true, // User-supplied user IDs.
562 &[(TrustAmount::Full, Expiration::Never)],
563 // No trusted introducer.
564 0, // Trust depth.
565 &[][..], // Domain.
566 &[][..], // Regex.
567 true, // Local.
568 false, // Non-revocable.
569 &[][..], // Notations.
570 None, // Output.
571 false, // Binary.
572 )?;
573 }
574
575 // And save any updates.
576 let cert_store = sq.cert_store_or_else()?;
577
578 for cert in updates.values() {
579 if let Err(err) = cert_store.update(
580 Arc::new(cert.clone().into()))
581 {
582 wwriteln!(stream = o,
583 "Error importing updated certificate: {}",
584 err);
585 return Err(err);
586 }
587 }
588 }
589 }
590 }
591
592 // Display the new certificate.
593 {
594 let mut bytes = Vec::new();
595 cert.as_tsk().serialize(&mut bytes)
596 .expect("serializing to a vector is infallible");
597
598 wwriteln!(stream = o);
599 if let Err(err) = inspect(
600 &mut sq,
601 buffered_reader::Memory::with_cookie(&bytes, Default::default()),
602 command.output
603 .as_ref()
604 .and_then(|output| {
605 output.path().map(|p| p.display().to_string())
606 })
607 .as_deref(),
608 &mut (Box::new(std::io::stderr()) as Box<dyn std::io::Write + Send + Sync>),
609 true, false)
610 {
611 wwriteln!(stream = o, "Failed to display key: {}", err);
612 wwriteln!(stream = o,
613 "This is probably a bug in sq, please report it to \
614 https://gitlab.com/sequoia-pgp/sequoia-sq/-/issues/new .");
615 }
616 }
617
618 // If we are writing to key store, provide some guidance.
619 if on_keystore && command.own_key {
620 sq.hint(format_args!("Because you supplied the `--own-key` flag, \
621 the user IDs on this key have been marked as \
622 authenticated, and this key has been marked \
623 as a fully trusted introducer. \
624 If that was a mistake, you can undo that \
625 with:"))
626 .sq().arg("pki").arg("link").arg("retract")
627 .arg_value("--cert", cert.fingerprint())
628 .arg("--all")
629 .done();
630 }
631
632 if on_keystore && command.shared_key {
633 sq.hint(format_args!("The user IDs on the key have been marked as \
634 authenticated. \
635 If that was a mistake, you can undo that \
636 with:"))
637 .sq().arg("pki").arg("link").arg("retract")
638 .arg_value("--cert", cert.fingerprint())
639 .arg("--all")
640 .done();
641 }
642
643 if on_keystore {
644 sq.hint(format_args!("You can export your certificate as follows:"))
645 .sq().arg("cert").arg("export")
646 .arg_value("--cert", cert.fingerprint())
647 .done();
648
649 sq.hint(format_args!("Once you are happy you can upload it to public \
650 directories using:"))
651 .sq().arg("network").arg("keyserver").arg("publish")
652 .arg_value("--cert", cert.fingerprint())
653 .done();
654
655 if ! updates.is_empty() {
656 let mut hint = sq.hint(format_args!(
657 "To make updates to other certificates effective, \
658 they also have to be published, for example using:"))
659 .sq().arg("network").arg("keyserver").arg("publish");
660
661 for cert in updates.values() {
662 hint = hint.arg_value("--cert", cert.fingerprint())
663 }
664
665 hint.done();
666 }
667 } else {
668 let mut shown = false;
669 if let Some(ref output) = command.output {
670 if let Some(output_path) = output.path() {
671 sq.hint(format_args!("You can extract the certificate from the \
672 generated key by running:"))
673 .sq().arg_value("--keyring", output_path.display())
674 .arg("cert").arg("export")
675 .arg_value("--cert", &cert.fingerprint().to_string())
676 .arg_value("--output", output_path.with_extension("cert").display())
677 .done();
678 shown = true;
679 }
680 }
681
682 if ! shown {
683 sq.hint(format_args!("You can extract the certificate from the \
684 generated key using:"))
685 .sq().arg("key").arg("delete").done();
686 }
687 }
688
689 Ok(())
690 }