Debian Codegraph @

tests/integration/sq_sign.rs

raw
1 use std::fs::{self, File};
2 use std::io;
3
4 use tempfile::TempDir;
5
6 use sequoia_openpgp as openpgp;
7 use openpgp::Fingerprint;
8 use openpgp::KeyHandle;
9 use openpgp::Result;
10 use openpgp::{Packet, PacketPile, Cert};
11 use openpgp::cert::CertBuilder;
12 use openpgp::crypto::KeyPair;
13 use openpgp::packet::key::SecretKeyMaterial;
14 use openpgp::packet::signature::subpacket::NotationData;
15 use openpgp::packet::signature::subpacket::NotationDataFlags;
16 use openpgp::types::{CompressionAlgorithm, SignatureType};
17 use openpgp::parse::Parse;
18 use openpgp::policy::StandardPolicy;
19 use openpgp::serialize::stream::{Message, Signer, Compressor, LiteralWriter};
20 use openpgp::serialize::Serialize;
21
22 use super::common::*;
23
24 const P: &StandardPolicy = &StandardPolicy::new();
25
26 #[test]
27 fn sq_sign() {
28 let sq = Sq::new();
29 let tmp_dir = TempDir::new().unwrap();
30 let sig = tmp_dir.path().join("sig0");
31
32 // Sign message.
33 sq.sign(artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"), None,
34 &artifact("messages/a-cypherpunks-manifesto.txt"), sig.as_path());
35
36 // Check that the content is sane.
37 let packets: Vec<Packet> =
38 PacketPile::from_file(&sig).unwrap().into_children().collect();
39 assert_eq!(packets.len(), 3);
40 if let Packet::OnePassSig(ref ops) = packets[0] {
41 assert!(ops.last());
42 assert_eq!(ops.typ(), SignatureType::Binary);
43 } else {
44 panic!("expected one pass signature");
45 }
46 if let Packet::Literal(_) = packets[1] {
47 // Do nothing.
48 } else {
49 panic!("expected literal");
50 }
51 if let Packet::Signature(ref sig) = packets[2] {
52 assert_eq!(sig.typ(), SignatureType::Binary);
53 } else {
54 panic!("expected signature");
55 }
56
57 let content = fs::read(&sig).unwrap();
58 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
59
60 // Verify signed message.
61 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
62 Verify::Message, &sig, None);
63 }
64
65 #[test]
66 fn sq_sign_with_notations() {
67 let sq = Sq::new();
68 let tmp_dir = TempDir::new().unwrap();
69 let sig = tmp_dir.path().join("sig0");
70
71 // Sign message.
72 sq.sign_args(&["--signature-notation", "foo", "bar",
73 "--signature-notation", "!foo", "xyzzy",
74 "--signature-notation", "[email protected]", "1234567890"],
75 artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"), None,
76 &artifact("messages/a-cypherpunks-manifesto.txt"), sig.as_path());
77
78 // Check that the content is sane.
79 let packets: Vec<Packet> =
80 PacketPile::from_file(&sig).unwrap().into_children().collect();
81 assert_eq!(packets.len(), 3);
82 if let Packet::OnePassSig(ref ops) = packets[0] {
83 assert!(ops.last());
84 assert_eq!(ops.typ(), SignatureType::Binary);
85 } else {
86 panic!("expected one pass signature");
87 }
88 if let Packet::Literal(_) = packets[1] {
89 // Do nothing.
90 } else {
91 panic!("expected literal");
92 }
93 if let Packet::Signature(ref sig) = packets[2] {
94 assert_eq!(sig.typ(), SignatureType::Binary);
95
96 eprintln!("{:?}", sig);
97
98 let hr = NotationDataFlags::empty().set_human_readable();
99 let notations = &mut [
100 (NotationData::new("foo", "bar", hr.clone()), false),
101 (NotationData::new("foo", "xyzzy", hr.clone()), false),
102 (NotationData::new("[email protected]", "1234567890", hr), false)
103 ];
104
105 for n in sig.notation_data() {
106 if n.name() == "[email protected]" {
107 continue;
108 }
109
110 for (m, found) in notations.iter_mut() {
111 if n == m {
112 assert!(!*found);
113 *found = true;
114 }
115 }
116 }
117 for (n, found) in notations.iter() {
118 assert!(found, "Missing: {:?}", n);
119 }
120 } else {
121 panic!("expected signature");
122 }
123
124 let content = fs::read(&sig).unwrap();
125 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
126
127 // Verify signed message.
128 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp"),
129 "--known-notation", "foo"],
130 Verify::Message, &sig, None);
131 }
132
133 #[test]
134 fn sq_sign_append() {
135 let sq = Sq::new();
136 let tmp_dir = TempDir::new().unwrap();
137 let sig0 = tmp_dir.path().join("sig0");
138
139 // Sign message.
140 sq.sign(artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"), None,
141 &artifact("messages/a-cypherpunks-manifesto.txt"), sig0.as_path());
142
143 // Check that the content is sane.
144 let packets: Vec<Packet> =
145 PacketPile::from_file(&sig0).unwrap().into_children().collect();
146 assert_eq!(packets.len(), 3);
147 if let Packet::OnePassSig(ref ops) = packets[0] {
148 assert!(ops.last());
149 assert_eq!(ops.typ(), SignatureType::Binary);
150 } else {
151 panic!("expected one pass signature");
152 }
153 if let Packet::Literal(_) = packets[1] {
154 // Do nothing.
155 } else {
156 panic!("expected literal");
157 }
158 if let Packet::Signature(ref sig) = packets[2] {
159 assert_eq!(sig.typ(), SignatureType::Binary);
160 } else {
161 panic!("expected signature");
162 }
163
164 let content = fs::read(&sig0).unwrap();
165 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
166
167 // Verify signed message.
168 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
169 Verify::Message, &sig0, None);
170
171 // Now add a second signature with --append.
172 let sig1 = tmp_dir.path().join("sig1");
173 sq.sign_args(
174 &["--append"],
175 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
176 None, sig0.as_path(), sig1.as_path());
177
178 // Check that the content is sane.
179 let packets: Vec<Packet> =
180 PacketPile::from_file(&sig1).unwrap().into_children().collect();
181 assert_eq!(packets.len(), 5);
182 if let Packet::OnePassSig(ref ops) = packets[0] {
183 assert!(! ops.last());
184 assert_eq!(ops.typ(), SignatureType::Binary);
185 } else {
186 panic!("expected one pass signature");
187 }
188 if let Packet::OnePassSig(ref ops) = packets[1] {
189 assert!(ops.last());
190 assert_eq!(ops.typ(), SignatureType::Binary);
191 } else {
192 panic!("expected one pass signature");
193 }
194 if let Packet::Literal(_) = packets[2] {
195 // Do nothing.
196 } else {
197 panic!("expected literal");
198 }
199 if let Packet::Signature(ref sig) = packets[3] {
200 assert_eq!(sig.typ(), SignatureType::Binary);
201 assert_eq!(sig.level(), 0);
202 } else {
203 panic!("expected signature");
204 }
205 if let Packet::Signature(ref sig) = packets[4] {
206 assert_eq!(sig.typ(), SignatureType::Binary);
207 assert_eq!(sig.level(), 0);
208 } else {
209 panic!("expected signature");
210 }
211
212 let content = fs::read(&sig1).unwrap();
213 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
214
215 // Verify both signatures of the signed message.
216 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
217 Verify::Message, &sig1, None);
218 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
219 Verify::Message, &sig1, None);
220 }
221
222 #[test]
223 #[allow(unreachable_code)]
224 fn sq_sign_append_on_compress_then_sign() {
225 let sq = Sq::new();
226 let tmp_dir = TempDir::new().unwrap();
227 let sig0 = tmp_dir.path().join("sig0");
228
229 // This is quite an odd scheme, so we need to create such a
230 // message by foot.
231 let tsk = Cert::from_file(&artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"))
232 .unwrap();
233 let key = tsk.keys().with_policy(P, None).for_signing().next().unwrap().key();
234 let sec = match key.optional_secret() {
235 Some(SecretKeyMaterial::Unencrypted(ref u)) => u.clone(),
236 _ => unreachable!(),
237 };
238 let keypair = KeyPair::new(key.clone(), sec).unwrap();
239 let message = Message::new(File::create(&sig0).unwrap());
240 let signer = Signer::new(message, keypair).unwrap()
241 .creation_time(sq.now())
242 .build().unwrap();
243 let compressor = Compressor::new(signer)
244 .algo(CompressionAlgorithm::Uncompressed)
245 .build().unwrap();
246 let mut literal = LiteralWriter::new(compressor).build()
247 .unwrap();
248 io::copy(
249 &mut File::open(&artifact("messages/a-cypherpunks-manifesto.txt")).unwrap(),
250 &mut literal)
251 .unwrap();
252 literal.finalize()
253 .unwrap();
254
255 // Check that the content is sane.
256 let packets: Vec<Packet> =
257 PacketPile::from_file(&sig0).unwrap().into_children().collect();
258 assert_eq!(packets.len(), 3);
259 if let Packet::OnePassSig(ref ops) = packets[0] {
260 assert!(ops.last());
261 assert_eq!(ops.typ(), SignatureType::Binary);
262 } else {
263 panic!("expected one pass signature");
264 }
265 if let Packet::CompressedData(_) = packets[1] {
266 // Do nothing.
267 } else {
268 panic!("expected compressed data");
269 }
270 if let Packet::Signature(ref sig) = packets[2] {
271 assert_eq!(sig.typ(), SignatureType::Binary);
272 } else {
273 panic!("expected signature");
274 }
275
276 // Verify signed message.
277 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
278 Verify::Message, &sig0, None);
279
280 // Now add a second signature with --append.
281 let sig1 = tmp_dir.path().join("sig1");
282 sq.command()
283 .arg("sign")
284 .arg("--message")
285 .arg("--append")
286 .arg("--signer-file").arg(artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"))
287 .arg("--output")
288 .arg(&*sig1.to_string_lossy())
289 .arg(&*sig0.to_string_lossy())
290 .assert()
291 .failure(); // XXX: Currently, this is not implemented.
292
293 // XXX: Currently, this is not implemented in sq.
294 return;
295
296 // Check that the content is sane.
297 let packets: Vec<Packet> =
298 PacketPile::from_file(&sig1).unwrap().into_children().collect();
299 assert_eq!(packets.len(), 5);
300 if let Packet::OnePassSig(ref ops) = packets[0] {
301 assert!(! ops.last());
302 assert_eq!(ops.typ(), SignatureType::Binary);
303 } else {
304 panic!("expected one pass signature");
305 }
306 if let Packet::OnePassSig(ref ops) = packets[1] {
307 assert!(ops.last());
308 assert_eq!(ops.typ(), SignatureType::Binary);
309 } else {
310 panic!("expected one pass signature");
311 }
312 if let Packet::CompressedData(_) = packets[2] {
313 // Do nothing.
314 } else {
315 panic!("expected compressed data");
316 }
317 if let Packet::Signature(ref sig) = packets[3] {
318 assert_eq!(sig.typ(), SignatureType::Binary);
319 assert_eq!(sig.level(), 0);
320 } else {
321 panic!("expected signature");
322 }
323 if let Packet::Signature(ref sig) = packets[4] {
324 assert_eq!(sig.typ(), SignatureType::Binary);
325 assert_eq!(sig.level(), 0);
326 } else {
327 panic!("expected signature");
328 }
329
330 let content = fs::read(&sig1).unwrap();
331 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
332
333 // Verify both signatures of the signed message.
334 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
335 Verify::Message, &sig0, None);
336 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
337 Verify::Message, &sig0, None);
338 }
339
340 #[test]
341 fn sq_sign_detached() {
342 let sq = Sq::new();
343 let tmp_dir = TempDir::new().unwrap();
344 let sig = tmp_dir.path().join("sig0");
345
346 // Sign detached.
347 sq.sign_detached(&[],
348 artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"),
349 &artifact("messages/a-cypherpunks-manifesto.txt"),
350 sig.as_path());
351
352 // Check that the content is sane.
353 let packets: Vec<Packet> =
354 PacketPile::from_file(&sig).unwrap().into_children().collect();
355 assert_eq!(packets.len(), 1);
356 if let Packet::Signature(ref sig) = packets[0] {
357 assert_eq!(sig.typ(), SignatureType::Binary);
358 } else {
359 panic!("expected signature");
360 }
361
362 let content = fs::read(&sig).unwrap();
363 assert!(&content[..].starts_with(b"-----BEGIN PGP SIGNATURE-----\n\n"));
364
365 // Verify detached.
366 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
367 Verify::SignatureFile(sig),
368 &artifact("messages/a-cypherpunks-manifesto.txt"), None);
369 }
370
371 #[test]
372 fn sq_sign_detached_append() {
373 let sq = Sq::new();
374 let tmp_dir = TempDir::new().unwrap();
375 let sig = tmp_dir.path().join("sig0");
376
377 // Sign detached.
378 sq.sign_detached(&[],
379 artifact("keys/emmelie-dorothea-dina-samantha-awina-ed25519-private.pgp"),
380 &artifact("messages/a-cypherpunks-manifesto.txt"),
381 sig.as_path());
382
383 // Check that the content is sane.
384 let packets: Vec<Packet> =
385 PacketPile::from_file(&sig).unwrap().into_children().collect();
386 assert_eq!(packets.len(), 1);
387 if let Packet::Signature(ref sig) = packets[0] {
388 assert_eq!(sig.typ(), SignatureType::Binary);
389 } else {
390 panic!("expected signature");
391 }
392
393 let content = fs::read(&sig).unwrap();
394 assert!(&content[..].starts_with(b"-----BEGIN PGP SIGNATURE-----\n\n"));
395
396 // Verify detached.
397 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
398 Verify::SignatureFile(sig.clone()),
399 &artifact("messages/a-cypherpunks-manifesto.txt"), None);
400
401 // Check that we don't blindly overwrite signatures.
402 sq.try_sign_detached(&[],
403 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
404 &artifact("messages/a-cypherpunks-manifesto.txt"),
405 sig.as_path())
406 .unwrap_err();
407
408 // Now add a second signature with --append.
409 eprintln!("now");
410 sq.sign_detached(&["--append"],
411 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
412 &artifact("messages/a-cypherpunks-manifesto.txt"),
413 sig.as_path());
414 eprintln!("done");
415
416 // Check that the content is sane.
417 let packets: Vec<Packet> =
418 PacketPile::from_file(&sig).unwrap().into_children().collect();
419 assert_eq!(packets.len(), 2);
420 if let Packet::Signature(ref sig) = packets[0] {
421 assert_eq!(sig.typ(), SignatureType::Binary);
422 } else {
423 panic!("expected signature");
424 }
425 if let Packet::Signature(ref sig) = packets[1] {
426 assert_eq!(sig.typ(), SignatureType::Binary);
427 } else {
428 panic!("expected signature");
429 }
430
431 let content = fs::read(&sig).unwrap();
432 assert!(&content[..].starts_with(b"-----BEGIN PGP SIGNATURE-----\n\n"));
433
434 // Verify both detached signatures.
435 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
436 Verify::SignatureFile(sig.clone()),
437 &artifact("messages/a-cypherpunks-manifesto.txt"), None);
438 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
439 Verify::SignatureFile(sig.clone()),
440 &artifact("messages/a-cypherpunks-manifesto.txt"), None);
441
442 // Finally, check that we don't truncate the file if something
443 // goes wrong.
444 sq.command()
445 .arg("sign")
446 .arg("--signature-file")
447 .arg("--append")
448 .arg("--signer-file") // Not a private key => signing will fail.
449 .arg(&artifact("keys/erika-corinna-daniela-simone-antonia-nistp521.pgp"))
450 .args(["--output", &sig.to_string_lossy()])
451 .arg(&artifact("messages/a-cypherpunks-manifesto.txt"))
452 .assert()
453 .failure();
454
455 // Check that the content is still sane.
456 let packets: Vec<Packet> =
457 PacketPile::from_file(&sig).unwrap().into_children().collect();
458 assert_eq!(packets.len(), 2);
459 if let Packet::Signature(ref sig) = packets[0] {
460 assert_eq!(sig.typ(), SignatureType::Binary);
461 } else {
462 panic!("expected signature");
463 }
464 if let Packet::Signature(ref sig) = packets[1] {
465 assert_eq!(sig.typ(), SignatureType::Binary);
466 } else {
467 panic!("expected signature");
468 }
469 }
470
471 // Notarizations ahead.
472
473 #[ignore]
474 #[test]
475 fn sq_sign_append_a_notarization() {
476 let sq = Sq::new();
477 let tmp_dir = TempDir::new().unwrap();
478 let sig0 = tmp_dir.path().join("sig0");
479
480 // Now add a third signature with --append to a notarized message.
481 sq.sign_detached(
482 &["--append"],
483 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
484 &artifact("messages/signed-1-notarized-by-ed25519.pgp"),
485 sig0.as_path());
486
487 // Check that the content is sane.
488 let packets: Vec<Packet> =
489 PacketPile::from_file(&sig0).unwrap().into_children().collect();
490 assert_eq!(packets.len(), 7);
491 if let Packet::OnePassSig(ref ops) = packets[0] {
492 assert!(! ops.last());
493 assert_eq!(ops.typ(), SignatureType::Binary);
494 } else {
495 panic!("expected one pass signature");
496 }
497 if let Packet::OnePassSig(ref ops) = packets[1] {
498 assert!(ops.last());
499 assert_eq!(ops.typ(), SignatureType::Binary);
500 } else {
501 panic!("expected one pass signature");
502 }
503 if let Packet::OnePassSig(ref ops) = packets[2] {
504 assert!(ops.last());
505 assert_eq!(ops.typ(), SignatureType::Binary);
506 } else {
507 panic!("expected one pass signature");
508 }
509 if let Packet::Literal(_) = packets[3] {
510 // Do nothing.
511 } else {
512 panic!("expected literal");
513 }
514 if let Packet::Signature(ref sig) = packets[4] {
515 assert_eq!(sig.typ(), SignatureType::Binary);
516 assert_eq!(sig.level(), 0);
517 } else {
518 panic!("expected signature");
519 }
520 if let Packet::Signature(ref sig) = packets[5] {
521 assert_eq!(sig.typ(), SignatureType::Binary);
522 assert_eq!(sig.level(), 1);
523 } else {
524 panic!("expected signature");
525 }
526 if let Packet::Signature(ref sig) = packets[6] {
527 assert_eq!(sig.typ(), SignatureType::Binary);
528 assert_eq!(sig.level(), 1);
529 } else {
530 panic!("expected signature");
531 }
532
533 let content = fs::read(&sig0).unwrap();
534 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
535
536 // Verify both notarizations and the signature.
537 sq.verify(&["--signer-file", &artifact_s("keys/neal.pgp")],
538 Verify::Message, &sig0, None);
539 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
540 Verify::Message, &sig0, None);
541 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
542 Verify::Message, &sig0, None);
543 }
544
545 #[ignore]
546 #[test]
547 fn sq_sign_notarize() {
548 let sq = Sq::new();
549 let tmp_dir = TempDir::new().unwrap();
550 let sig0 = tmp_dir.path().join("sig0");
551
552 // Now add a third signature with --append to a notarized message.
553 sq.sign_args(
554 &["--notarize"],
555 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
556 None,
557 &artifact("messages/signed-1.gpg"),
558 sig0.as_path());
559
560 // Check that the content is sane.
561 let packets: Vec<Packet> =
562 PacketPile::from_file(&sig0).unwrap().into_children().collect();
563 assert_eq!(packets.len(), 5);
564 if let Packet::OnePassSig(ref ops) = packets[0] {
565 assert!(ops.last());
566 assert_eq!(ops.typ(), SignatureType::Binary);
567 } else {
568 panic!("expected one pass signature");
569 }
570 if let Packet::OnePassSig(ref ops) = packets[1] {
571 assert!(ops.last());
572 assert_eq!(ops.typ(), SignatureType::Binary);
573 } else {
574 panic!("expected one pass signature");
575 }
576 if let Packet::Literal(_) = packets[2] {
577 // Do nothing.
578 } else {
579 panic!("expected literal");
580 }
581 if let Packet::Signature(ref sig) = packets[3] {
582 assert_eq!(sig.typ(), SignatureType::Binary);
583 assert_eq!(sig.level(), 0);
584 } else {
585 panic!("expected signature");
586 }
587 if let Packet::Signature(ref sig) = packets[4] {
588 assert_eq!(sig.typ(), SignatureType::Binary);
589 assert_eq!(sig.level(), 1);
590 } else {
591 panic!("expected signature");
592 }
593
594 let content = fs::read(&sig0).unwrap();
595 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
596
597 // Verify both notarizations and the signature.
598 sq.verify(&["--signer-file", &artifact_s("keys/neal.pgp")],
599 Verify::Message, &sig0, None);
600 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
601 Verify::Message, &sig0, None);
602 }
603
604 #[ignore]
605 #[test]
606 fn sq_sign_notarize_a_notarization() {
607 let sq = Sq::new();
608 let tmp_dir = TempDir::new().unwrap();
609 let sig0 = tmp_dir.path().join("sig0");
610
611 // Now add a third signature with --append to a notarized message.
612 sq.sign_args(
613 &["--notarize"],
614 artifact("keys/erika-corinna-daniela-simone-antonia-nistp256-private.pgp"),
615 None,
616 &artifact("messages/signed-1-notarized-by-ed25519.pgp"),
617 sig0.as_path());
618
619 // Check that the content is sane.
620 let packets: Vec<Packet> =
621 PacketPile::from_file(&sig0).unwrap().into_children().collect();
622 assert_eq!(packets.len(), 7);
623 if let Packet::OnePassSig(ref ops) = packets[0] {
624 assert!(ops.last());
625 assert_eq!(ops.typ(), SignatureType::Binary);
626 } else {
627 panic!("expected one pass signature");
628 }
629 if let Packet::OnePassSig(ref ops) = packets[1] {
630 assert!(ops.last());
631 assert_eq!(ops.typ(), SignatureType::Binary);
632 } else {
633 panic!("expected one pass signature");
634 }
635 if let Packet::OnePassSig(ref ops) = packets[2] {
636 assert!(ops.last());
637 assert_eq!(ops.typ(), SignatureType::Binary);
638 } else {
639 panic!("expected one pass signature");
640 }
641 if let Packet::Literal(_) = packets[3] {
642 // Do nothing.
643 } else {
644 panic!("expected literal");
645 }
646 if let Packet::Signature(ref sig) = packets[4] {
647 assert_eq!(sig.typ(), SignatureType::Binary);
648 assert_eq!(sig.level(), 0);
649 } else {
650 panic!("expected signature");
651 }
652 if let Packet::Signature(ref sig) = packets[5] {
653 assert_eq!(sig.typ(), SignatureType::Binary);
654 assert_eq!(sig.level(), 1);
655 } else {
656 panic!("expected signature");
657 }
658 if let Packet::Signature(ref sig) = packets[6] {
659 assert_eq!(sig.typ(), SignatureType::Binary);
660 assert_eq!(sig.level(), 2);
661 } else {
662 panic!("expected signature");
663 }
664
665 let content = fs::read(&sig0).unwrap();
666 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
667
668 // Verify both notarizations and the signature.
669 sq.verify(&["--signer-file", &artifact_s("keys/neal.pgp")],
670 Verify::Message, &sig0, None);
671 sq.verify(&["--signer-file", &artifact_s("keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp")],
672 Verify::Message, &sig0, None);
673 sq.verify(&["--signer-file", &artifact_s("keys/erika-corinna-daniela-simone-antonia-nistp256.pgp")],
674 Verify::Message, &sig0, None);
675 }
676
677 #[test]
678 fn sq_multiple_signers() -> Result<()> {
679 let sq = Sq::new();
680 let tmp = TempDir::new()?;
681
682 let gen = |userid: &str| {
683 CertBuilder::new()
684 .add_signing_subkey()
685 .add_userid(userid)
686 .generate().map(|(key, _rev)| key)
687 };
688
689 let alice = gen("<[email protected]>")?;
690 let alice_pgp = tmp.path().join("alice.pgp");
691 let mut file = File::create(&alice_pgp)?;
692 alice.as_tsk().serialize(&mut file)?;
693
694 let bob = gen("<[email protected]>")?;
695 let bob_pgp = tmp.path().join("bob.pgp");
696 let mut file = File::create(&bob_pgp)?;
697 bob.as_tsk().serialize(&mut file)?;
698
699 // Sign message.
700 let assertion = sq.command()
701 .args([
702 "sign",
703 "--signer-file", alice_pgp.to_str().unwrap(),
704 "--signer-file", &bob_pgp.to_str().unwrap(),
705 "--signature-file=-",
706 ])
707 .write_stdin(&b"foo"[..])
708 .assert().try_success()?;
709
710 let stdout = String::from_utf8_lossy(&assertion.get_output().stdout);
711
712 let pp = PacketPile::from_bytes(&*stdout)?;
713
714 assert_eq!(pp.children().count(), 2,
715 "expected two packets");
716
717 let mut sigs: Vec<Fingerprint> = pp.children().map(|p| {
718 if let &Packet::Signature(ref sig) = p {
719 if let Some(KeyHandle::Fingerprint(fpr))
720 = sig.get_issuers().into_iter().next()
721 {
722 fpr
723 } else {
724 panic!("No issuer fingerprint subpacket!");
725 }
726 } else {
727 panic!("Expected a signature, got: {:?}", pp);
728 }
729 }).collect();
730 sigs.sort();
731
732 let alice_sig_fpr = alice.with_policy(P, None)?
733 .keys().for_signing().next().unwrap().key().fingerprint();
734 let bob_sig_fpr = bob.with_policy(P, None)?
735 .keys().for_signing().next().unwrap().key().fingerprint();
736
737 let mut expected = vec![
738 alice_sig_fpr,
739 bob_sig_fpr,
740 ];
741 expected.sort();
742
743 assert_eq!(sigs, expected);
744
745 Ok(())
746 }
747
748 #[test]
749 fn sq_sign_using_cert_store() -> Result<()> {
750 let sq = Sq::new();
751 let dir = TempDir::new()?;
752
753 let certd = dir.path().join("cert.d").display().to_string();
754 std::fs::create_dir(&certd).expect("mkdir works");
755
756 let msg_pgp = dir.path().join("msg.pgp");
757
758 // Generate a key.
759 let (alice, alice_pgp, _rev) =
760 sq.key_generate(&["--expiration", "never"], &["<[email protected]>"]);
761
762 // Import it.
763 let mut cmd = sq.command();
764 cmd.args(["--cert-store", &certd,
765 "cert", "import"]);
766 cmd.arg(&alice_pgp);
767 sq.run(cmd, true);
768
769 // Sign a message.
770 sq.sign(&alice_pgp, None,
771 &artifact("messages/a-cypherpunks-manifesto.txt"),
772 msg_pgp.as_path());
773
774 // Check that the content is sane.
775 let packets: Vec<Packet> =
776 PacketPile::from_file(&msg_pgp).unwrap().into_children().collect();
777 assert_eq!(packets.len(), 3);
778 if let Packet::OnePassSig(ref ops) = packets[0] {
779 assert!(ops.last());
780 assert_eq!(ops.typ(), SignatureType::Binary);
781 } else {
782 panic!("expected one pass signature");
783 }
784 if let Packet::Literal(_) = packets[1] {
785 // Do nothing.
786 } else {
787 panic!("expected literal");
788 }
789 if let Packet::Signature(ref sig) = packets[2] {
790 assert_eq!(sig.typ(), SignatureType::Binary);
791
792 let alice_signer = alice.with_policy(P, None)?
793 .keys().for_signing().next().expect("have one");
794 assert_eq!(sig.get_issuers().into_iter().next(),
795 Some(KeyHandle::from(alice_signer.key().fingerprint())));
796 } else {
797 panic!("expected signature");
798 }
799
800 let content = fs::read(&msg_pgp).unwrap();
801 assert!(&content[..].starts_with(b"-----BEGIN PGP MESSAGE-----\n\n"));
802
803 // Verify the signed message. First, we specify the certificate
804 // explicitly.
805 sq.verify(&["--signer-file", &alice_pgp.display().to_string()],
806 Verify::Message, &msg_pgp, None);
807
808 // Verify the signed message. Now, we don't specify the
809 // certificate or use a certificate store.
810 let result = sq.verify_maybe(&[], Verify::Message, &msg_pgp, None);
811 assert!(result.is_err());
812 let err = result.unwrap_err().to_string();
813 assert!(err.contains("missing certificate."), "{}", err);
814 assert!(err.contains("Error: Verification failed") , "{}", err);
815
816 // Now we use the certificate store.
817 let result = sq.verify_maybe(
818 &["--cert-store", &certd], Verify::Message, &msg_pgp, None);
819 assert!(result.is_err());
820 let err = result.unwrap_err().to_string();
821
822 // The default trust model says that certificates from the
823 // certificate store are not authenticated.
824 assert!(err.contains("the certificate can't be authenticated."),
825 "{}", err);
826 assert!(err.contains("Error: Verification failed"),
827 "{}", err);
828
829 // Now we use the certificate store *and* specify the certificate.
830 let mut cmd = sq.command();
831 cmd.arg("--cert-store").arg(&certd)
832 .arg("verify").arg("--message")
833 .arg("--signer").arg(&alice.fingerprint().to_string())
834 .arg(&msg_pgp);
835 let output = cmd.output().expect("success");
836 let stdout = String::from_utf8_lossy(&output.stdout);
837 let stderr = String::from_utf8_lossy(&output.stderr);
838 assert!(output.status.success(),
839 "stdout:\n{}\nstderr: {}", stdout, stderr);
840
841 // The default trust model says that certificates from the
842 // certificate store are not authenticated.
843 assert!(stderr.contains("Authenticated signature made by "),
844 "stdout:\n{}\nstderr: {}", stdout, stderr);
845 assert!(stderr.contains("1 authenticated signature."),
846 "stdout:\n{}\nstderr: {}", stdout, stderr);
847
848 Ok(())
849 }
850
851 // Verify signatures using the web of trust to authenticate the
852 // signers.
853 #[test]
854 fn sq_verify_wot() -> Result<()> {
855 let sq = Sq::new();
856 let dir = TempDir::new()?;
857
858 let certd = dir.path().join("cert.d").display().to_string();
859 std::fs::create_dir(&certd).expect("mkdir works");
860
861 let alice_pgp = dir.path().join("alice.pgp").display().to_string();
862 let bob_pgp = dir.path().join("bob.pgp").display().to_string();
863 let carol_pgp = dir.path().join("carol.pgp").display().to_string();
864 let dave_pgp = dir.path().join("dave.pgp").display().to_string();
865 let msg_pgp = dir.path().join("msg.pgp").display().to_string();
866
867 // Generates a key.
868 //
869 // If cert_store is not `None`, then the resulting certificate is also
870 // imported.
871 let sq_gen_key = |sq: &Sq, userids: &[&str], file_out: &str|
872 -> Cert
873 {
874 let (cert, file, _) = sq.key_generate(&[], userids);
875 sq.cert_import(&file);
876 fs::rename(file, file_out).unwrap();
877 cert
878 };
879
880 // Verifies a signed message.
881 let sq_verify = |sq: &Sq,
882 trust_roots: &[&str],
883 signer_files: &[&str],
884 msg_pgp: &str|
885 {
886 let mut cmd = sq.command();
887 for trust_root in trust_roots {
888 cmd.args(&["--trust-root", trust_root]);
889 }
890 cmd.arg("verify").arg("--message");
891 for signer_file in signer_files {
892 cmd.args(&["--signer-file", signer_file]);
893 }
894 cmd.arg(msg_pgp);
895 let output = sq.run(cmd, None);
896
897 (output.status.clone(),
898 String::from_utf8_lossy(&output.stdout).to_string(),
899 String::from_utf8_lossy(&output.stderr).to_string())
900 };
901
902 // Certifies a binding.
903 //
904 // The certification is imported into the cert store.
905 let sq_certify = |sq: &Sq,
906 certifier: &str, cert: &str, userid: &str,
907 trust_amount: Option<usize>|
908 {
909 let mut extra_args = Vec::new();
910 let trust_amount_;
911 if let Some(trust_amount) = trust_amount {
912 extra_args.push("--amount");
913 trust_amount_ = format!("{}", trust_amount);
914 extra_args.push(&trust_amount_);
915 }
916
917 let certification = sq.scratch_file(Some(&format!(
918 "certification {} {} by {}", cert, userid, certifier)[..]));
919
920 let cert = if let Ok(kh) = cert.parse::<KeyHandle>() {
921 kh.into()
922 } else {
923 FileOrKeyHandle::FileOrStdin(cert.into())
924 };
925
926 sq.pki_vouch_add(&extra_args, certifier, cert, &[userid],
927 Some(certification.as_path()));
928 sq.cert_import(&certification);
929 };
930
931 let alice = sq_gen_key(&sq, &[ "<[email protected]>" ], &alice_pgp);
932 let bob = sq_gen_key(&sq, &[ "<[email protected]>" ], &bob_pgp);
933 let carol = sq_gen_key(&sq, &[ "<[email protected]>" ], &carol_pgp);
934 let dave = sq_gen_key(&sq, &[ "<[email protected]>" ], &dave_pgp);
935
936 let alice_fpr = alice.fingerprint().to_string();
937 let bob_fpr = bob.fingerprint().to_string();
938 let carol_fpr = carol.fingerprint().to_string();
939 let dave_fpr = dave.fingerprint().to_string();
940
941 // Sign a message.
942 sq.command()
943 .arg("sign")
944 .arg("--message")
945 .args(["--signer-file", &bob_pgp])
946 .args(["--signer-file", &carol_pgp])
947 .args(["--signer-file", &dave_pgp])
948 .args(["--output", &msg_pgp])
949 .arg(&artifact("messages/a-cypherpunks-manifesto.txt"))
950 .assert()
951 .success();
952
953 // When designating the signers using a file, the signers are
954 // fully trusted.
955 {
956 let output = sq_verify(&sq, &[], &[&bob_pgp], &msg_pgp);
957 assert!(output.0.success());
958 let output = sq_verify(&sq, &[], &[&carol_pgp], &msg_pgp);
959 assert!(output.0.success());
960 let output = sq_verify(&sq, &[], &[&dave_pgp], &msg_pgp);
961 assert!(output.0.success());
962
963 // Alice did not sign it so this should fail.
964 let output = sq_verify(&sq, &[], &[&alice_pgp], &msg_pgp);
965 assert!(! output.0.success());
966
967 // But, one authenticated signature is enough.
968 let output = sq_verify(&sq, &[], &[&alice_pgp, &bob_pgp], &msg_pgp);
969 assert!(output.0.success());
970 }
971
972 // When the signers' certificates are found in the cert store, and
973 // they can't be authenticated with the web of trust, the
974 // verification will fail.
975 {
976 let output = sq_verify(&sq, &[], &[], &msg_pgp);
977 assert!(! output.0.success(),
978 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
979 assert!(output.2.contains("the certificate can't be authenticated."),
980 "stdout:\n{}\nstderr:\n{}",
981 output.1, output.2);
982
983 // Specifying a trust root won't help if there is no path to a
984 // signer.
985 let output = sq_verify(&sq, &[&alice_fpr], &[], &msg_pgp);
986 assert!(! output.0.success(),
987 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
988 assert!(output.2.contains("the certificate can't be authenticated."),
989 "stdout:\n{}\nstderr:\n{}",
990 output.1, output.2);
991 }
992
993 // A trust root can certify itself
994 {
995 let output = sq_verify(&sq, &[&bob_fpr], &[], &msg_pgp);
996 assert!(output.0.success(),
997 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
998 assert!(output.2.contains("Authenticated signature made by "),
999 "stdout:\n{}\nstderr:\n{}",
1000 output.1, output.2);
1001
1002 let output = sq_verify(
1003 &sq, &[&alice_fpr, &bob_fpr], &[], &msg_pgp);
1004 assert!(output.0.success(),
1005 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
1006 assert!(output.2.contains("Authenticated signature made by "),
1007 "stdout:\n{}\nstderr:\n{}",
1008 output.1, output.2);
1009 }
1010
1011 // Have Alice partially certify Bob, and make Alice the trust
1012 // root. The signature should still be bad.
1013 {
1014 sq_certify(&sq, &alice_pgp,
1015 &bob.fingerprint().to_string(), "<[email protected]>",
1016 Some(90));
1017 let output = sq_verify(&sq, &[&alice_fpr], &[], &msg_pgp);
1018 assert!(! output.0.success(),
1019 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
1020 assert!(output.2.contains("the certificate can't be authenticated."),
1021 "stdout:\n{}\nstderr:\n{}",
1022 output.1, output.2);
1023 }
1024
1025 // Have Alice also partially certify Carol, and make Alice the
1026 // trust root. Bob and Carol combined don't (currently) make the
1027 // signature good.
1028 {
1029 sq_certify(&sq, &alice_pgp,
1030 &carol_fpr, "<[email protected]>",
1031 Some(60));
1032 let output = sq_verify(&sq, &[&alice_fpr], &[], &msg_pgp);
1033 assert!(! output.0.success(),
1034 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
1035 assert!(output.2.contains("the certificate can't be authenticated."),
1036 "stdout:\n{}\nstderr:\n{}",
1037 output.1, output.2);
1038 assert!(output.2.contains("3 unauthenticated signatures"),
1039 "stdout:\n{}\nstderr:\n{}",
1040 output.1, output.2);
1041 }
1042
1043 // Have Alice fully certify Dave, and make Alice the trust root.
1044 // Now the signature will be considered verified.
1045 {
1046 sq_certify(&sq, &alice_pgp,
1047 &dave_fpr, "<[email protected]>",
1048 None);
1049 let output = sq_verify(&sq, &[&alice_fpr], &[], &msg_pgp);
1050 assert!(output.0.success(),
1051 "stdout:\n{}\nstderr:\n{}", output.1, output.2);
1052 assert!(output.2.contains("Authenticated signature made by "),
1053 "stdout:\n{}\nstderr:\n{}",
1054 output.1, output.2);
1055 assert!(output.2.contains("1 authenticated signature, 2 unauthenticated signatures"),
1056 "stdout:\n{}\nstderr:\n{}",
1057 output.1, output.2);
1058 }
1059
1060 Ok(())
1061 }
1062
1063 #[test]
1064 fn sq_sign_keyring() {
1065 // Check that we can provide the secret key material via
1066 // --keyring.
1067
1068 let sq = Sq::new();
1069
1070 let (_alice, alice_pgp, _alice_rev)
1071 = sq.key_generate(&[], &["alice"]);
1072
1073 let mut alice_pub = alice_pgp.clone();
1074 alice_pub.set_extension("pub");
1075
1076 sq.key_delete(&alice_pgp, Some(&*alice_pub));
1077
1078 // We pass the secret key material via --keyring. This should
1079 // work.
1080 let mut cmd = sq.command();
1081 cmd.arg("--keyring").arg(&alice_pgp)
1082 .arg("sign")
1083 .arg("--message")
1084 .arg("--signer-file").arg(&alice_pub);
1085
1086 sq.run(cmd, Some(true));
1087
1088 // If we don't pass the secret key material, this should fail.
1089 let mut cmd = sq.command();
1090 cmd.arg("sign")
1091 .arg("--message")
1092 .arg("--signer-file").arg(&alice_pub);
1093
1094 sq.run(cmd, Some(false));
1095 }
1096
1097 /// Creates a text signature.
1098 #[test]
1099 fn sq_sign_mode_text() -> Result<()> {
1100 let sq = Sq::new();
1101
1102 let (_alice, alice_pgp, _alice_rev)
1103 = sq.key_generate(&[], &["alice"]);
1104
1105 let data_n = sq.scratch_dir().join("data_n");
1106 std::fs::write(&data_n, "Hello\n")?;
1107
1108 let sig = sq.scratch_dir().join("sig");
1109 sq.sign_detached(&["--mode=text"], alice_pgp.as_path(),
1110 data_n.as_path(), sig.as_path());
1111
1112 let verify_args = ["--signer-file", &alice_pgp.display().to_string()];
1113 sq.verify(&verify_args, Verify::SignatureFile(sig.clone()), &data_n, None);
1114
1115 let data_rn = sq.scratch_dir().join("data_rn");
1116 std::fs::write(&data_rn, "Hello\r\n")?;
1117 sq.verify(&verify_args, Verify::SignatureFile(sig.clone()), &data_rn, None);
1118
1119 Ok(())
1120 }