Debian Codegraph @

tests/integration/sq_key_subkey.rs

raw
1 use std::time::Duration;
2
3 use sequoia_openpgp as openpgp;
4 use openpgp::packet::Key;
5 use openpgp::parse::Parse;
6 use openpgp::types::KeyFlags;
7 use openpgp::types::ReasonForRevocation;
8 use openpgp::types::RevocationStatus;
9 use openpgp::types::SignatureType;
10 use openpgp::Cert;
11 use openpgp::Result;
12
13 use super::common::NO_USERIDS;
14 use super::common::STANDARD_POLICY;
15 use super::common::Sq;
16 use super::common::UserIDArg;
17 use super::common::compare_notations;
18 use super::common::time_as_string;
19
20 #[test]
21 fn sq_key_subkey() -> Result<()> {
22 let sq = Sq::new();
23
24 for (arg, expected_key_flags, expected_count) in [
25 ("--can-authenticate", KeyFlags::empty().set_authentication(), 2),
26 ("--can-encrypt=universal", KeyFlags::empty().set_transport_encryption(), 2),
27 ("--can-encrypt=universal", KeyFlags::empty().set_storage_encryption(), 2),
28 ("--can-sign", KeyFlags::empty().set_signing(), 2),
29 ] {
30 for keystore in [false, true] {
31 let (cert, cert_path, _rev_path)
32 = sq.key_generate(&[], &["alice <[email protected]>"]);
33
34 let modified_cert_path = sq.scratch_file("new_key.pgp");
35
36 if keystore {
37 sq.key_import(&cert_path);
38 }
39
40 // Add the subkey.
41 let mut cmd = sq.command();
42 cmd.args([
43 "key",
44 "subkey",
45 "add",
46 "--without-password",
47 arg,
48 ]);
49
50 if keystore {
51 cmd.args([
52 "--cert", &cert.fingerprint().to_string(),
53 ]);
54 } else {
55 cmd.args([
56 "--overwrite",
57 "--output",
58 &modified_cert_path.to_string_lossy(),
59 "--cert-file", &cert_path.to_string_lossy(),
60 ]);
61 }
62 cmd.assert().success();
63
64 let cert = if keystore {
65 sq.cert_export(cert.key_handle())
66 } else {
67 Cert::from_file(&modified_cert_path)?
68 };
69 let valid_cert = cert.with_policy(STANDARD_POLICY, None)?;
70
71 assert_eq!(
72 valid_cert.keys().key_flags(&expected_key_flags).count(),
73 expected_count
74 );
75 }
76 }
77
78 Ok(())
79 }
80
81 #[test]
82 fn sq_key_subkey_add_with_password() -> Result<()> {
83 let sq = Sq::new();
84
85 let password2 = "hunter2";
86 let path2 = sq.base().join("password2");
87 std::fs::write(&path2, password2)?;
88
89 let (cert, cert_path, _) = sq.key_generate(&[
90 "--cannot-sign",
91 "--cannot-authenticate",
92 "--cannot-encrypt",
93 "--new-password-file", &path2.display().to_string(),
94 ], NO_USERIDS);
95
96 assert!(cert.is_tsk());
97 assert_eq!(cert.keys().subkeys().count(), 0);
98 let key = cert.primary_key().key();
99 let secret = key.optional_secret().unwrap();
100 assert!(secret.is_encrypted());
101 assert!(secret.clone().decrypt(key, &password2.into()).is_ok());
102
103 // Add the subkey.
104 let password3 = "hunter3";
105 let path3 = sq.base().join("password3");
106 std::fs::write(&path3, password3)?;
107
108 let output = sq.base().join("output");
109 let mut cmd = sq.command();
110 cmd.args([
111 "key",
112 "subkey",
113 "add",
114 "--can-authenticate",
115 "--cert-file", &cert_path.display().to_string(),
116 "--password-file", &path2.display().to_string(),
117 "--new-password-file", &path3.display().to_string(),
118 "--output", &output.display().to_string(),
119 ]);
120 sq.run(cmd, Some(true));
121
122 let cert = Cert::from_file(output)?;
123
124 assert!(cert.is_tsk());
125 assert_eq!(cert.keys().subkeys().count(), 1);
126 let key = cert.primary_key().key();
127 let secret = key.optional_secret().unwrap();
128 assert!(secret.is_encrypted());
129 assert!(secret.clone().decrypt(key, &password2.into()).is_ok());
130
131 let key = cert.keys().subkeys().next().unwrap().key();
132 let secret = key.optional_secret().unwrap();
133 assert!(secret.is_encrypted());
134 assert!(secret.clone().decrypt(key, &password3.into()).is_ok());
135
136 Ok(())
137 }
138
139 #[test]
140 fn sq_key_subkey_revoke() -> Result<()> {
141 let sq = Sq::new();
142 let time = sq.now();
143
144 // revoke for various reasons, with or without notations added, or with
145 // a revocation whose reference time is one hour after the creation of the
146 // certificate
147 for (reason, reason_str, notations, revocation_time) in [
148 (
149 ReasonForRevocation::KeyCompromised,
150 "compromised",
151 &[][..],
152 None,
153 ),
154 (
155 ReasonForRevocation::KeyCompromised,
156 "compromised",
157 &[][..],
158 Some(time + Duration::new(60 * 60, 0)),
159 ),
160 (
161 ReasonForRevocation::KeyCompromised,
162 "compromised",
163 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
164 None,
165 ),
166 (ReasonForRevocation::KeyRetired, "retired", &[][..], None),
167 (
168 ReasonForRevocation::KeyRetired,
169 "retired",
170 &[][..],
171 Some(time + Duration::new(60 * 60, 0)),
172 ),
173 (
174 ReasonForRevocation::KeyRetired,
175 "retired",
176 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
177 None,
178 ),
179 (ReasonForRevocation::KeySuperseded, "superseded", &[][..], None),
180 (
181 ReasonForRevocation::KeySuperseded,
182 "superseded",
183 &[][..],
184 Some(time + Duration::new(60 * 60, 0)),
185 ),
186 (
187 ReasonForRevocation::KeySuperseded,
188 "superseded",
189 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
190 None,
191 ),
192 (ReasonForRevocation::Unspecified, "unspecified", &[][..], None),
193 (
194 ReasonForRevocation::Unspecified,
195 "unspecified",
196 &[][..],
197 Some(time + Duration::new(60 * 60, 0)),
198 ),
199 (
200 ReasonForRevocation::Unspecified,
201 "unspecified",
202 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
203 None,
204 ),
205 ] {
206 eprintln!("==========================");
207 eprintln!("reason: {}, message: {}, notations: {:?}, time: {:?}",
208 reason, reason_str, notations, revocation_time);
209
210 for keystore in [false, true].into_iter() {
211 eprintln!("--------------------------");
212 eprintln!("keystore: {}", keystore);
213
214 let (cert, cert_path, _rev_path)
215 = sq.key_generate(&[], &["alice <[email protected]>"]);
216
217 let valid_cert = cert.with_policy(STANDARD_POLICY, Some(time.into()))?;
218 let fingerprint = valid_cert.clone().fingerprint();
219 let subkey: Key<_, _> = valid_cert
220 .with_policy(STANDARD_POLICY, Some(time.into()))
221 .unwrap()
222 .keys()
223 .subkeys()
224 .nth(0)
225 .unwrap()
226 .key()
227 .clone();
228 let subkey_fingerprint = subkey.fingerprint();
229 let message = "message";
230
231 let revocation = sq.scratch_file(Some(&*format!(
232 "revocation_{}_{}_{}.rev",
233 reason_str,
234 if notations.is_empty() {
235 "no_notations"
236 } else {
237 "notations"
238 },
239 if revocation_time.is_some() {
240 "time"
241 } else {
242 "no_time"
243 }
244 )));
245
246 if keystore {
247 // When using the keystore, we need to import the key.
248 sq.key_import(&cert_path);
249 }
250
251 let mut cmd = sq.command();
252 cmd.args([
253 "key",
254 "subkey",
255 "revoke",
256 "--key", &subkey_fingerprint.to_string(),
257 "--reason", reason_str,
258 "--message", message,
259 ]);
260
261 if keystore {
262 cmd.args([
263 "--cert", &cert.fingerprint().to_string(),
264 ]);
265 } else {
266 cmd.arg("--output").arg(&revocation)
267 .arg("--cert-file").arg(&cert_path);
268 }
269
270 for (k, v) in notations {
271 cmd.args(["--signature-notation", k, v]);
272 }
273 if let Some(time) = revocation_time {
274 cmd.args([
275 "--time",
276 &time_as_string(time.into()),
277 ]);
278 }
279 let output = cmd.output()?;
280 if !output.status.success() {
281 panic!("sq exited with non-zero status code: {}",
282 String::from_utf8_lossy(&output.stderr));
283 }
284
285 // whether we found a revocation signature
286 let mut found_revoked = false;
287
288 // read revocation cert
289 let rev = if keystore {
290 sq.cert_export(cert.key_handle())
291 } else {
292 Cert::from_file(&revocation)?
293 };
294 assert!(! rev.is_tsk());
295
296 // and merge it into the certificate.
297 let cert = cert.clone().merge_public(rev)?;
298 let valid_cert =
299 cert.with_policy(STANDARD_POLICY, revocation_time.map(Into::into))?;
300 valid_cert
301 .with_policy(STANDARD_POLICY, revocation_time.map(Into::into))
302 .unwrap()
303 .keys()
304 .subkeys()
305 .for_each(|x| {
306 if x.key().fingerprint() == subkey_fingerprint {
307 let status = x.bundle().revocation_status(
308 STANDARD_POLICY,
309 revocation_time.map(Into::into),
310 );
311
312 // the subkey is revoked
313 assert!(matches!(status, RevocationStatus::Revoked(_)));
314
315 if let RevocationStatus::Revoked(sigs) = status {
316 // there is only one signature packet
317 assert_eq!(sigs.len(), 1);
318 let sig = sigs.into_iter().next().unwrap();
319
320 // it is a subkey revocation
321 assert_eq!(sig.typ(), SignatureType::SubkeyRevocation);
322
323 // the issuer is the certificate owner
324 assert_eq!(
325 sig.get_issuers().into_iter().next().as_ref(),
326 Some(&fingerprint.clone().into())
327 );
328
329 // our reason for revocation and message matches
330 assert_eq!(
331 sig.reason_for_revocation(),
332 Some((reason, message.as_bytes()))
333 );
334
335 // the notations of the revocation match the ones
336 // we passed in
337 assert!(compare_notations(sig, notations).is_ok());
338
339 found_revoked = true;
340 }
341 }
342 });
343
344 if !found_revoked {
345 panic!("the revoked subkey is not found in the revocation cert");
346 }
347 }
348 }
349
350 Ok(())
351 }
352
353 #[test]
354 fn sq_key_subkey_revoke_multiple() -> Result<()> {
355 let sq = Sq::new();
356
357 let (cert, cert_path, _rev_path)
358 = sq.key_generate(&[], &[UserIDArg::Email("[email protected]")]);
359 assert!(cert.keys().subkeys().count() > 0);
360 sq.key_import(cert_path);
361
362 let mut cmd = sq.command();
363 cmd.args([
364 "key", "subkey", "revoke",
365 "--cert", &cert.fingerprint().to_string(),
366 ]);
367
368 for subkey in cert.keys().subkeys() {
369 cmd.args(["--key", &subkey.key().fingerprint().to_string(),]);
370 }
371
372 cmd.args(["--reason", "retired", "--message", "rotation"]);
373 sq.run(cmd, Some(true));
374
375 let revoked = sq.cert_export(cert.key_handle());
376 assert_eq!(cert.keys().subkeys().count(), revoked.keys().subkeys().count());
377
378 let vrevoked = revoked.with_policy(STANDARD_POLICY, sq.now())?;
379 for subkey in vrevoked.keys().subkeys() {
380 use sequoia_openpgp::cert::amalgamation::ValidAmalgamation;
381 assert!(matches!(subkey.revocation_status(),
382 RevocationStatus::Revoked(_)));
383 }
384
385 Ok(())
386 }
387
388
389 #[test]
390 fn sq_key_subkey_revoke_thirdparty() -> Result<()> {
391 let sq = Sq::new();
392 let time = sq.now();
393
394 // revoke for various reasons, with or without notations added, or with
395 // a revocation whose reference time is one hour after the creation of the
396 // certificate
397 for (reason, reason_str, notations, revocation_time) in [
398 (
399 ReasonForRevocation::KeyCompromised,
400 "compromised",
401 &[][..],
402 None,
403 ),
404 (
405 ReasonForRevocation::KeyCompromised,
406 "compromised",
407 &[][..],
408 Some(time + Duration::new(60 * 60, 0)),
409 ),
410 (
411 ReasonForRevocation::KeyCompromised,
412 "compromised",
413 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
414 None,
415 ),
416 (ReasonForRevocation::KeyRetired, "retired", &[][..], None),
417 (
418 ReasonForRevocation::KeyRetired,
419 "retired",
420 &[][..],
421 Some(time + Duration::new(60 * 60, 0)),
422 ),
423 (
424 ReasonForRevocation::KeyRetired,
425 "retired",
426 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
427 None,
428 ),
429 (ReasonForRevocation::KeySuperseded, "superseded", &[][..], None),
430 (
431 ReasonForRevocation::KeySuperseded,
432 "superseded",
433 &[][..],
434 Some(time + Duration::new(60 * 60, 0)),
435 ),
436 (
437 ReasonForRevocation::KeySuperseded,
438 "superseded",
439 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
440 None,
441 ),
442 (ReasonForRevocation::Unspecified, "unspecified", &[][..], None),
443 (
444 ReasonForRevocation::Unspecified,
445 "unspecified",
446 &[][..],
447 Some(time + Duration::new(60 * 60, 0)),
448 ),
449 (
450 ReasonForRevocation::Unspecified,
451 "unspecified",
452 &[("foo", "bar"), ("[email protected]", "VALUE")][..],
453 None,
454 ),
455 ] {
456 for keystore in [false, true].into_iter() {
457 let (cert, cert_path, _rev_path)
458 = sq.key_generate(&[], &["alice <[email protected]>"]);
459
460 let valid_cert = cert.with_policy(STANDARD_POLICY, Some(time.into()))?;
461 let subkey: Key<_, _> = valid_cert
462 .with_policy(STANDARD_POLICY, Some(time.into()))
463 .unwrap()
464 .keys()
465 .subkeys()
466 .nth(0)
467 .unwrap()
468 .key()
469 .clone();
470 let subkey_fingerprint = subkey.fingerprint();
471
472 let (thirdparty_cert, thirdparty_path, _rev_path) =
473 sq.key_generate(&[], &["bob <[email protected]>"]);
474
475 let thirdparty_valid_cert = thirdparty_cert
476 .with_policy(STANDARD_POLICY, Some(time.into()))?;
477 let thirdparty_fingerprint = thirdparty_valid_cert.clone().fingerprint();
478
479 let message = "message";
480
481 let revocation = sq.scratch_file(Some(&*format!(
482 "revocation_{}_{}_{}.rev",
483 reason_str,
484 if ! notations.is_empty() {
485 "no_notations"
486 } else {
487 "notations"
488 },
489 if revocation_time.is_some() {
490 "time"
491 } else {
492 "no_time"
493 }
494 )));
495
496 if keystore {
497 // When using the keystore, we need to import the key.
498
499 for path in &[ &cert_path, &thirdparty_path ] {
500 sq.key_import(path);
501 }
502 }
503
504 let mut cmd = sq.command();
505 cmd.args([
506 "key",
507 "subkey",
508 "revoke",
509 "--key", &subkey_fingerprint.to_string(),
510 "--reason", reason_str,
511 "--message", message,
512 ]);
513
514 if keystore {
515 cmd.args([
516 "--cert", &cert.fingerprint().to_string(),
517 "--revoker", &thirdparty_cert.fingerprint().to_string(),
518 ]);
519 } else {
520 cmd.arg("--output").arg(&revocation)
521 .arg("--cert-file").arg(&cert_path)
522 .arg("--revoker-file").arg(&thirdparty_path);
523 }
524
525 for (k, v) in notations {
526 cmd.args(["--signature-notation", k, v]);
527 }
528 if let Some(time) = revocation_time {
529 cmd.args([
530 "--time",
531 &time_as_string(time.into()),
532 ]);
533 }
534 let output = cmd.output()?;
535 if !output.status.success() {
536 panic!("sq exited with non-zero status code: {}",
537 String::from_utf8_lossy(&output.stderr));
538 }
539
540 // read revocation cert
541 let rev = if keystore {
542 sq.cert_export(cert.key_handle())
543 } else {
544 Cert::from_file(&revocation)?
545 };
546 assert!(! rev.is_tsk());
547
548 // and merge it into the certificate.
549 let cert = cert.clone().merge_public(rev)?;
550 let valid_cert =
551 cert.with_policy(STANDARD_POLICY, revocation_time.map(Into::into))?;
552
553 // whether we found a revocation signature
554 let mut found_revoked = false;
555
556 assert_eq!(valid_cert.userids().count(), 1);
557 valid_cert
558 .with_policy(STANDARD_POLICY, revocation_time.map(Into::into))
559 .unwrap()
560 .keys()
561 .subkeys()
562 .for_each(|x| {
563 if x.key().fingerprint() == subkey_fingerprint {
564 if let RevocationStatus::CouldBe(sigs) = x
565 .bundle()
566 .revocation_status(
567 STANDARD_POLICY,
568 revocation_time.map(Into::into),
569 )
570 {
571 // there is only one signature packet
572 assert_eq!(sigs.len(), 1);
573 let sig = sigs.into_iter().next().unwrap();
574
575 // it is a subkey revocation
576 assert_eq!(sig.typ(), SignatureType::SubkeyRevocation);
577
578 // the issuer is a thirdparty revoker
579 assert_eq!(
580 sig.get_issuers().into_iter().next().as_ref(),
581 Some(&thirdparty_fingerprint.clone().into())
582 );
583
584 // the revocation can be verified
585 if sig
586 .clone()
587 .verify_subkey_revocation(
588 thirdparty_cert.primary_key().key(),
589 cert.primary_key().key(),
590 &subkey,
591 )
592 .is_err()
593 {
594 panic!("revocation is not valid")
595 }
596
597 // our reason for revocation and message matches
598 assert_eq!(
599 sig.reason_for_revocation(),
600 Some((reason, message.as_bytes()))
601 );
602
603 // the notations of the revocation match the ones
604 // we passed in
605 assert!(compare_notations(sig, notations).is_ok());
606
607 found_revoked = true;
608 } else {
609 panic!("there are no signatures in {:?}", x);
610 }
611 }
612 });
613
614 if !found_revoked {
615 panic!("the revoked subkey is not found in the revocation cert");
616 }
617 }
618 }
619
620 Ok(())
621 }