Debian Codegraph @

src/common/revoke.rs

raw
1 use std::sync::Arc;
2
3 use anyhow::Context;
4 use anyhow::Result;
5
6 use chrono::offset::Utc;
7 use chrono::DateTime;
8
9 use sequoia_openpgp as openpgp;
10 use openpgp::armor::Kind;
11 use openpgp::armor::Writer;
12 use openpgp::Cert;
13 use openpgp::crypto::Signer;
14 use openpgp::serialize::Serialize;
15
16 use sequoia_cert_store as cert_store;
17 use cert_store::StoreUpdate;
18 use cert_store::LazyCert;
19
20 use crate::cli::types::FileOrStdout;
21 use crate::Sq;
22 use crate::sq::GetKeysOptions;
23
24 /// A trait for unifying the approach of writing a revocation to an output
25 pub trait RevocationOutput {
26 /// Returns a minimal version of the certificate including the
27 /// revocation certificate.
28 fn cert(&self) -> Result<Cert>;
29
30 /// Returns a comment, which will be used as a header in the
31 /// ASCII-armor output.
32 ///
33 /// This should be of the form:
34 ///
35 /// ```
36 /// Includes a revocation certificate for User ID $userid
37 /// ```
38 fn comment(&self) -> String;
39
40 /// Returns the revoker's certificate.
41 fn revoker(&self) -> &Cert;
42
43 /// Write out the revocation certificate.
44 fn write(&self, sq: &Sq, output: Option<FileOrStdout>, binary: bool)
45 -> Result<()>
46 {
47 // Target width of comments.
48 const COMMENT_WIDTH: usize = 70;
49
50 if let Some(output) = output {
51 let mut output = output.create_safe(sq)?;
52
53 // First, build a minimal revocation certificate containing
54 // the primary key, the revoked component, and the revocation
55 // signature.
56 let cert = self.cert()?;
57
58 if binary {
59 cert.serialize(&mut output)
60 .context("serializing revocation certificate")?;
61 } else {
62 // Add some more helpful ASCII-armor comments.
63 let mut more: Vec<String> = vec![];
64
65 // First, the thing that is being revoked.
66 textwrap::wrap(&self.comment(), COMMENT_WIDTH)
67 .into_iter().for_each(|line| more.push(line.into()));
68
69 let revoker = self.revoker();
70
71 let first_party_issuer = revoker.fingerprint() == cert.fingerprint();
72 if ! first_party_issuer {
73 // Then if it was issued by a third-party.
74 more.push("".into());
75 more.push(format!("This revocation is issued \
76 by the cert {} ({}).",
77 revoker.fingerprint(),
78 sq.best_userid(revoker, false).display()));
79 }
80
81 let headers: Vec<(&str, &str)> = more.iter()
82 .map(|value| ("Comment", value.as_str()))
83 .collect();
84
85 let mut writer =
86 Writer::with_headers(&mut output, Kind::PublicKey, headers)?;
87 cert.serialize(&mut writer)
88 .context("serializing revocation certificate")?;
89 writer.finalize()?;
90 }
91 } else {
92 let cert_store = sq.cert_store_or_else()?;
93 let cert = self.cert()?;
94 cert_store.update(Arc::new(LazyCert::from(cert)))
95 .with_context(|| {
96 "Error importing the revocation certificate into cert store"
97 })?;
98 }
99
100 Ok(())
101 }
102 }
103
104 /// Get secret Cert and Signer from an optional secret Cert or a Cert
105 ///
106 /// Returns a secret Cert and the corresponding Signer, derived from `secret`,
107 /// if `secret` is `Some`, else attempts to derive it from `cert`.
108 ///
109 /// ## Errors
110 ///
111 /// - Returns an `Error` if `secret` is `Some`, but no suitable certification key
112 /// can be derived from it.
113 /// - Returns an `Error` if `secret` is `None` and no suitable certification key
114 /// can be derived from `cert`.
115 pub fn get_secret_signer<'a>(
116 sq: &'a Sq,
117 cert: &'a Cert,
118 secret: Option<&'a Cert>,
119 ) -> Result<(Cert, Box<dyn Signer + Send + Sync>)> {
120 let flags = Some(&[
121 GetKeysOptions::AllowRevoked,
122 GetKeysOptions::AllowNotAlive,
123 GetKeysOptions::NullPolicy,
124 ][..]);
125
126 if let Some(secret) = secret {
127 match sq.get_primary_key(secret, flags) {
128 Ok(key) => Ok((secret.clone(), key)),
129 Err(err) => {
130 if ! sq.time_is_now {
131 return Err(err.context(format!("\
132 No certification key found: the key specified with --revocation-file \
133 does not contain a certification key with secret key material. \
134 Perhaps this is because no certification keys are valid at the time \
135 you specified ({})",
136 DateTime::<Utc>::from(sq.time))));
137 } else {
138 return Err(err.context(format!("\
139 No certification key found: the key specified with --revocation-file \
140 does not contain a certification key with secret key material")));
141 }
142 }
143 }
144 } else {
145 match sq.get_primary_key(cert, flags) {
146 Ok(key) => Ok((cert.clone(), key)),
147 Err(err) => {
148 if ! sq.time_is_now {
149 return Err(err.context(format!("\
150 No certification key found: --revocation-file not provided and the
151 certificate to revoke does not contain a certification key with secret
152 key material. Perhaps this is because no certification keys are valid at
153 the time you specified ({})",
154 DateTime::<Utc>::from(sq.time))));
155 } else {
156 return Err(err.context(format!("\
157 No certification key found: --revocation-file not provided and the
158 certificate to revoke does not contain a certification key with secret
159 key material")));
160 }
161 }
162 }
163 }
164 }