Debian Codegraph @

src/commands/key/generate.rs

raw
1 use chrono::DateTime;
2 use chrono::Utc;
3
4 use anyhow::Context;
5
6 use sequoia_openpgp as openpgp;
7 use openpgp::armor::Kind;
8 use openpgp::armor::Writer;
9 use openpgp::cert::CertBuilder;
10 use openpgp::serialize::Serialize;
11 use openpgp::types::KeyFlags;
12 use openpgp::Packet;
13 use openpgp::packet::UserID;
14 use openpgp::Result;
15
16 use crate::common::password;
17 use crate::common::userid::{lint_userids, lint_names, lint_emails};
18 use crate::Sq;
19 use crate::cli::{
20 self,
21 types::{
22 Expiration,
23 FileOrStdout,
24 TrustAmount,
25 },
26 };
27 use crate::commands::inspect::inspect;
28 use crate::common::key::certify_generated;
29 use crate::output::import::ImportStatus;
30
31 pub fn generate(
32 mut sq: Sq,
33 mut command: cli::key::generate::Command,
34 ) -> Result<()> {
35 if command.output.as_ref().map(|s| s.is_stdout()).unwrap_or(false)
36 && command.rev_cert.as_ref().map(|s| s.is_stdout()).unwrap_or(false)
37 {
38 return Err(anyhow::anyhow!(
39 "--output and --rev-cert must not both be stdout"));
40 }
41
42 if command.output.is_none() {
43 // We're going to save the output to the certificate store and
44 // the key store. Make sure they are enabled.
45 sq.cert_store_or_else()?;
46 sq.key_store_or_else()?;
47 }
48
49 // Common key flags. If this is a shared key, mark it as such.
50 assert!(command.own_key ^ command.shared_key);
51 let key_flags_template = if command.own_key {
52 KeyFlags::empty()
53 } else {
54 KeyFlags::empty().set_group_key()
55 };
56
57 let mut builder = CertBuilder::new()
58 .set_profile(command.profile.into())?;
59
60 // Names, email addresses, and user IDs.
61 lint_names(&command.names)?;
62 for n in &command.names {
63 command.userid.push(UserID::from(n.as_str()));
64 }
65
66 lint_emails(&command.emails)?;
67 for n in &command.emails {
68 command.userid.push(UserID::from_address(None, None, n)?);
69 }
70
71 if command.userid.is_empty() {
72 weprintln!("No user ID given, using direct key signature");
73 } else {
74 // Make sure the user IDs are in canonical form. If not, and
75 // `--allow-non-canonical-userids` is not set, error out.
76 if ! command.allow_non_canonical_userids {
77 lint_userids(&command.userid)?;
78 }
79
80 for uid in &command.userid {
81 builder = builder.add_userid(uid.clone());
82 }
83 }
84
85 // Creation time.
86 builder = builder.set_creation_time(sq.time);
87
88 // Expiration.
89 builder = builder.set_validity_period(
90 command
91 .expiration
92 .as_duration(DateTime::<Utc>::from(sq.time))?
93 );
94
95 // Cipher Suite
96 builder = builder.set_cipher_suite(
97 sq.config.cipher_suite(&command.cipher_suite,
98 command.cipher_suite_source));
99
100 // Profile. XXX: Currently, this is not actionable.
101 let _profile = sq.config.key_generate_profile(
102 &command.profile, command.profile_source);
103
104 // Primary key capabilities.
105 builder = builder.set_primary_key_flags(
106 key_flags_template.clone().set_certification());
107
108 // Signing Capability
109 match (command.can_sign, command.cannot_sign) {
110 (false, false) | (true, false) => {
111 builder = builder.add_subkey(
112 key_flags_template.clone().set_signing(),
113 None, None);
114 }
115 (false, true) => { /* no signing subkey */ }
116 (true, true) => {
117 return Err(anyhow::anyhow!(
118 "Conflicting arguments --can-sign and --cannot-sign"
119 ));
120 }
121 }
122
123 // Authentication Capability
124 match (command.can_authenticate, command.cannot_authenticate) {
125 (false, false) | (true, false) => {
126 builder = builder.add_subkey(
127 key_flags_template.clone().set_authentication(),
128 None, None);
129 }
130 (false, true) => { /* no authentication subkey */ }
131 (true, true) => {
132 return Err(anyhow::anyhow!(
133 "Conflicting arguments --can-authenticate and \
134 --cannot-authenticate"
135 ));
136 }
137 }
138
139 // Encryption Capability
140 use cli::types::EncryptPurpose::*;
141 match (command.can_encrypt, command.cannot_encrypt) {
142 (Some(Universal), false) | (None, false) => {
143 builder = builder.add_subkey(
144 key_flags_template.clone()
145 .set_transport_encryption()
146 .set_storage_encryption(),
147 None, None);
148 }
149 (Some(Storage), false) => {
150 builder = builder.add_subkey(
151 key_flags_template.clone().set_storage_encryption(),
152 None, None);
153 }
154 (Some(Transport), false) => {
155 builder = builder.add_subkey(
156 key_flags_template.clone().set_transport_encryption(),
157 None, None);
158 }
159 (None, true) => { /* no encryption subkey */ }
160 (Some(_), true) => {
161 return Err(anyhow::anyhow!(
162 "Conflicting arguments --can-encrypt and \
163 --cannot-encrypt"
164 ));
165 }
166 }
167
168 if let Some(password_file) = command.new_password_file {
169 let password = std::fs::read(&password_file)
170 .with_context(|| {
171 format!("Reading {}", password_file.display())
172 })?;
173 builder = builder.set_password(Some(password.into()));
174 } else if ! command.without_password {
175 builder = builder.set_password(
176 password::prompt_for_new_or_none(&sq, "key")?);
177 }
178
179 let on_keystore = command.output.is_none();
180
181 // Generate the key
182 let gen = || {
183 builder.generate()
184 };
185
186 let (mut cert, rev);
187
188 let rev_path = if let Some(rev_cert) = command.rev_cert {
189 (cert, rev) = gen()?;
190
191 rev_cert
192 } else if on_keystore {
193 if let Some(home) = &sq.home {
194 let dir = home.data_dir(sequoia_directories::Component::Other(
195 "revocation-certificates".into()));
196 std::fs::create_dir_all(&dir)
197 .with_context(|| {
198 format!("While creating {}", dir.display())
199 })?;
200
201 (cert, rev) = gen()?;
202 FileOrStdout::new(
203 Some(dir.join(format!("{}-revocation.pgp",
204 cert.fingerprint()))))
205 } else {
206 return Err(anyhow::anyhow!(
207 "Missing arguments: --rev-cert is mandatory if --home=none is \
208 given."
209 ));
210 }
211 } else {
212 return Err(anyhow::anyhow!(
213 "Missing arguments: --rev-cert is mandatory if --output is \
214 given."
215 ));
216 };
217
218 let headers = cert.armor_headers();
219
220 // write out rev cert
221 {
222 let mut headers: Vec<_> = headers
223 .iter()
224 .map(|value| ("Comment", value.as_str()))
225 .collect();
226 headers.insert(0, ("Comment", "Revocation certificate for"));
227
228 let w = rev_path.create_safe(&sq)?;
229 let mut w = Writer::with_headers(w, Kind::PublicKey, headers)?;
230 Packet::from(cert.primary_key().key().clone()).serialize(&mut w)?;
231 Packet::Signature(rev).serialize(&mut w)?;
232 w.finalize()?;
233 }
234
235 // write out key
236 {
237 let headers: Vec<_> = headers
238 .iter()
239 .map(|value| ("Comment", value.as_str()))
240 .collect();
241
242 match command.output {
243 Some(ref output_file) => {
244 // Write the key to a file or to stdout.
245 let w = output_file.clone().for_secrets()
246 .create_safe(&sq)?;
247 let mut w = Writer::with_headers(w, Kind::SecretKey, headers)?;
248 cert.as_tsk().serialize(&mut w)?;
249 w.finalize()?;
250 }
251 None => {
252 // write the key to the key store
253
254 // Certify the key with a per-host shadow CA if there
255 // are any user IDs to certify.
256 let have_userids = cert.userids().next().is_some();
257 if have_userids {
258 cert = certify_generated(&mut sq, &cert)?;
259 }
260
261 match sq.import_key(cert.clone(), &mut Default::default())
262 .map(|(key_status, _cert_status)| key_status)
263 {
264 Ok(ImportStatus::New) => { /* success */ }
265 Ok(ImportStatus::Unchanged) => {
266 panic!(
267 "The new key is identical to an existing one; this \
268 should never happen");
269 }
270 Ok(ImportStatus::Updated) => {
271 panic!(
272 "The new key collides with an existing one; this \
273 should never happen")
274 }
275 Err(err) => {
276 return Err(anyhow::anyhow!(
277 "Failed saving to the store: {}", err))
278 }
279 }
280
281 // Now certify the user IDs, and if this is our own
282 // key, mark it as trusted introducer.
283 let trust_root = sq.local_trust_root()?;
284 let trust_root = trust_root.to_cert()?;
285
286 if command.own_key && have_userids {
287 // Mark all user IDs as authenticated, and mark
288 // the key as a trusted introducer.
289 crate::common::pki::certify::certify(
290 &mut std::io::stderr(),
291 &sq,
292 false, // Recreate.
293 &trust_root,
294 &cert,
295 &command.userid.into_iter().map(Into::into)
296 .collect::<Vec<_>>(),
297 true, // User-supplied user IDs.
298 &[(TrustAmount::Full, Expiration::Never)],
299 // Make it a unconstrained trusted introducer.
300 u8::MAX, // Trust depth.
301 &[][..], // Domain.
302 &[][..], // Regex.
303 true, // Local.
304 false, // Non-revocable.
305 &[][..], // Notations.
306 None, // Output.
307 false, // Binary.
308 )?;
309 } else if command.shared_key && have_userids {
310 // Mark all user IDs as authenticated.
311 crate::common::pki::certify::certify(
312 &mut std::io::stderr(),
313 &sq,
314 false, // Recreate.
315 &trust_root,
316 &cert,
317 &command.userid.into_iter().map(Into::into)
318 .collect::<Vec<_>>(),
319 true, // User-supplied user IDs.
320 &[(TrustAmount::Full, Expiration::Never)],
321 // No trusted introducer.
322 0, // Trust depth.
323 &[][..], // Domain.
324 &[][..], // Regex.
325 true, // Local.
326 false, // Non-revocable.
327 &[][..], // Notations.
328 None, // Output.
329 false, // Binary.
330 )?;
331 }
332 }
333 }
334 }
335
336 {
337 let mut bytes = Vec::new();
338 cert.as_tsk().serialize(&mut bytes)
339 .expect("serializing to a vector is infallible");
340
341 if let Err(err) = inspect(
342 &mut sq,
343 buffered_reader::Memory::with_cookie(&bytes, Default::default()),
344 command.output
345 .as_ref()
346 .and_then(|output| {
347 output.path().map(|p| p.display().to_string())
348 })
349 .as_deref(),
350 &mut (Box::new(std::io::stderr()) as Box<dyn std::io::Write + Send + Sync>),
351 false, false)
352 {
353 weprintln!("Failed to display key: {}", err);
354 weprintln!("This is probably a bug in sq, please report it to \
355 https://gitlab.com/sequoia-pgp/sequoia-sq/-/issues/new .");
356 }
357 }
358
359 // If we are writing to key store, provide some guidance.
360 if on_keystore && command.own_key {
361 sq.hint(format_args!("Because you supplied the `--own-key` flag, \
362 the user IDs on this key have been marked as \
363 authenticated, and this key has been marked \
364 as a fully trusted introducer. \
365 If that was a mistake, you can undo that \
366 with:"))
367 .sq().arg("pki").arg("link").arg("retract")
368 .arg_value("--cert", cert.fingerprint())
369 .arg("--all")
370 .done();
371 }
372
373 if on_keystore && command.shared_key {
374 sq.hint(format_args!("The user IDs on the key have been marked as \
375 authenticated. \
376 If that was a mistake, you can undo that \
377 with:"))
378 .sq().arg("pki").arg("link").arg("retract")
379 .arg_value("--cert", cert.fingerprint())
380 .arg("--all")
381 .done();
382 }
383
384 if on_keystore {
385 sq.hint(format_args!("You can export your certificate as follows:"))
386 .sq().arg("cert").arg("export")
387 .arg_value("--cert", cert.fingerprint())
388 .done();
389
390 sq.hint(format_args!("Once you are happy you can upload it to public \
391 directories using:"))
392 .sq().arg("network").arg("keyserver").arg("publish")
393 .arg_value("--cert", cert.fingerprint())
394 .done();
395 } else {
396 let mut shown = false;
397 if let Some(ref output) = command.output {
398 if let Some(output_path) = output.path() {
399 sq.hint(format_args!("You can extract the certificate from the \
400 generated key by running:"))
401 .sq().arg("key").arg("delete")
402 .arg_value("--cert-file", output_path.display())
403 .arg_value("--output", output_path.with_extension("cert").display())
404 .done();
405 shown = true;
406 }
407 }
408
409 if ! shown {
410 sq.hint(format_args!("You can extract the certificate from the \
411 generated key using:"))
412 .sq().arg("key").arg("delete").done();
413 }
414 }
415
416 Ok(())
417 }