sequoia_openpgp/parse/stream.rs
1//! Streaming decryption and verification.
2//!
3//! This module provides convenient filters for decryption and
4//! verification of OpenPGP messages (see [Section 10.3 of RFC 9580]).
5//! It is the preferred interface to process OpenPGP messages:
6//!
7//! [Section 10.3 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-10.3
8//!
9//! - Use the [`Verifier`] to verify a signed message,
10//! - [`DetachedVerifier`] to verify a detached signature,
11//! - or [`Decryptor`] to decrypt and verify an encrypted and
12//! possibly signed message.
13//!
14//!
15//! Consuming OpenPGP messages is more difficult than producing them.
16//! When we produce the message, we control the packet structure being
17//! generated using our programs control flow. However, when we
18//! consume a message, the control flow is determined by the message
19//! being processed.
20//!
21//! To use Sequoia's streaming [`Verifier`] and [`Decryptor`], you
22//! need to provide an object that implements [`VerificationHelper`],
23//! and for the [`Decryptor`] also [`DecryptionHelper`].
24//!
25//!
26//! The [`VerificationHelper`] trait give certificates for the
27//! signature verification to the [`Verifier`] or [`Decryptor`], let
28//! you inspect the message structure (see [Section 10.3 of RFC
29//! 9580]), and implements the signature verification policy.
30//!
31//! The [`DecryptionHelper`] trait is concerned with producing the
32//! session key to decrypt a message, most commonly by decrypting one
33//! of the messages' [`PKESK`] or [`SKESK`] packets. It could also
34//! use a cached session key, or one that has been explicitly provided
35//! to the decryption operation.
36//!
37//! [`PKESK`]: crate::packet::PKESK
38//! [`SKESK`]: crate::packet::SKESK
39//!
40//! The [`Verifier`] and [`Decryptor`] are filters: they consume
41//! OpenPGP data from a reader, file, or bytes, and implement
42//! [`io::Read`] that can be used to read the verified and/or
43//! decrypted data.
44//!
45//! [`io::Read`]: std::io::Read
46//!
47//! [`DetachedVerifier`] does not provide the [`io::Read`] interface,
48//! because in this case, the data to be verified is easily available
49//! without any transformation. Not providing a filter-like interface
50//! allows for a very performant implementation of the verification.
51//!
52//! # Examples
53//!
54//! This example demonstrates how to use the streaming interface using
55//! the [`Verifier`]. For brevity, no certificates are fed to the
56//! verifier, and the message structure is not verified, i.e. this
57//! merely extracts the literal data. See the [`Verifier` examples]
58//! and the [`Decryptor` examples] for how to verify the message and
59//! its structure.
60//!
61//! [`Verifier` examples]: Verifier#examples
62//! [`Decryptor` examples]: Decryptor#examples
63//!
64//! ```
65//! # fn main() -> sequoia_openpgp::Result<()> {
66//! use std::io::Read;
67//! use sequoia_openpgp as openpgp;
68//! use openpgp::{KeyHandle, Cert, Result};
69//! use openpgp::parse::{Parse, stream::*};
70//! use openpgp::policy::StandardPolicy;
71//!
72//! let p = &StandardPolicy::new();
73//!
74//! // This fetches keys and computes the validity of the verification.
75//! struct Helper {}
76//! impl VerificationHelper for Helper {
77//! fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
78//! Ok(Vec::new()) // Feed the Certs to the verifier here...
79//! }
80//! fn check(&mut self, structure: MessageStructure) -> Result<()> {
81//! Ok(()) // Implement your verification policy here.
82//! }
83//! }
84//!
85//! let message =
86//! b"-----BEGIN PGP MESSAGE-----
87//!
88//! xA0DAAoWBpwMNI3YLBkByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoAJwWCW37P
89//! 8RahBI6MM/pGJjN5dtl5eAacDDSN2CwZCZAGnAw0jdgsGQAAeZQA/2amPbBXT96Q
90//! O7PFms9DRuehsVVrFkaDtjN2WSxI4RGvAQDq/pzNdCMpy/Yo7AZNqZv5qNMtDdhE
91//! b2WH5lghfKe/AQ==
92//! =DjuO
93//! -----END PGP MESSAGE-----";
94//!
95//! let h = Helper {};
96//! let mut v = VerifierBuilder::from_bytes(&message[..])?
97//! .with_policy(p, None, h)?;
98//!
99//! let mut content = Vec::new();
100//! v.read_to_end(&mut content)?;
101//! assert_eq!(content, b"Hello World!");
102//! # Ok(()) }
103//! ```
104use std::cmp;
105use std::io;
106use std::path::Path;
107use std::time;
108
109use buffered_reader::BufferedReader;
110use crate::{
111 Error,
112 Fingerprint,
113 types::{
114 AEADAlgorithm,
115 CompressionAlgorithm,
116 RevocationStatus,
117 SymmetricAlgorithm,
118 },
119 packet::{
120 key,
121 OnePassSig,
122 PKESK,
123 SEIP,
124 SKESK,
125 },
126 KeyHandle,
127 Packet,
128 Result,
129 packet,
130 packet::{Signature, Unknown},
131 cert::prelude::*,
132 crypto::SessionKey,
133 policy::Policy,
134};
135use crate::parse::{
136 Cookie,
137 HashingMode,
138 PacketParser,
139 PacketParserBuilder,
140 PacketParserResult,
141 Parse,
142};
143
144/// Whether to trace execution by default (on stderr).
145const TRACE : bool = false;
146
147/// Indentation level for tracing in this module.
148const TRACE_INDENT: isize = 5;
149
150/// How much data to buffer before giving it to the caller.
151///
152/// Signature verification and detection of ciphertext tampering
153/// requires processing the whole message first. Therefore, OpenPGP
154/// implementations supporting streaming operations necessarily must
155/// output unverified data. This has been a source of problems in the
156/// past. To alleviate this, we buffer the message first (up to 25
157/// megabytes of net message data by default), and verify the
158/// signatures if the message fits into our buffer. Nevertheless it
159/// is important to treat the data as unverified and untrustworthy
160/// until you have seen a positive verification.
161///
162/// The default can be changed using [`VerifierBuilder::buffer_size`]
163/// and [`DecryptorBuilder::buffer_size`].
164///
165/// [`VerifierBuilder::buffer_size`]: VerifierBuilder::buffer_size()
166/// [`DecryptorBuilder::buffer_size`]: DecryptorBuilder::buffer_size()
167pub const DEFAULT_BUFFER_SIZE: usize = 25 * 1024 * 1024;
168
169/// Result of a signature verification.
170///
171/// A signature verification is either successful yielding a
172/// [`GoodChecksum`], or there was some [`VerificationError`]
173/// explaining the verification failure.
174///
175pub type VerificationResult<'a> =
176 std::result::Result<GoodChecksum<'a>, VerificationError<'a>>;
177
178/// A good signature.
179///
180/// Represents the result of a successful signature verification. It
181/// includes the signature and the signing key with all the necessary
182/// context (i.e. certificate, time, policy) to evaluate the
183/// trustworthiness of the signature using a trust model.
184///
185/// `GoodChecksum` is used in [`VerificationResult`]. See also
186/// [`VerificationError`].
187///
188///
189/// A signature is considered good if and only if all the following
190/// conditions are met:
191///
192/// - The signature has a Signature Creation Time subpacket.
193///
194/// - The signature is alive at the specified time (the time
195/// parameter passed to, e.g., [`VerifierBuilder::with_policy`]).
196///
197/// [`VerifierBuilder::with_policy`]: VerifierBuilder::with_policy()
198///
199/// - The certificate is alive and not revoked as of the signature's
200/// creation time.
201///
202/// - The signing key is alive, not revoked, and signing capable as
203/// of the signature's creation time.
204///
205/// - The signature was generated by the signing key.
206///
207/// **Note**: This doesn't mean that the key that generated the
208/// signature is in any way trustworthy in the sense that it
209/// belongs to the person or entity that the user thinks it
210/// belongs to. This property can only be evaluated within a
211/// trust model, such as the [web of trust] (WoT). This policy is
212/// normally implemented in the [`VerificationHelper::check`]
213/// method.
214///
215/// [web of trust]: https://en.wikipedia.org/wiki/Web_of_trust
216#[derive(Debug)]
217pub struct GoodChecksum<'a> {
218 /// The signature.
219 pub sig: &'a Signature,
220
221 /// The signing key that made the signature.
222 ///
223 /// The amalgamation of the signing key includes the necessary
224 /// context (i.e. certificate, time, policy) to evaluate the
225 /// trustworthiness of the signature using a trust model.
226 pub ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
227}
228assert_send_and_sync!(GoodChecksum<'_>);
229
230/// A bad signature.
231///
232/// Represents the result of an unsuccessful signature verification.
233/// It contains all the context that could be gathered until the
234/// verification process failed.
235///
236/// `VerificationError` is used in [`VerificationResult`]. See also
237/// [`GoodChecksum`].
238///
239///
240/// You can either explicitly match on the variants, or convert to
241/// [`Error`] using [`From`].
242///
243/// [`Error`]: super::super::Error
244/// [`From`]: std::convert::From
245#[non_exhaustive]
246#[derive(Debug)]
247pub enum VerificationError<'a> {
248 /// Missing Key
249 MissingKey {
250 /// The signature.
251 sig: &'a Signature,
252 },
253 /// Unbound key.
254 ///
255 /// There is no valid binding signature at the time the signature
256 /// was created under the given policy.
257 UnboundKey {
258 /// The signature.
259 sig: &'a Signature,
260
261 /// The certificate that made the signature.
262 cert: &'a Cert,
263
264 /// The reason why the key is not bound.
265 error: anyhow::Error,
266 },
267 /// Bad key (have a key, but it is not alive, etc.)
268 BadKey {
269 /// The signature.
270 sig: &'a Signature,
271
272 /// The signing key that made the signature.
273 ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
274
275 /// The reason why the key is bad.
276 error: anyhow::Error,
277 },
278 /// Bad signature (have a valid key, but the signature didn't check out)
279 BadSignature {
280 /// The signature.
281 sig: &'a Signature,
282
283 /// The signing key that made the signature.
284 ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
285
286 /// The reason why the signature is bad.
287 error: anyhow::Error,
288 },
289
290 /// Malformed signature (no signature creation subpacket, etc.).
291 MalformedSignature {
292 /// The signature.
293 sig: &'a Signature,
294
295 /// The reason why the signature is malformed.
296 error: anyhow::Error,
297 },
298
299 /// A signature that failed to parse at all.
300 UnknownSignature {
301 /// The signature parsed into an [`crate::packet::Unknown`]
302 /// packet.
303 sig: &'a Unknown,
304 }
305}
306assert_send_and_sync!(VerificationError<'_>);
307
308impl<'a> std::fmt::Display for VerificationError<'a> {
309 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
310 use self::VerificationError::*;
311 match self {
312 MalformedSignature { error, .. } =>
313 write!(f, "Malformed signature: {}", error),
314 UnknownSignature { sig, .. } =>
315 write!(f, "Malformed signature: {}", sig.error()),
316 MissingKey { sig } =>
317 if let Some(issuer) = sig.get_issuers().get(0) {
318 write!(f, "Missing key: {}", issuer)
319 } else {
320 write!(f, "Missing key")
321 },
322 UnboundKey { cert, error, .. } =>
323 write!(f, "Subkey of {} not bound: {}", cert, error),
324 BadKey { ka, error, .. } =>
325 write!(f, "Subkey of {} is bad: {}", ka.cert(), error),
326 BadSignature { error, .. } =>
327 write!(f, "Bad signature: {}", error),
328 }
329 }
330}
331
332impl<'a> std::error::Error for VerificationError<'a> {}
333
334impl<'a> From<VerificationError<'a>> for Error {
335 fn from(e: VerificationError<'a>) -> Self {
336 use self::VerificationError::*;
337 match e {
338 MalformedSignature { .. } =>
339 Error::MalformedPacket(e.to_string()),
340 UnknownSignature { sig } =>
341 Error::MalformedPacket(sig.error().to_string()),
342 MissingKey { .. } =>
343 Error::InvalidKey(e.to_string()),
344 UnboundKey { .. } =>
345 Error::InvalidKey(e.to_string()),
346 BadKey { .. } =>
347 Error::InvalidKey(e.to_string()),
348 BadSignature { .. } =>
349 Error::BadSignature(e.to_string()),
350 }
351 }
352}
353
354/// Like VerificationError, but without referencing the signature.
355///
356/// This avoids borrowing the signature, so that we can continue to
357/// mutably borrow the signature trying other keys. After all keys
358/// are tried, we attach the reference to the signature, yielding a
359/// `VerificationError`.
360enum VerificationErrorInternal<'a> {
361 // MalformedSignature is not used, so it is omitted here.
362
363 /// Missing Key
364 MissingKey {
365 },
366 /// Unbound key.
367 ///
368 /// There is no valid binding signature at the time the signature
369 /// was created under the given policy.
370 UnboundKey {
371 /// The certificate that made the signature.
372 cert: &'a Cert,
373
374 /// The reason why the key is not bound.
375 error: anyhow::Error,
376 },
377 /// Bad key (have a key, but it is not alive, etc.)
378 BadKey {
379 /// The signing key that made the signature.
380 ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
381
382 /// The reason why the key is bad.
383 error: anyhow::Error,
384 },
385 /// Bad signature (have a valid key, but the signature didn't check out)
386 BadSignature {
387 /// The signing key that made the signature.
388 ka: ValidErasedKeyAmalgamation<'a, key::PublicParts>,
389
390 /// The reason why the signature is bad.
391 error: anyhow::Error,
392 },
393}
394
395impl<'a> VerificationErrorInternal<'a> {
396 fn attach_sig(self, sig: &'a Signature) -> VerificationError<'a> {
397 use self::VerificationErrorInternal::*;
398 match self {
399 MissingKey {} =>
400 VerificationError::MissingKey { sig },
401 UnboundKey { cert, error } =>
402 VerificationError::UnboundKey { sig, cert, error },
403 BadKey { ka, error } =>
404 VerificationError::BadKey { sig, ka, error },
405 BadSignature { ka, error } =>
406 VerificationError::BadSignature { sig, ka, error },
407 }
408 }
409}
410
411/// Communicates the message structure to the VerificationHelper.
412///
413/// A valid OpenPGP message contains one literal data packet with
414/// optional [encryption, signing, and compression layers] freely
415/// combined on top. This structure is passed to
416/// [`VerificationHelper::check`] for verification.
417///
418/// [encryption, signing, and compression layers]: MessageLayer
419///
420/// The most common structure is an optionally encrypted, optionally
421/// compressed, and optionally signed message, i.e. if the message is
422/// encrypted, then the encryption is the outermost layer; if the
423/// message is signed, then the signature group is the innermost
424/// layer. This is a sketch of such a message:
425///
426/// ```text
427/// [ encryption layer: [ compression layer: [ signature group: [ literal data ]]]]
428/// ```
429///
430/// However, OpenPGP allows encryption, signing, and compression
431/// operations to be freely combined (see [Section 10.3 of RFC 9580]).
432/// This is represented as a stack of [`MessageLayer`]s, where
433/// signatures of the same level (i.e. those over the same data:
434/// either directly over the literal data, or over other signatures
435/// and the literal data) are grouped into one layer. See also
436/// [`Signature::level`].
437///
438/// [Section 10.3 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-10.3
439/// [`Signature::level`]: crate::packet::Signature#method.level
440///
441/// Consider the following structure. This is a set of notarizing
442/// signatures *N* over a set of signatures *S* over the literal data:
443///
444/// ```text
445/// [ signature group: [ signature group: [ literal data ]]]
446/// ```
447///
448/// The notarizing signatures *N* are said to be of level 1,
449/// i.e. signatures over the signatures *S* and the literal data. The
450/// signatures *S* are level 0 signatures, i.e. signatures over the
451/// literal data.
452///
453/// OpenPGP's flexibility allows adaption to new use cases, but also
454/// presents a challenge to implementations and downstream users. The
455/// message structure must be both validated, and possibly
456/// communicated to the application's user. Note that if
457/// compatibility is a concern, generated messages must be restricted
458/// to a narrow subset of possible structures, see this [test of
459/// unusual message structures].
460///
461/// [test of unusual message structures]: https://tests.sequoia-pgp.org/#Unusual_Message_Structure
462#[derive(Debug)]
463pub struct MessageStructure<'a>(Vec<MessageLayer<'a>>);
464assert_send_and_sync!(MessageStructure<'_>);
465
466impl<'a> MessageStructure<'a> {
467 fn new() -> Self {
468 MessageStructure(Vec::new())
469 }
470
471 fn new_compression_layer(&mut self, algo: CompressionAlgorithm) {
472 self.0.push(MessageLayer::Compression {
473 algo,
474 })
475 }
476
477 fn new_encryption_layer(&mut self, sym_algo: SymmetricAlgorithm,
478 aead_algo: Option<AEADAlgorithm>) {
479 self.0.push(MessageLayer::Encryption {
480 sym_algo,
481 aead_algo,
482 })
483 }
484
485 fn new_signature_group(&mut self) {
486 self.0.push(MessageLayer::SignatureGroup {
487 results: Vec::new(),
488 })
489 }
490
491 fn push_verification_result(&mut self, sig: VerificationResult<'a>) {
492 if let Some(MessageLayer::SignatureGroup { ref mut results }) =
493 self.0.iter_mut().last()
494 {
495 results.push(sig);
496 } else {
497 panic!("cannot push to encryption or compression layer");
498 }
499 }
500
501 /// Returns an iterator over the message layers.
502 pub fn iter(&self) -> impl Iterator<Item=&MessageLayer<'a>> {
503 self.0.iter()
504 }
505}
506
507impl<'a> IntoIterator for MessageStructure<'a> {
508 type Item = MessageLayer<'a>;
509 type IntoIter = std::vec::IntoIter<MessageLayer<'a>>;
510
511 fn into_iter(self) -> Self::IntoIter {
512 self.0.into_iter()
513 }
514}
515
516/// Represents a layer of the message structure.
517///
518/// A valid OpenPGP message contains one literal data packet with
519/// optional encryption, signing, and compression layers freely
520/// combined on top (see [Section 10.3 of RFC 9580]). This enum
521/// represents the layers. The [`MessageStructure`] is communicated
522/// to the [`VerificationHelper::check`]. Iterating over the
523/// [`MessageStructure`] yields the individual message layers.
524///
525/// [Section 10.3 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-10.3
526#[derive(Debug)]
527pub enum MessageLayer<'a> {
528 /// Represents a compression container.
529 ///
530 /// Compression is usually transparent in OpenPGP, though it may
531 /// sometimes be interesting for advanced users to indicate that
532 /// the message was compressed, and how (see [Section 5.6 of RFC
533 /// 9580]).
534 ///
535 /// [Section 5.6 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.6
536 Compression {
537 /// Compression algorithm used.
538 algo: CompressionAlgorithm,
539 },
540 /// Represents an encryption container.
541 ///
542 /// Indicates the fact that the message was encrypted (see
543 /// [Section 5.13 of RFC 9580]). If you expect encrypted
544 /// messages, make sure that there is at least one encryption
545 /// container present.
546 ///
547 /// [Section 5.13 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.13
548 Encryption {
549 /// Symmetric algorithm used.
550 sym_algo: SymmetricAlgorithm,
551 /// AEAD algorithm used, if any.
552 aead_algo: Option<AEADAlgorithm>,
553 },
554 /// Represents a signature group.
555 ///
556 /// A signature group consists of all signatures with the same
557 /// level (see [Section 5.2 of RFC 9580]). Each
558 /// [`VerificationResult`] represents the result of a single
559 /// signature verification. In your [`VerificationHelper::check`]
560 /// method, iterate over the verification results, see if it meets
561 /// your policies' demands, and communicate it to the user, if
562 /// applicable.
563 ///
564 /// [Section 5.2 of RFC 9580]: https://www.rfc-editor.org/rfc/rfc9580.html#section-5.2
565 SignatureGroup {
566 /// The results of the signature verifications.
567 results: Vec<VerificationResult<'a>>,
568 }
569}
570assert_send_and_sync!(MessageLayer<'_>);
571
572/// Internal version of the message structure.
573///
574/// In contrast to MessageStructure, this owns unverified
575/// signature packets.
576#[derive(Debug)]
577struct IMessageStructure {
578 layers: Vec<IMessageLayer>,
579
580 // We insert a SignatureGroup layer every time we see a OnePassSig
581 // packet with the last flag.
582 //
583 // However, we need to make sure that we insert a SignatureGroup
584 // layer even if the OnePassSig packet has the last flag set to
585 // false. To do that, we keep track of the fact that we saw such
586 // a OPS packet.
587 sig_group_counter: usize,
588}
589
590impl IMessageStructure {
591 fn new() -> Self {
592 IMessageStructure {
593 layers: Vec::new(),
594 sig_group_counter: 0,
595 }
596 }
597
598 fn new_compression_layer(&mut self, algo: CompressionAlgorithm) {
599 tracer!(TRACE, "IMessageStructure::new_compression_layer", TRACE_INDENT);
600 t!("pushing a {:?} layer", algo);
601
602 self.insert_missing_signature_group();
603 self.layers.push(IMessageLayer::Compression {
604 algo,
605 });
606 }
607
608 fn new_encryption_layer(&mut self,
609 depth: isize,
610 expect_mdc: bool,
611 sym_algo: SymmetricAlgorithm,
612 aead_algo: Option<AEADAlgorithm>) {
613 tracer!(TRACE, "IMessageStructure::new_encryption_layer", TRACE_INDENT);
614 t!("pushing a {:?}/{:?} layer", sym_algo, aead_algo);
615
616 self.insert_missing_signature_group();
617 self.layers.push(IMessageLayer::Encryption {
618 depth,
619 expect_mdc,
620 sym_algo,
621 aead_algo,
622 });
623 }
624
625 /// Returns whether we expect an MDC packet in an
626 /// encryption container at this recursion depth.
627 ///
628 /// Handling MDC packets has to be done carefully, otherwise, we
629 /// may create a decryption oracle.
630 fn expect_mdc_at(&self, at: isize) -> bool {
631 for l in &self.layers {
632 match l {
633 IMessageLayer::Encryption {
634 depth,
635 expect_mdc,
636 ..
637 } if *depth == at && *expect_mdc => return true,
638 _ => (),
639 }
640 }
641 false
642 }
643
644 /// Makes sure that we insert a signature group even if the
645 /// previous OPS packet had the last flag set to false.
646 fn insert_missing_signature_group(&mut self) {
647 tracer!(TRACE, "IMessageStructure::insert_missing_signature_group",
648 TRACE_INDENT);
649
650 if self.sig_group_counter > 0 {
651 t!("implicit insert of signature group for {} sigs",
652 self.sig_group_counter);
653
654 self.layers.push(IMessageLayer::SignatureGroup {
655 sigs: Vec::new(),
656 count: self.sig_group_counter,
657 });
658 }
659 self.sig_group_counter = 0;
660 }
661
662 fn push_ops(&mut self, ops: &OnePassSig) {
663 tracer!(TRACE, "IMessageStructure::push_ops", TRACE_INDENT);
664 t!("Pushing {:?}", ops);
665
666 self.sig_group_counter += 1;
667 if ops.last() {
668 self.layers.push(IMessageLayer::SignatureGroup {
669 sigs: Vec::new(),
670 count: self.sig_group_counter,
671 });
672 self.sig_group_counter = 0;
673 }
674 }
675
676 fn push_signature(&mut self, sig: MaybeSignature, csf_message: bool) {
677 tracer!(TRACE, "IMessageStructure::push_signature", TRACE_INDENT);
678 t!("Pushing {:?}", sig);
679 if csf_message {
680 t!("Cleartext Signature Framework transformation enabled");
681 }
682
683 for (i, layer) in self.layers.iter_mut().enumerate().rev() {
684 t!("{}: {:?}", i, layer);
685 match layer {
686 IMessageLayer::SignatureGroup {
687 ref mut sigs, ref mut count,
688 } if *count > 0 => {
689 t!("Layer {} is a signature group with {} outstanding sigs",
690 i, *count);
691
692 sigs.push(sig);
693 if csf_message {
694 // The CSF transformation does not know how
695 // many signatures will follow, so we may end
696 // up with too few synthesized OPS packets.
697 // But, we only have one layer anyway, and no
698 // notarizations, so we don't need to concern
699 // ourselves with the counter.
700 } else {
701 *count -= 1;
702 }
703 return;
704 },
705 _ => (),
706 }
707 }
708
709 // As a last resort, push a new signature group for this
710 // signature. This may not accurately describe the structure,
711 // but if we get to this point, we failed to grasp the message
712 // structure in some way, so there is nothing we can do really.
713 t!("signature unaccounted for");
714 self.layers.push(IMessageLayer::SignatureGroup {
715 sigs: vec![sig],
716 count: 0,
717 });
718 }
719
720 fn push_bare_signature(&mut self, sig: MaybeSignature) {
721 if let Some(IMessageLayer::SignatureGroup { .. }) = self.layers.iter().last() {
722 // The last layer is a SignatureGroup. We will append the
723 // signature there without accounting for it.
724 } else {
725 // The last layer is not a SignatureGroup, or there is no
726 // layer at all. Create one.
727 self.layers.push(IMessageLayer::SignatureGroup {
728 sigs: Vec::new(),
729 count: 0,
730 });
731 }
732
733 if let IMessageLayer::SignatureGroup { ref mut sigs, .. } =
734 self.layers.iter_mut().last().expect("just checked or created")
735 {
736 sigs.push(sig);
737 } else {
738 unreachable!("just checked or created")
739 }
740 }
741
742}
743
744/// Internal version of a layer of the message structure.
745///
746/// In contrast to MessageLayer, this owns unverified signature packets.
747#[derive(Debug)]
748enum IMessageLayer {
749 Compression {
750 algo: CompressionAlgorithm,
751 },
752 Encryption {
753 /// Recursion depth of this container.
754 depth: isize,
755 /// Do we expect an MDC packet?
756 ///
757 /// I.e. is this a SEIPv1 container?
758 expect_mdc: bool,
759 sym_algo: SymmetricAlgorithm,
760 aead_algo: Option<AEADAlgorithm>,
761 },
762 SignatureGroup {
763 sigs: Vec<MaybeSignature>,
764 count: usize,
765 }
766}
767
768/// Represents [`Signature`]s and those that failed to parse in the
769/// form of [`Unknown`] packets.
770type MaybeSignature = std::result::Result<Signature, Unknown>;
771
772/// Helper for signature verification.
773///
774/// This trait abstracts over signature and message structure
775/// verification. It allows us to provide the [`Verifier`],
776/// [`DetachedVerifier`], and [`Decryptor`] without imposing a policy
777/// on how certificates for signature verification are looked up, or
778/// what message structure is considered acceptable.
779///
780///
781/// It also allows you to inspect each packet that is processed during
782/// verification or decryption, optionally providing a [`Map`] for
783/// each packet.
784///
785/// [`Map`]: super::map::Map
786pub trait VerificationHelper {
787 /// Inspects the message.
788 ///
789 /// Called once per packet. Can be used to inspect and dump
790 /// packets in encrypted messages.
791 ///
792 /// The default implementation does nothing.
793 fn inspect(&mut self, pp: &PacketParser) -> Result<()> {
794 // Do nothing.
795 let _ = pp;
796 Ok(())
797 }
798
799 /// Retrieves the certificates containing the specified keys.
800 ///
801 /// When implementing this method, you should return as many
802 /// certificates corresponding to the `ids` as you can.
803 ///
804 /// If an identifier is ambiguous, because, for instance, there
805 /// are multiple certificates with the same Key ID, then you
806 /// should return all of them.
807 ///
808 /// You should only return an error if processing should be
809 /// aborted. In general, you shouldn't return an error if you
810 /// don't have a certificate for a given identifier: if there are
811 /// multiple signatures, then, depending on your policy, verifying
812 /// a subset of them may be sufficient.
813 ///
814 /// This method will be called at most once per message.
815 ///
816 /// # Examples
817 ///
818 /// This example demonstrates how to look up the certificates for
819 /// the signature verification given the list of signature
820 /// issuers.
821 ///
822 /// ```
823 /// use sequoia_openpgp as openpgp;
824 /// use openpgp::{KeyHandle, Cert, Result};
825 /// use openpgp::parse::stream::*;
826 /// # fn lookup_cert_by_handle(_: &KeyHandle) -> Result<Cert> {
827 /// # unimplemented!()
828 /// # }
829 ///
830 /// struct Helper { /* ... */ }
831 /// impl VerificationHelper for Helper {
832 /// fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
833 /// let mut certs = Vec::new();
834 /// for id in ids {
835 /// certs.push(lookup_cert_by_handle(id)?);
836 /// }
837 /// Ok(certs)
838 /// }
839 /// // ...
840 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
841 /// # unimplemented!()
842 /// # }
843 /// }
844 /// ```
845 fn get_certs(&mut self, ids: &[crate::KeyHandle]) -> Result<Vec<Cert>>;
846
847 /// Validates the message structure.
848 ///
849 /// This function must validate the message's structure according
850 /// to an application specific policy. For example, it could
851 /// check that the required number of signatures or notarizations
852 /// were confirmed as good, and evaluate every signature's
853 /// validity under a trust model.
854 ///
855 /// A valid OpenPGP message contains one literal data packet with
856 /// optional encryption, signing, and compression layers on top.
857 /// Notably, the message structure contains the results of
858 /// signature verifications. See [`MessageStructure`] for more
859 /// information.
860 ///
861 ///
862 /// When verifying a message, this callback will be called exactly
863 /// once per message *after* the last signature has been verified
864 /// and *before* all the data has been returned. Any error
865 /// returned by this function will abort reading, and the error
866 /// will be propagated via the [`io::Read`] operation.
867 ///
868 /// [`io::Read`]: std::io::Read
869 ///
870 /// After this method was called, [`Verifier::message_processed`]
871 /// and [`Decryptor::message_processed`] return `true`.
872 ///
873 /// [`Verifier::message_processed`]: Verifier::message_processed()
874 /// [`Decryptor::message_processed`]: Decryptor::message_processed()
875 ///
876 /// When verifying a detached signature using the
877 /// [`DetachedVerifier`], this method will be called with a
878 /// [`MessageStructure`] containing exactly one layer, a signature
879 /// group.
880 ///
881 ///
882 /// # Examples
883 ///
884 /// This example demonstrates how to verify that the message is an
885 /// encrypted, optionally compressed, and signed message that has
886 /// at least one valid signature.
887 ///
888 /// ```
889 /// use sequoia_openpgp as openpgp;
890 /// use openpgp::{KeyHandle, Cert, Result};
891 /// use openpgp::parse::stream::*;
892 ///
893 /// struct Helper { /* ... */ }
894 /// impl VerificationHelper for Helper {
895 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
896 /// # unimplemented!();
897 /// # }
898 /// fn check(&mut self, structure: MessageStructure) -> Result<()> {
899 /// for (i, layer) in structure.into_iter().enumerate() {
900 /// match layer {
901 /// MessageLayer::Encryption { .. } if i == 0 => (),
902 /// MessageLayer::Compression { .. } if i == 1 => (),
903 /// MessageLayer::SignatureGroup { ref results }
904 /// if i == 1 || i == 2 =>
905 /// {
906 /// if ! results.iter().any(|r| r.is_ok()) {
907 /// return Err(anyhow::anyhow!(
908 /// "No valid signature"));
909 /// }
910 /// }
911 /// _ => return Err(anyhow::anyhow!(
912 /// "Unexpected message structure")),
913 /// }
914 /// }
915 /// Ok(())
916 /// }
917 /// // ...
918 /// }
919 /// ```
920 fn check(&mut self, structure: MessageStructure) -> Result<()>;
921}
922
923/// Wraps a VerificationHelper and adds a non-functional
924/// DecryptionHelper implementation.
925struct NoDecryptionHelper<V: VerificationHelper> {
926 v: V,
927}
928
929impl<V: VerificationHelper> VerificationHelper for NoDecryptionHelper<V> {
930 fn get_certs(&mut self, ids: &[crate::KeyHandle]) -> Result<Vec<Cert>>
931 {
932 self.v.get_certs(ids)
933 }
934 fn check(&mut self, structure: MessageStructure) -> Result<()>
935 {
936 self.v.check(structure)
937 }
938 fn inspect(&mut self, pp: &PacketParser) -> Result<()> {
939 self.v.inspect(pp)
940 }
941}
942
943impl<V: VerificationHelper> DecryptionHelper for NoDecryptionHelper<V> {
944 fn decrypt(&mut self, _: &[PKESK], _: &[SKESK],
945 _: Option<SymmetricAlgorithm>,
946 _: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
947 -> Result<Option<Cert>>
948 {
949 unreachable!("This is not used for verifications")
950 }
951}
952
953/// Verifies a signed OpenPGP message.
954///
955/// To create a `Verifier`, create a [`VerifierBuilder`] using
956/// [`Parse`], and customize it to your needs.
957///
958/// [`Parse`]: super::Parse
959///
960/// Signature verification requires processing the whole message
961/// first. Therefore, OpenPGP implementations supporting streaming
962/// operations necessarily must output unverified data. This has been
963/// a source of problems in the past. To alleviate this, we buffer
964/// the message first (up to 25 megabytes of net message data by
965/// default, see [`DEFAULT_BUFFER_SIZE`]), and verify the signatures
966/// if the message fits into our buffer. Nevertheless it is important
967/// to treat the data as unverified and untrustworthy until you have
968/// seen a positive verification. See [`Verifier::message_processed`]
969/// for more information.
970///
971/// [`Verifier::message_processed`]: Verifier::message_processed()
972///
973/// See [`GoodChecksum`] for what it means for a signature to be
974/// considered valid.
975///
976///
977/// # Examples
978///
979/// ```
980/// # fn main() -> sequoia_openpgp::Result<()> {
981/// use std::io::Read;
982/// use sequoia_openpgp as openpgp;
983/// use openpgp::{KeyHandle, Cert, Result};
984/// use openpgp::parse::{Parse, stream::*};
985/// use openpgp::policy::StandardPolicy;
986/// # fn lookup_cert_by_handle(_: &KeyHandle) -> Result<Cert> {
987/// # Cert::from_bytes(
988/// # &b"-----BEGIN PGP PUBLIC KEY BLOCK-----
989/// #
990/// # xjMEWlNvABYJKwYBBAHaRw8BAQdA+EC2pvebpEbzPA9YplVgVXzkIG5eK+7wEAez
991/// # lcBgLJrNMVRlc3R5IE1jVGVzdGZhY2UgKG15IG5ldyBrZXkpIDx0ZXN0eUBleGFt
992/// # cGxlLm9yZz7CkAQTFggAOBYhBDnRAKtn1b2MBAECBfs3UfFYfa7xBQJaU28AAhsD
993/// # BQsJCAcCBhUICQoLAgQWAgMBAh4BAheAAAoJEPs3UfFYfa7xJHQBAO4/GABMWUcJ
994/// # 5D/DZ9b+6YiFnysSjCT/gILJgxMgl7uoAPwJherI1pAAh49RnPHBR1IkWDtwzX65
995/// # CJG8sDyO2FhzDs44BFpTbwASCisGAQQBl1UBBQEBB0B+A0GRHuBgdDX50T1nePjb
996/// # mKQ5PeqXJbWEtVrUtVJaPwMBCAfCeAQYFggAIBYhBDnRAKtn1b2MBAECBfs3UfFY
997/// # fa7xBQJaU28AAhsMAAoJEPs3UfFYfa7xzjIBANX2/FgDX3WkmvwpEHg/sn40zACM
998/// # W2hrBY5x0sZ8H7JlAP47mCfCuRVBqyaePuzKbxLJeLe2BpDdc0n2izMVj8t9Cg==
999/// # =QetZ
1000/// # -----END PGP PUBLIC KEY BLOCK-----"[..])
1001/// # }
1002///
1003/// let p = &StandardPolicy::new();
1004///
1005/// // This fetches keys and computes the validity of the verification.
1006/// struct Helper {}
1007/// impl VerificationHelper for Helper {
1008/// fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1009/// let mut certs = Vec::new();
1010/// for id in ids {
1011/// certs.push(lookup_cert_by_handle(id)?);
1012/// }
1013/// Ok(certs)
1014/// }
1015///
1016/// fn check(&mut self, structure: MessageStructure) -> Result<()> {
1017/// for (i, layer) in structure.into_iter().enumerate() {
1018/// match layer {
1019/// MessageLayer::Encryption { .. } if i == 0 => (),
1020/// MessageLayer::Compression { .. } if i == 1 => (),
1021/// MessageLayer::SignatureGroup { ref results } => {
1022/// if ! results.iter().any(|r| r.is_ok()) {
1023/// return Err(anyhow::anyhow!(
1024/// "No valid signature"));
1025/// }
1026/// }
1027/// _ => return Err(anyhow::anyhow!(
1028/// "Unexpected message structure")),
1029/// }
1030/// }
1031/// Ok(())
1032/// }
1033/// }
1034///
1035/// let message =
1036/// b"-----BEGIN PGP MESSAGE-----
1037///
1038/// xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1039/// AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1040/// UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1041/// YmAFv/UfO0vYBw==
1042/// =+l94
1043/// -----END PGP MESSAGE-----
1044/// ";
1045///
1046/// let h = Helper {};
1047/// let mut v = VerifierBuilder::from_bytes(&message[..])?
1048/// .with_policy(p, None, h)?;
1049///
1050/// let mut content = Vec::new();
1051/// v.read_to_end(&mut content)?;
1052/// assert_eq!(content, b"Hello World!");
1053/// # Ok(()) }
1054pub struct Verifier<'a, H: VerificationHelper> {
1055 decryptor: Decryptor<'a, NoDecryptionHelper<H>>,
1056}
1057assert_send_and_sync!(Verifier<'_, H> where H: VerificationHelper);
1058
1059/// A builder for `Verifier`.
1060///
1061/// This allows the customization of [`Verifier`], which can
1062/// be built using [`VerifierBuilder::with_policy`].
1063///
1064/// [`VerifierBuilder::with_policy`]: VerifierBuilder::with_policy()
1065pub struct VerifierBuilder<'a> {
1066 message: Box<dyn BufferedReader<Cookie> + 'a>,
1067 buffer_size: usize,
1068 mapping: bool,
1069}
1070assert_send_and_sync!(VerifierBuilder<'_>);
1071
1072impl<'a> Parse<'a, VerifierBuilder<'a>>
1073 for VerifierBuilder<'a>
1074{
1075 fn from_buffered_reader<R>(reader: R) -> Result<VerifierBuilder<'a>>
1076 where
1077 R: BufferedReader<Cookie> + 'a,
1078 {
1079 VerifierBuilder::new(reader)
1080 }
1081}
1082
1083impl<'a> crate::seal::Sealed for VerifierBuilder<'a> {}
1084
1085impl<'a> VerifierBuilder<'a> {
1086 fn new<B>(signatures: B) -> Result<Self>
1087 where B: buffered_reader::BufferedReader<Cookie> + 'a
1088 {
1089 Ok(VerifierBuilder {
1090 message: Box::new(signatures),
1091 buffer_size: DEFAULT_BUFFER_SIZE,
1092 mapping: false,
1093 })
1094 }
1095
1096 /// Changes the amount of buffered data.
1097 ///
1098 /// By default, we buffer up to 25 megabytes of net message data
1099 /// (see [`DEFAULT_BUFFER_SIZE`]). This changes the default.
1100 ///
1101 ///
1102 /// # Examples
1103 ///
1104 /// ```
1105 /// # fn main() -> sequoia_openpgp::Result<()> {
1106 /// use sequoia_openpgp as openpgp;
1107 /// # use openpgp::{KeyHandle, Cert, Result};
1108 /// use openpgp::parse::{Parse, stream::*};
1109 /// use openpgp::policy::StandardPolicy;
1110 ///
1111 /// let p = &StandardPolicy::new();
1112 ///
1113 /// struct Helper {}
1114 /// impl VerificationHelper for Helper {
1115 /// // ...
1116 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1117 /// # Ok(Vec::new())
1118 /// # }
1119 /// #
1120 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1121 /// # Ok(())
1122 /// # }
1123 /// }
1124 ///
1125 /// let message =
1126 /// // ...
1127 /// # &b"-----BEGIN PGP MESSAGE-----
1128 /// #
1129 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1130 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1131 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1132 /// # YmAFv/UfO0vYBw==
1133 /// # =+l94
1134 /// # -----END PGP MESSAGE-----
1135 /// # "[..];
1136 ///
1137 /// let h = Helper {};
1138 /// let mut v = VerifierBuilder::from_bytes(message)?
1139 /// .buffer_size(1 << 12)
1140 /// .with_policy(p, None, h)?;
1141 /// # let _ = v;
1142 /// # Ok(()) }
1143 /// ```
1144 pub fn buffer_size(mut self, size: usize) -> Self {
1145 self.buffer_size = size;
1146 self
1147 }
1148
1149 /// Enables mapping.
1150 ///
1151 /// If mapping is enabled, the packet parser will create a [`Map`]
1152 /// of the packets that can be inspected in
1153 /// [`VerificationHelper::inspect`]. Note that this buffers the
1154 /// packets contents, and is not recommended unless you know that
1155 /// the packets are small.
1156 ///
1157 /// [`Map`]: super::map::Map
1158 ///
1159 /// # Examples
1160 ///
1161 /// ```
1162 /// # fn main() -> sequoia_openpgp::Result<()> {
1163 /// use sequoia_openpgp as openpgp;
1164 /// # use openpgp::{KeyHandle, Cert, Result};
1165 /// use openpgp::parse::{Parse, stream::*};
1166 /// use openpgp::policy::StandardPolicy;
1167 ///
1168 /// let p = &StandardPolicy::new();
1169 ///
1170 /// struct Helper {}
1171 /// impl VerificationHelper for Helper {
1172 /// // ...
1173 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1174 /// # Ok(Vec::new())
1175 /// # }
1176 /// #
1177 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1178 /// # Ok(())
1179 /// # }
1180 /// }
1181 ///
1182 /// let message =
1183 /// // ...
1184 /// # &b"-----BEGIN PGP MESSAGE-----
1185 /// #
1186 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1187 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1188 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1189 /// # YmAFv/UfO0vYBw==
1190 /// # =+l94
1191 /// # -----END PGP MESSAGE-----
1192 /// # "[..];
1193 ///
1194 /// let h = Helper {};
1195 /// let mut v = VerifierBuilder::from_bytes(message)?
1196 /// .mapping(true)
1197 /// .with_policy(p, None, h)?;
1198 /// # let _ = v;
1199 /// # Ok(()) }
1200 /// ```
1201 pub fn mapping(mut self, enabled: bool) -> Self {
1202 self.mapping = enabled;
1203 self
1204 }
1205
1206 /// Creates the `Verifier`.
1207 ///
1208 /// Signature verifications are done under the given `policy` and
1209 /// relative to time `time`, or the current time, if `time` is
1210 /// `None`. `helper` is the [`VerificationHelper`] to use.
1211 ///
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```
1216 /// # fn main() -> sequoia_openpgp::Result<()> {
1217 /// use sequoia_openpgp as openpgp;
1218 /// # use openpgp::{KeyHandle, Cert, Result};
1219 /// use openpgp::parse::{Parse, stream::*};
1220 /// use openpgp::policy::StandardPolicy;
1221 ///
1222 /// let p = &StandardPolicy::new();
1223 ///
1224 /// struct Helper {}
1225 /// impl VerificationHelper for Helper {
1226 /// // ...
1227 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1228 /// # Ok(Vec::new())
1229 /// # }
1230 /// #
1231 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1232 /// # Ok(())
1233 /// # }
1234 /// }
1235 ///
1236 /// let message =
1237 /// // ...
1238 /// # &b"-----BEGIN PGP MESSAGE-----
1239 /// #
1240 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1241 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1242 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1243 /// # YmAFv/UfO0vYBw==
1244 /// # =+l94
1245 /// # -----END PGP MESSAGE-----
1246 /// # "[..];
1247 ///
1248 /// let h = Helper {};
1249 /// let mut v = VerifierBuilder::from_bytes(message)?
1250 /// // Customize the `Verifier` here.
1251 /// .with_policy(p, None, h)?;
1252 /// # let _ = v;
1253 /// # Ok(()) }
1254 /// ```
1255 pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
1256 -> Result<Verifier<'a, H>>
1257 where H: VerificationHelper,
1258 T: Into<Option<time::SystemTime>>,
1259 {
1260 // Do not eagerly map `t` to the current time.
1261 let t = time.into();
1262 Ok(Verifier {
1263 decryptor: Decryptor::from_cookie_reader(
1264 policy,
1265 self.message,
1266 NoDecryptionHelper { v: helper, },
1267 t, Mode::Verify, self.buffer_size, self.mapping, true)?,
1268 })
1269 }
1270}
1271
1272impl<'a, H: VerificationHelper> Verifier<'a, H> {
1273 /// Returns a reference to the helper.
1274 pub fn helper_ref(&self) -> &H {
1275 &self.decryptor.helper_ref().v
1276 }
1277
1278 /// Returns a mutable reference to the helper.
1279 pub fn helper_mut(&mut self) -> &mut H {
1280 &mut self.decryptor.helper_mut().v
1281 }
1282
1283 /// Recovers the helper.
1284 pub fn into_helper(self) -> H {
1285 self.decryptor.into_helper().v
1286 }
1287
1288 /// Returns true if the whole message has been processed and
1289 /// authenticated.
1290 ///
1291 /// If the function returns `true`, the whole message has been
1292 /// processed, the signatures are verified, and the message
1293 /// structure has been passed to [`VerificationHelper::check`].
1294 /// Data read from this `Verifier` using [`io::Read`] has been
1295 /// authenticated.
1296 ///
1297 /// [`io::Read`]: std::io::Read
1298 ///
1299 /// If the function returns `false`, the message did not fit into
1300 /// the internal buffer, and therefore data read from this
1301 /// `Verifier` using [`io::Read`] has **not yet been
1302 /// authenticated**. It is important to treat this data as
1303 /// attacker controlled and not use it until it has been
1304 /// authenticated.
1305 ///
1306 /// # Examples
1307 ///
1308 /// This example demonstrates how to verify a message in a
1309 /// streaming fashion, writing the data to a temporary file and
1310 /// only commit the result once the data is authenticated.
1311 ///
1312 /// ```
1313 /// # fn main() -> sequoia_openpgp::Result<()> {
1314 /// use std::io::{Read, Seek, SeekFrom};
1315 /// use sequoia_openpgp as openpgp;
1316 /// use openpgp::{KeyHandle, Cert, Result};
1317 /// use openpgp::parse::{Parse, stream::*};
1318 /// use openpgp::policy::StandardPolicy;
1319 /// #
1320 /// # // Mock of `tempfile::tempfile`.
1321 /// # mod tempfile {
1322 /// # pub fn tempfile() -> sequoia_openpgp::Result<std::fs::File> {
1323 /// # unimplemented!()
1324 /// # }
1325 /// # }
1326 ///
1327 /// let p = &StandardPolicy::new();
1328 ///
1329 /// // This fetches keys and computes the validity of the verification.
1330 /// struct Helper {}
1331 /// impl VerificationHelper for Helper {
1332 /// // ...
1333 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1334 /// # Ok(Vec::new())
1335 /// # }
1336 /// # fn check(&mut self, _: MessageStructure) -> Result<()> {
1337 /// # Ok(())
1338 /// # }
1339 /// }
1340 ///
1341 /// let mut source =
1342 /// // ...
1343 /// # std::io::Cursor::new(&b"-----BEGIN PGP MESSAGE-----
1344 /// #
1345 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1346 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1347 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1348 /// # YmAFv/UfO0vYBw==
1349 /// # =+l94
1350 /// # -----END PGP MESSAGE-----
1351 /// # "[..]);
1352 ///
1353 /// fn consume(r: &mut dyn Read) -> Result<()> {
1354 /// // ...
1355 /// # let _ = r; Ok(())
1356 /// }
1357 ///
1358 /// let h = Helper {};
1359 /// let mut v = VerifierBuilder::from_reader(&mut source)?
1360 /// .with_policy(p, None, h)?;
1361 ///
1362 /// if v.message_processed() {
1363 /// // The data has been authenticated.
1364 /// consume(&mut v)?;
1365 /// } else {
1366 /// let mut tmp = tempfile::tempfile()?;
1367 /// std::io::copy(&mut v, &mut tmp)?;
1368 ///
1369 /// // If the copy succeeds, the message has been fully
1370 /// // processed and the data has been authenticated.
1371 /// assert!(v.message_processed());
1372 ///
1373 /// // Rewind and consume.
1374 /// tmp.seek(SeekFrom::Start(0))?;
1375 /// consume(&mut tmp)?;
1376 /// }
1377 /// # Ok(()) }
1378 /// ```
1379 pub fn message_processed(&self) -> bool {
1380 self.decryptor.message_processed()
1381 }
1382}
1383
1384impl<'a, H: VerificationHelper> io::Read for Verifier<'a, H> {
1385 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
1386 self.decryptor.read(buf)
1387 }
1388}
1389
1390
1391/// Verifies a detached signature.
1392///
1393/// To create a `DetachedVerifier`, create a
1394/// [`DetachedVerifierBuilder`] using [`Parse`], and customize it to
1395/// your needs.
1396///
1397/// [`Parse`]: super::Parse
1398///
1399/// See [`GoodChecksum`] for what it means for a signature to be
1400/// considered valid. When the signature(s) are processed,
1401/// [`VerificationHelper::check`] will be called with a
1402/// [`MessageStructure`] containing exactly one layer, a signature
1403/// group.
1404///
1405///
1406/// # Examples
1407///
1408/// ```
1409/// # fn main() -> sequoia_openpgp::Result<()> {
1410/// use std::io::{self, Read};
1411/// use sequoia_openpgp as openpgp;
1412/// use openpgp::{KeyHandle, Cert, Result};
1413/// use openpgp::parse::{Parse, stream::*};
1414/// use sequoia_openpgp::policy::StandardPolicy;
1415///
1416/// let p = &StandardPolicy::new();
1417///
1418/// // This fetches keys and computes the validity of the verification.
1419/// struct Helper {}
1420/// impl VerificationHelper for Helper {
1421/// fn get_certs(&mut self, _ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1422/// Ok(Vec::new()) // Feed the Certs to the verifier here...
1423/// }
1424/// fn check(&mut self, structure: MessageStructure) -> Result<()> {
1425/// Ok(()) // Implement your verification policy here.
1426/// }
1427/// }
1428///
1429/// let signature =
1430/// b"-----BEGIN PGP SIGNATURE-----
1431///
1432/// wnUEABYKACcFglt+z/EWoQSOjDP6RiYzeXbZeXgGnAw0jdgsGQmQBpwMNI3YLBkA
1433/// AHmUAP9mpj2wV0/ekDuzxZrPQ0bnobFVaxZGg7YzdlksSOERrwEA6v6czXQjKcv2
1434/// KOwGTamb+ajTLQ3YRG9lh+ZYIXynvwE=
1435/// =IJ29
1436/// -----END PGP SIGNATURE-----";
1437///
1438/// let data = b"Hello World!";
1439/// let h = Helper {};
1440/// let mut v = DetachedVerifierBuilder::from_bytes(&signature[..])?
1441/// .with_policy(p, None, h)?;
1442/// v.verify_bytes(data)?;
1443/// # Ok(()) }
1444pub struct DetachedVerifier<'a, H: VerificationHelper> {
1445 decryptor: Decryptor<'a, NoDecryptionHelper<H>>,
1446}
1447assert_send_and_sync!(DetachedVerifier<'_, H> where H: VerificationHelper);
1448
1449/// A builder for `DetachedVerifier`.
1450///
1451/// This allows the customization of [`DetachedVerifier`], which can
1452/// be built using [`DetachedVerifierBuilder::with_policy`].
1453///
1454/// [`DetachedVerifierBuilder::with_policy`]: DetachedVerifierBuilder::with_policy()
1455pub struct DetachedVerifierBuilder<'a> {
1456 signatures: Box<dyn BufferedReader<Cookie> + 'a>,
1457 mapping: bool,
1458}
1459assert_send_and_sync!(DetachedVerifierBuilder<'_>);
1460
1461impl<'a> Parse<'a, DetachedVerifierBuilder<'a>>
1462 for DetachedVerifierBuilder<'a>
1463{
1464 fn from_buffered_reader<R>(reader: R) -> Result<DetachedVerifierBuilder<'a>>
1465 where
1466 R: BufferedReader<Cookie> + 'a,
1467 {
1468 DetachedVerifierBuilder::new(reader)
1469 }
1470}
1471
1472impl<'a> crate::seal::Sealed for DetachedVerifierBuilder<'a> {}
1473
1474impl<'a> DetachedVerifierBuilder<'a> {
1475 fn new<B>(signatures: B) -> Result<Self>
1476 where B: buffered_reader::BufferedReader<Cookie> + 'a
1477 {
1478 Ok(DetachedVerifierBuilder {
1479 signatures: Box::new(signatures),
1480 mapping: false,
1481 })
1482 }
1483
1484 /// Enables mapping.
1485 ///
1486 /// If mapping is enabled, the packet parser will create a [`Map`]
1487 /// of the packets that can be inspected in
1488 /// [`VerificationHelper::inspect`]. Note that this buffers the
1489 /// packets contents, and is not recommended unless you know that
1490 /// the packets are small.
1491 ///
1492 /// [`Map`]: super::map::Map
1493 ///
1494 /// # Examples
1495 ///
1496 /// ```
1497 /// # fn main() -> sequoia_openpgp::Result<()> {
1498 /// use sequoia_openpgp as openpgp;
1499 /// # use openpgp::{KeyHandle, Cert, Result};
1500 /// use openpgp::parse::{Parse, stream::*};
1501 /// use openpgp::policy::StandardPolicy;
1502 ///
1503 /// let p = &StandardPolicy::new();
1504 ///
1505 /// struct Helper {}
1506 /// impl VerificationHelper for Helper {
1507 /// // ...
1508 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1509 /// # Ok(Vec::new())
1510 /// # }
1511 /// #
1512 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1513 /// # Ok(())
1514 /// # }
1515 /// }
1516 ///
1517 /// let signature =
1518 /// // ...
1519 /// # b"-----BEGIN PGP SIGNATURE-----
1520 /// #
1521 /// # wnUEABYKACcFglt+z/EWoQSOjDP6RiYzeXbZeXgGnAw0jdgsGQmQBpwMNI3YLBkA
1522 /// # AHmUAP9mpj2wV0/ekDuzxZrPQ0bnobFVaxZGg7YzdlksSOERrwEA6v6czXQjKcv2
1523 /// # KOwGTamb+ajTLQ3YRG9lh+ZYIXynvwE=
1524 /// # =IJ29
1525 /// # -----END PGP SIGNATURE-----";
1526 ///
1527 /// let h = Helper {};
1528 /// let mut v = DetachedVerifierBuilder::from_bytes(&signature[..])?
1529 /// .mapping(true)
1530 /// .with_policy(p, None, h)?;
1531 /// # let _ = v;
1532 /// # Ok(()) }
1533 /// ```
1534 pub fn mapping(mut self, enabled: bool) -> Self {
1535 self.mapping = enabled;
1536 self
1537 }
1538
1539 /// Creates the `DetachedVerifier`.
1540 ///
1541 /// Signature verifications are done under the given `policy` and
1542 /// relative to time `time`, or the current time, if `time` is
1543 /// `None`. `helper` is the [`VerificationHelper`] to use.
1544 /// [`VerificationHelper::check`] will be called with a
1545 /// [`MessageStructure`] containing exactly one layer, a signature
1546 /// group.
1547 ///
1548 ///
1549 /// # Examples
1550 ///
1551 /// ```
1552 /// # fn main() -> sequoia_openpgp::Result<()> {
1553 /// use sequoia_openpgp as openpgp;
1554 /// # use openpgp::{KeyHandle, Cert, Result};
1555 /// use openpgp::parse::{Parse, stream::*};
1556 /// use openpgp::policy::StandardPolicy;
1557 ///
1558 /// let p = &StandardPolicy::new();
1559 ///
1560 /// struct Helper {}
1561 /// impl VerificationHelper for Helper {
1562 /// // ...
1563 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1564 /// # Ok(Vec::new())
1565 /// # }
1566 /// #
1567 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1568 /// # Ok(())
1569 /// # }
1570 /// }
1571 ///
1572 /// let signature =
1573 /// // ...
1574 /// # b"-----BEGIN PGP SIGNATURE-----
1575 /// #
1576 /// # wnUEABYKACcFglt+z/EWoQSOjDP6RiYzeXbZeXgGnAw0jdgsGQmQBpwMNI3YLBkA
1577 /// # AHmUAP9mpj2wV0/ekDuzxZrPQ0bnobFVaxZGg7YzdlksSOERrwEA6v6czXQjKcv2
1578 /// # KOwGTamb+ajTLQ3YRG9lh+ZYIXynvwE=
1579 /// # =IJ29
1580 /// # -----END PGP SIGNATURE-----";
1581 ///
1582 /// let h = Helper {};
1583 /// let mut v = DetachedVerifierBuilder::from_bytes(&signature[..])?
1584 /// // Customize the `DetachedVerifier` here.
1585 /// .with_policy(p, None, h)?;
1586 /// # let _ = v;
1587 /// # Ok(()) }
1588 /// ```
1589 pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
1590 -> Result<DetachedVerifier<'a, H>>
1591 where H: VerificationHelper,
1592 T: Into<Option<time::SystemTime>>,
1593 {
1594 // Do not eagerly map `t` to the current time.
1595 let t = time.into();
1596 Ok(DetachedVerifier {
1597 decryptor: Decryptor::from_cookie_reader(
1598 policy,
1599 self.signatures,
1600 NoDecryptionHelper { v: helper, },
1601 t, Mode::VerifyDetached, 0, self.mapping, false)?,
1602 })
1603 }
1604}
1605
1606impl<'a, H: VerificationHelper> DetachedVerifier<'a, H> {
1607 /// Verifies the given data.
1608 pub fn verify_buffered_reader<R>(&mut self, reader: R)
1609 -> Result<()>
1610 where
1611 R: BufferedReader<Cookie>,
1612 {
1613 self.decryptor.verify_detached(reader.into_boxed())
1614 }
1615
1616 /// Verifies the given data.
1617 pub fn verify_reader<R: io::Read + Send + Sync>(&mut self, reader: R) -> Result<()> {
1618 self.verify_buffered_reader(buffered_reader::Generic::with_cookie(
1619 reader, None, Default::default()))
1620 }
1621
1622 /// Verifies the given data.
1623 pub fn verify_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
1624 self.verify_buffered_reader(buffered_reader::File::with_cookie(
1625 path, Default::default())?)
1626 }
1627
1628 /// Verifies the given data.
1629 pub fn verify_bytes<B: AsRef<[u8]>>(&mut self, buf: B) -> Result<()> {
1630 self.verify_buffered_reader(buffered_reader::Memory::with_cookie(
1631 buf.as_ref(), Default::default()))
1632 }
1633
1634 /// Returns a reference to the helper.
1635 pub fn helper_ref(&self) -> &H {
1636 &self.decryptor.helper_ref().v
1637 }
1638
1639 /// Returns a mutable reference to the helper.
1640 pub fn helper_mut(&mut self) -> &mut H {
1641 &mut self.decryptor.helper_mut().v
1642 }
1643
1644 /// Recovers the helper.
1645 pub fn into_helper(self) -> H {
1646 self.decryptor.into_helper().v
1647 }
1648}
1649
1650
1651/// Modes of operation for the Decryptor.
1652#[derive(Debug, PartialEq, Eq)]
1653enum Mode {
1654 Decrypt,
1655 Verify,
1656 VerifyDetached,
1657}
1658
1659/// Decrypts and verifies an encrypted and optionally signed OpenPGP
1660/// message.
1661///
1662/// To create a `Decryptor`, create a [`DecryptorBuilder`] using
1663/// [`Parse`], and customize it to your needs.
1664///
1665/// [`Parse`]: super::Parse
1666///
1667/// Signature verification and detection of ciphertext tampering
1668/// requires processing the whole message first. Therefore, OpenPGP
1669/// implementations supporting streaming operations necessarily must
1670/// output unverified data. This has been a source of problems in the
1671/// past. To alleviate this, we buffer the message first (up to 25
1672/// megabytes of net message data by default, see
1673/// [`DEFAULT_BUFFER_SIZE`]), and verify the signatures if the message
1674/// fits into our buffer. Nevertheless it is important to treat the
1675/// data as unverified and untrustworthy until you have seen a
1676/// positive verification. See [`Decryptor::message_processed`] for
1677/// more information.
1678///
1679/// [`Decryptor::message_processed`]: Decryptor::message_processed()
1680///
1681/// See [`GoodChecksum`] for what it means for a signature to be
1682/// considered valid.
1683///
1684///
1685/// # Examples
1686///
1687/// ```
1688/// # fn main() -> sequoia_openpgp::Result<()> {
1689/// use std::io::Read;
1690/// use sequoia_openpgp as openpgp;
1691/// use openpgp::crypto::SessionKey;
1692/// use openpgp::types::SymmetricAlgorithm;
1693/// use openpgp::{KeyID, Cert, Result, packet::{Key, PKESK, SKESK}};
1694/// use openpgp::parse::{Parse, stream::*};
1695/// use sequoia_openpgp::policy::StandardPolicy;
1696///
1697/// let p = &StandardPolicy::new();
1698///
1699/// // This fetches keys and computes the validity of the verification.
1700/// struct Helper {}
1701/// impl VerificationHelper for Helper {
1702/// fn get_certs(&mut self, _ids: &[openpgp::KeyHandle]) -> Result<Vec<Cert>> {
1703/// Ok(Vec::new()) // Feed the Certs to the verifier here...
1704/// }
1705/// fn check(&mut self, structure: MessageStructure) -> Result<()> {
1706/// Ok(()) // Implement your verification policy here.
1707/// }
1708/// }
1709/// impl DecryptionHelper for Helper {
1710/// fn decrypt(&mut self, _: &[PKESK], skesks: &[SKESK],
1711/// _sym_algo: Option<SymmetricAlgorithm>,
1712/// decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
1713/// -> Result<Option<Cert>>
1714/// {
1715/// skesks[0].decrypt(&"streng geheim".into())
1716/// .map(|(algo, session_key)| decrypt(algo, &session_key));
1717/// Ok(None)
1718/// }
1719/// }
1720///
1721/// let message =
1722/// b"-----BEGIN PGP MESSAGE-----
1723///
1724/// wy4ECQMIY5Zs8RerVcXp85UgoUKjKkevNPX3WfcS5eb7rkT9I6kw6N2eEc5PJUDh
1725/// 0j0B9mnPKeIwhp2kBHpLX/en6RfNqYauX9eSeia7aqsd/AOLbO9WMCLZS5d2LTxN
1726/// rwwb8Aggyukj13Mi0FF5
1727/// =OB/8
1728/// -----END PGP MESSAGE-----";
1729///
1730/// let h = Helper {};
1731/// let mut v = DecryptorBuilder::from_bytes(&message[..])?
1732/// .with_policy(p, None, h)?;
1733///
1734/// let mut content = Vec::new();
1735/// v.read_to_end(&mut content)?;
1736/// assert_eq!(content, b"Hello World!");
1737/// # Ok(()) }
1738pub struct Decryptor<'a, H: VerificationHelper + DecryptionHelper> {
1739 helper: H,
1740
1741 /// The issuers collected from OPS and Signature packets.
1742 issuers: Vec<KeyHandle>,
1743
1744 /// The certificates used for signature verification.
1745 certs: Vec<Cert>,
1746
1747 oppr: Option<PacketParserResult<'a>>,
1748 identity: Option<Fingerprint>,
1749 structure: IMessageStructure,
1750
1751 /// We want to hold back some data until the signatures checked
1752 /// out. We buffer this here, cursor is the offset of unread
1753 /// bytes in the buffer.
1754 buffer_size: usize,
1755 reserve: Option<Vec<u8>>,
1756 cursor: usize,
1757
1758 /// The mode of operation.
1759 mode: Mode,
1760
1761 /// Whether we are actually processing a cleartext signature
1762 /// framework message. If so, we need to tweak our behavior a
1763 /// bit.
1764 processing_csf_message: Option<bool>,
1765
1766 /// Signature verification relative to this time.
1767 ///
1768 /// This is needed for checking the signature's liveness.
1769 ///
1770 /// We want the same semantics as `Subpacket::signature_alive`.
1771 /// Specifically, when using the current time, we want to tolerate
1772 /// some clock skew, but when using some specific time, we don't.
1773 /// (See `Subpacket::signature_alive` for an explanation.)
1774 ///
1775 /// These semantics can be realized by making `time` an
1776 /// `Option<time::SystemTime>` and passing that as is to
1777 /// `Subpacket::signature_alive`. But that approach has two new
1778 /// problems. First, if we are told to use the current time, then
1779 /// we want to use the time at which the Verifier was
1780 /// instantiated, not the time at which we call
1781 /// `Subpacket::signature_alive`. Second, if we call
1782 /// `Subpacket::signature_alive` multiple times, they should all
1783 /// use the same time. To work around these issues, when a
1784 /// Verifier is instantiated, we evaluate `time` and we record how
1785 /// much we want to tolerate clock skew in the same way as
1786 /// `Subpacket::signature_alive`.
1787 time: time::SystemTime,
1788 clock_skew_tolerance: time::Duration,
1789
1790 policy: &'a dyn Policy,
1791}
1792assert_send_and_sync!(Decryptor<'_, H>
1793 where H: VerificationHelper + DecryptionHelper);
1794
1795/// A builder for `Decryptor`.
1796///
1797/// This allows the customization of [`Decryptor`], which can
1798/// be built using [`DecryptorBuilder::with_policy`].
1799///
1800/// [`DecryptorBuilder::with_policy`]: DecryptorBuilder::with_policy()
1801pub struct DecryptorBuilder<'a> {
1802 message: Box<dyn BufferedReader<Cookie> + 'a>,
1803 buffer_size: usize,
1804 mapping: bool,
1805}
1806assert_send_and_sync!(DecryptorBuilder<'_>);
1807
1808impl<'a> Parse<'a, DecryptorBuilder<'a>>
1809 for DecryptorBuilder<'a>
1810{
1811 fn from_buffered_reader<R>(reader: R) -> Result<DecryptorBuilder<'a>>
1812 where
1813 R: BufferedReader<Cookie> + 'a,
1814 {
1815 DecryptorBuilder::new(reader)
1816 }
1817}
1818
1819impl<'a> crate::seal::Sealed for DecryptorBuilder<'a> {}
1820
1821impl<'a> DecryptorBuilder<'a> {
1822 fn new<B>(signatures: B) -> Result<Self>
1823 where B: buffered_reader::BufferedReader<Cookie> + 'a
1824 {
1825 Ok(DecryptorBuilder {
1826 message: Box::new(signatures),
1827 buffer_size: DEFAULT_BUFFER_SIZE,
1828 mapping: false,
1829 })
1830 }
1831
1832 /// Changes the amount of buffered data.
1833 ///
1834 /// By default, we buffer up to 25 megabytes of net message data
1835 /// (see [`DEFAULT_BUFFER_SIZE`]). This changes the default.
1836 ///
1837 ///
1838 /// # Examples
1839 ///
1840 /// ```
1841 /// # fn main() -> sequoia_openpgp::Result<()> {
1842 /// use sequoia_openpgp as openpgp;
1843 /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
1844 /// use openpgp::parse::{Parse, stream::*};
1845 /// use openpgp::policy::StandardPolicy;
1846 ///
1847 /// let p = &StandardPolicy::new();
1848 ///
1849 /// struct Helper {}
1850 /// impl VerificationHelper for Helper {
1851 /// // ...
1852 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1853 /// # Ok(Vec::new())
1854 /// # }
1855 /// #
1856 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1857 /// # Ok(())
1858 /// # }
1859 /// }
1860 /// impl DecryptionHelper for Helper {
1861 /// // ...
1862 /// # fn decrypt(&mut self, _: &[PKESK], skesks: &[SKESK],
1863 /// # _sym_algo: Option<SymmetricAlgorithm>,
1864 /// # decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
1865 /// # -> Result<Option<Cert>>
1866 /// # {
1867 /// # Ok(None)
1868 /// # }
1869 /// }
1870 ///
1871 /// let message =
1872 /// // ...
1873 /// # &b"-----BEGIN PGP MESSAGE-----
1874 /// #
1875 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1876 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1877 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1878 /// # YmAFv/UfO0vYBw==
1879 /// # =+l94
1880 /// # -----END PGP MESSAGE-----
1881 /// # "[..];
1882 ///
1883 /// let h = Helper {};
1884 /// let mut v = DecryptorBuilder::from_bytes(message)?
1885 /// .buffer_size(1 << 12)
1886 /// .with_policy(p, None, h)?;
1887 /// # let _ = v;
1888 /// # Ok(()) }
1889 /// ```
1890 pub fn buffer_size(mut self, size: usize) -> Self {
1891 self.buffer_size = size;
1892 self
1893 }
1894
1895 /// Enables mapping.
1896 ///
1897 /// If mapping is enabled, the packet parser will create a [`Map`]
1898 /// of the packets that can be inspected in
1899 /// [`VerificationHelper::inspect`]. Note that this buffers the
1900 /// packets contents, and is not recommended unless you know that
1901 /// the packets are small.
1902 ///
1903 /// [`Map`]: super::map::Map
1904 ///
1905 /// # Examples
1906 ///
1907 /// ```
1908 /// # fn main() -> sequoia_openpgp::Result<()> {
1909 /// use sequoia_openpgp as openpgp;
1910 /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
1911 /// use openpgp::parse::{Parse, stream::*};
1912 /// use openpgp::policy::StandardPolicy;
1913 ///
1914 /// let p = &StandardPolicy::new();
1915 ///
1916 /// struct Helper {}
1917 /// impl VerificationHelper for Helper {
1918 /// // ...
1919 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1920 /// # Ok(Vec::new())
1921 /// # }
1922 /// #
1923 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1924 /// # Ok(())
1925 /// # }
1926 /// }
1927 /// impl DecryptionHelper for Helper {
1928 /// // ...
1929 /// # fn decrypt(&mut self, _: &[PKESK], skesks: &[SKESK],
1930 /// # _sym_algo: Option<SymmetricAlgorithm>,
1931 /// # decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
1932 /// # -> Result<Option<Cert>>
1933 /// # {
1934 /// # Ok(None)
1935 /// # }
1936 /// }
1937 ///
1938 /// let message =
1939 /// // ...
1940 /// # &b"-----BEGIN PGP MESSAGE-----
1941 /// #
1942 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
1943 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
1944 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
1945 /// # YmAFv/UfO0vYBw==
1946 /// # =+l94
1947 /// # -----END PGP MESSAGE-----
1948 /// # "[..];
1949 ///
1950 /// let h = Helper {};
1951 /// let mut v = DecryptorBuilder::from_bytes(message)?
1952 /// .mapping(true)
1953 /// .with_policy(p, None, h)?;
1954 /// # let _ = v;
1955 /// # Ok(()) }
1956 /// ```
1957 pub fn mapping(mut self, enabled: bool) -> Self {
1958 self.mapping = enabled;
1959 self
1960 }
1961
1962 /// Creates the `Decryptor`.
1963 ///
1964 /// Signature verifications are done under the given `policy` and
1965 /// relative to time `time`, or the current time, if `time` is
1966 /// `None`. `helper` is the [`VerificationHelper`] and
1967 /// [`DecryptionHelper`] to use.
1968 ///
1969 ///
1970 /// # Examples
1971 ///
1972 /// ```
1973 /// # fn main() -> sequoia_openpgp::Result<()> {
1974 /// use sequoia_openpgp as openpgp;
1975 /// # use openpgp::{*, crypto::*, packet::prelude::*, types::*};
1976 /// use openpgp::parse::{Parse, stream::*};
1977 /// use openpgp::policy::StandardPolicy;
1978 ///
1979 /// let p = &StandardPolicy::new();
1980 ///
1981 /// struct Helper {}
1982 /// impl VerificationHelper for Helper {
1983 /// // ...
1984 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
1985 /// # Ok(Vec::new())
1986 /// # }
1987 /// #
1988 /// # fn check(&mut self, structure: MessageStructure) -> Result<()> {
1989 /// # Ok(())
1990 /// # }
1991 /// }
1992 /// impl DecryptionHelper for Helper {
1993 /// // ...
1994 /// # fn decrypt(&mut self, _: &[PKESK], skesks: &[SKESK],
1995 /// # _sym_algo: Option<SymmetricAlgorithm>,
1996 /// # decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
1997 /// # -> Result<Option<Cert>>
1998 /// # {
1999 /// # Ok(None)
2000 /// # }
2001 /// }
2002 ///
2003 /// let message =
2004 /// // ...
2005 /// # &b"-----BEGIN PGP MESSAGE-----
2006 /// #
2007 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
2008 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
2009 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
2010 /// # YmAFv/UfO0vYBw==
2011 /// # =+l94
2012 /// # -----END PGP MESSAGE-----
2013 /// # "[..];
2014 ///
2015 /// let h = Helper {};
2016 /// let mut v = DecryptorBuilder::from_bytes(message)?
2017 /// // Customize the `Decryptor` here.
2018 /// .with_policy(p, None, h)?;
2019 /// # let _ = v;
2020 /// # Ok(()) }
2021 /// ```
2022 pub fn with_policy<T, H>(self, policy: &'a dyn Policy, time: T, helper: H)
2023 -> Result<Decryptor<'a, H>>
2024 where H: VerificationHelper + DecryptionHelper,
2025 T: Into<Option<time::SystemTime>>,
2026 {
2027 // Do not eagerly map `t` to the current time.
2028 let t = time.into();
2029 Decryptor::from_cookie_reader(
2030 policy,
2031 self.message,
2032 helper,
2033 t, Mode::Decrypt, self.buffer_size, self.mapping, false)
2034 }
2035}
2036
2037/// Helper for decrypting messages.
2038///
2039/// This trait abstracts over session key decryption. It allows us to
2040/// provide the [`Decryptor`] without imposing any policy on how the
2041/// session key is decrypted.
2042///
2043pub trait DecryptionHelper {
2044 /// Decrypts the message.
2045 ///
2046 /// This function is called with every [`PKESK`] and [`SKESK`]
2047 /// packet found in the message. The implementation must decrypt
2048 /// the symmetric algorithm and session key from one of the
2049 /// [`PKESK`] packets, the [`SKESK`] packets, or retrieve it from
2050 /// a cache, and then call `decrypt` with the symmetric algorithm
2051 /// and session key. `decrypt` returns `true` if the decryption
2052 /// was successful.
2053 ///
2054 /// [`PKESK`]: crate::packet::PKESK
2055 /// [`SKESK`]: crate::packet::SKESK
2056 ///
2057 /// If a symmetric algorithm is given, it should be passed on to
2058 /// [`PKESK::decrypt`].
2059 ///
2060 /// [`PKESK::decrypt`]: crate::packet::PKESK#method.decrypt
2061 ///
2062 /// If the message is decrypted using a [`PKESK`] packet, then the
2063 /// fingerprint of the certificate containing the encryption
2064 /// subkey should be returned. This is used in conjunction with
2065 /// the intended recipient subpacket (see [Intended Recipient
2066 /// Fingerprint]) to prevent [*Surreptitious Forwarding*].
2067 ///
2068 /// [Intended Recipient Fingerprint]: https://www.rfc-editor.org/rfc/rfc9580.html#name-intended-recipient-fingerpr
2069 /// [*Surreptitious Forwarding*]: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
2070 ///
2071 /// This method will be called once per encryption layer.
2072 ///
2073 /// # Examples
2074 ///
2075 /// This example demonstrates how to decrypt a message using local
2076 /// keys (i.e. excluding remote keys like smart cards) while
2077 /// maximizing convenience for the user.
2078 ///
2079 /// ```
2080 /// use sequoia_openpgp as openpgp;
2081 /// use openpgp::{Cert, Fingerprint, KeyHandle, KeyID, Result};
2082 /// use openpgp::crypto::SessionKey;
2083 /// use openpgp::types::SymmetricAlgorithm;
2084 /// use openpgp::packet::{PKESK, SKESK};
2085 /// # use openpgp::packet::{Key, key::*};
2086 /// use openpgp::parse::stream::*;
2087 /// # fn lookup_cache(_: &[PKESK], _: &[SKESK])
2088 /// # -> Option<(Option<Cert>, Option<SymmetricAlgorithm>, SessionKey)> {
2089 /// # unimplemented!()
2090 /// # }
2091 /// # fn lookup_key(_: Option<KeyHandle>)
2092 /// # -> Option<(Cert, Key<SecretParts, UnspecifiedRole>)> {
2093 /// # unimplemented!()
2094 /// # }
2095 /// # fn all_keys() -> impl Iterator<Item = (Cert, Key<SecretParts, UnspecifiedRole>)> {
2096 /// # Vec::new().into_iter()
2097 /// # }
2098 ///
2099 /// struct Helper { /* ... */ }
2100 /// impl DecryptionHelper for Helper {
2101 /// fn decrypt(&mut self, pkesks: &[PKESK], skesks: &[SKESK],
2102 /// sym_algo: Option<SymmetricAlgorithm>,
2103 /// decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
2104 /// -> Result<Option<Cert>>
2105 /// {
2106 /// // Try to decrypt, from the most convenient method to the
2107 /// // least convenient one.
2108 ///
2109 /// // First, see if it is in the cache.
2110 /// if let Some((cert, algo, sk)) = lookup_cache(pkesks, skesks) {
2111 /// if decrypt(algo, &sk) {
2112 /// return Ok(cert);
2113 /// }
2114 /// }
2115 ///
2116 /// // Second, we try those keys that we can use without
2117 /// // prompting for a password.
2118 /// for pkesk in pkesks {
2119 /// if let Some((cert, key)) = lookup_key(pkesk.recipient()) {
2120 /// if ! key.secret().is_encrypted() {
2121 /// let mut keypair = key.clone().into_keypair()?;
2122 /// if pkesk.decrypt(&mut keypair, sym_algo)
2123 /// .map(|(algo, sk)| decrypt(algo, &sk))
2124 /// .unwrap_or(false)
2125 /// {
2126 /// return Ok(Some(cert));
2127 /// }
2128 /// }
2129 /// }
2130 /// }
2131 ///
2132 /// // Third, we try to decrypt PKESK packets with
2133 /// // wildcard recipients using those keys that we can
2134 /// // use without prompting for a password.
2135 /// for pkesk in pkesks.iter().filter(
2136 /// |p| p.recipient().is_none())
2137 /// {
2138 /// for (cert, key) in all_keys() {
2139 /// if ! key.secret().is_encrypted() {
2140 /// let mut keypair = key.clone().into_keypair()?;
2141 /// if pkesk.decrypt(&mut keypair, sym_algo)
2142 /// .map(|(algo, sk)| decrypt(algo, &sk))
2143 /// .unwrap_or(false)
2144 /// {
2145 /// return Ok(Some(cert));
2146 /// }
2147 /// }
2148 /// }
2149 /// }
2150 ///
2151 /// // Fourth, we try to decrypt all PKESK packets that we
2152 /// // need encrypted keys for.
2153 /// // [...]
2154 ///
2155 /// // Fifth, we try to decrypt all PKESK packets with
2156 /// // wildcard recipients using encrypted keys.
2157 /// // [...]
2158 ///
2159 /// // At this point, we have exhausted our options at
2160 /// // decrypting the PKESK packets.
2161 /// if skesks.is_empty() {
2162 /// return
2163 /// Err(anyhow::anyhow!("No key to decrypt message"));
2164 /// }
2165 ///
2166 /// // Finally, try to decrypt using the SKESKs.
2167 /// loop {
2168 /// let password = // Prompt for a password.
2169 /// # "".into();
2170 ///
2171 /// for skesk in skesks {
2172 /// if skesk.decrypt(&password)
2173 /// .map(|(algo, sk)| decrypt(algo, &sk))
2174 /// .unwrap_or(false)
2175 /// {
2176 /// return Ok(None);
2177 /// }
2178 /// }
2179 ///
2180 /// eprintln!("Bad password.");
2181 /// }
2182 /// }
2183 /// }
2184 /// ```
2185 fn decrypt(&mut self, pkesks: &[PKESK], skesks: &[SKESK],
2186 sym_algo: Option<SymmetricAlgorithm>,
2187 decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
2188 -> Result<Option<Cert>>;
2189}
2190
2191impl<'a, H: VerificationHelper + DecryptionHelper> Decryptor<'a, H> {
2192 /// Returns a reference to the helper.
2193 pub fn helper_ref(&self) -> &H {
2194 &self.helper
2195 }
2196
2197 /// Returns a mutable reference to the helper.
2198 pub fn helper_mut(&mut self) -> &mut H {
2199 &mut self.helper
2200 }
2201
2202 /// Recovers the helper.
2203 pub fn into_helper(self) -> H {
2204 self.helper
2205 }
2206
2207 /// Returns true if the whole message has been processed and
2208 /// authenticated.
2209 ///
2210 /// If the function returns `true`, the whole message has been
2211 /// processed, the signatures are verified, and the message
2212 /// structure has been passed to [`VerificationHelper::check`].
2213 /// Data read from this `Verifier` using [`io::Read`] has been
2214 /// authenticated.
2215 ///
2216 /// [`io::Read`]: std::io::Read
2217 ///
2218 /// If the function returns `false`, the message did not fit into
2219 /// the internal buffer, and therefore data read from this
2220 /// `Verifier` using [`io::Read`] has **not yet been
2221 /// authenticated**. It is important to treat this data as
2222 /// attacker controlled and not use it until it has been
2223 /// authenticated.
2224 ///
2225 /// # Examples
2226 ///
2227 /// This example demonstrates how to verify a message in a
2228 /// streaming fashion, writing the data to a temporary file and
2229 /// only commit the result once the data is authenticated.
2230 ///
2231 /// ```
2232 /// # fn main() -> sequoia_openpgp::Result<()> {
2233 /// use std::io::{Read, Seek, SeekFrom};
2234 /// use sequoia_openpgp as openpgp;
2235 /// use openpgp::{KeyHandle, Cert, Result};
2236 /// use openpgp::parse::{Parse, stream::*};
2237 /// use openpgp::policy::StandardPolicy;
2238 /// #
2239 /// # // Mock of `tempfile::tempfile`.
2240 /// # mod tempfile {
2241 /// # pub fn tempfile() -> sequoia_openpgp::Result<std::fs::File> {
2242 /// # unimplemented!()
2243 /// # }
2244 /// # }
2245 ///
2246 /// let p = &StandardPolicy::new();
2247 ///
2248 /// // This fetches keys and computes the validity of the verification.
2249 /// struct Helper {}
2250 /// impl VerificationHelper for Helper {
2251 /// // ...
2252 /// # fn get_certs(&mut self, ids: &[KeyHandle]) -> Result<Vec<Cert>> {
2253 /// # Ok(Vec::new())
2254 /// # }
2255 /// # fn check(&mut self, _: MessageStructure) -> Result<()> {
2256 /// # Ok(())
2257 /// # }
2258 /// }
2259 ///
2260 /// let mut source =
2261 /// // ...
2262 /// # std::io::Cursor::new(&b"-----BEGIN PGP MESSAGE-----
2263 /// #
2264 /// # xA0DAAoW+zdR8Vh9rvEByxJiAAAAAABIZWxsbyBXb3JsZCHCdQQAFgoABgWCXrLl
2265 /// # AQAhCRD7N1HxWH2u8RYhBDnRAKtn1b2MBAECBfs3UfFYfa7xRUsBAJaxkU/RCstf
2266 /// # UD7TM30IorO1Mb9cDa/hPRxyzipulT55AQDN1m9LMqi9yJDjHNHwYYVwxDcg+pLY
2267 /// # YmAFv/UfO0vYBw==
2268 /// # =+l94
2269 /// # -----END PGP MESSAGE-----
2270 /// # "[..]);
2271 ///
2272 /// fn consume(r: &mut dyn Read) -> Result<()> {
2273 /// // ...
2274 /// # let _ = r; Ok(())
2275 /// }
2276 ///
2277 /// let h = Helper {};
2278 /// let mut v = VerifierBuilder::from_reader(&mut source)?
2279 /// .with_policy(p, None, h)?;
2280 ///
2281 /// if v.message_processed() {
2282 /// // The data has been authenticated.
2283 /// consume(&mut v)?;
2284 /// } else {
2285 /// let mut tmp = tempfile::tempfile()?;
2286 /// std::io::copy(&mut v, &mut tmp)?;
2287 ///
2288 /// // If the copy succeeds, the message has been fully
2289 /// // processed and the data has been authenticated.
2290 /// assert!(v.message_processed());
2291 ///
2292 /// // Rewind and consume.
2293 /// tmp.seek(SeekFrom::Start(0))?;
2294 /// consume(&mut tmp)?;
2295 /// }
2296 /// # Ok(()) }
2297 /// ```
2298 pub fn message_processed(&self) -> bool {
2299 // oppr is only None after we've processed the packet sequence.
2300 self.oppr.is_none()
2301 }
2302
2303 /// Creates the `Decryptor`, and buffers the data up to `buffer_size`.
2304 fn from_cookie_reader<T>(
2305 policy: &'a dyn Policy,
2306 bio: Box<dyn BufferedReader<Cookie> + 'a>,
2307 helper: H, time: T,
2308 mode: Mode,
2309 buffer_size: usize,
2310 mapping: bool,
2311 csf_transformation: bool,
2312 )
2313 -> Result<Decryptor<'a, H>>
2314 where T: Into<Option<time::SystemTime>>
2315 {
2316 tracer!(TRACE, "Decryptor::from_cookie_reader", TRACE_INDENT);
2317
2318 let time = time.into();
2319 let tolerance = time
2320 .map(|_| time::Duration::new(0, 0))
2321 .unwrap_or(
2322 crate::packet::signature::subpacket::CLOCK_SKEW_TOLERANCE);
2323 let time = time.unwrap_or_else(crate::now);
2324
2325 let mut ppr = PacketParserBuilder::from_cookie_reader(bio)?
2326 .map(mapping)
2327 .csf_transformation(csf_transformation)
2328 .build()?;
2329
2330 let mut v = Decryptor {
2331 helper,
2332 issuers: Vec::new(),
2333 certs: Vec::new(),
2334 oppr: None,
2335 identity: None,
2336 structure: IMessageStructure::new(),
2337 buffer_size,
2338 reserve: None,
2339 cursor: 0,
2340 mode,
2341 time,
2342 clock_skew_tolerance: tolerance,
2343 policy,
2344 processing_csf_message: None, // We don't know yet.
2345 };
2346
2347 let mut pkesks: Vec<packet::PKESK> = Vec::new();
2348 let mut skesks: Vec<packet::SKESK> = Vec::new();
2349
2350 while let PacketParserResult::Some(mut pp) = ppr {
2351 match &pp.packet {
2352 Packet::PKESK(p) =>
2353 t!("Found a {:?}v{} at depth {}",
2354 pp.packet.tag(), p.version(),
2355 pp.recursion_depth()),
2356 Packet::SKESK(p) =>
2357 t!("Found a {:?}v{} at depth {}",
2358 pp.packet.tag(), p.version(),
2359 pp.recursion_depth()),
2360 Packet::SEIP(p) =>
2361 t!("Found a {:?}v{} at depth {}",
2362 pp.packet.tag(), p.version(),
2363 pp.recursion_depth()),
2364 _ =>
2365 t!("Found a {:?} at depth {}", pp.packet.tag(),
2366 pp.recursion_depth()),
2367 }
2368
2369 // Check whether we are actually processing a cleartext
2370 // signature framework message.
2371 if v.processing_csf_message.is_none() {
2372 v.processing_csf_message = Some(pp.processing_csf_message());
2373 }
2374
2375 v.policy.packet(&pp.packet)?;
2376 v.helper.inspect(&pp)?;
2377
2378 // When verifying detached signatures, we parse only the
2379 // signatures here, which on their own are not a valid
2380 // message.
2381 if v.mode == Mode::VerifyDetached {
2382 if pp.packet.tag() != packet::Tag::Signature
2383 && pp.packet.tag() != packet::Tag::Marker
2384 {
2385 return Err(Error::MalformedMessage(
2386 format!("Expected signature, got {}", pp.packet.tag()))
2387 .into());
2388 }
2389 } else if let Err(err) = pp.possible_message() {
2390 if v.processing_csf_message.expect("set by now") {
2391 // Our CSF transformation yields just one OPS
2392 // packet per encountered 'Hash' algorithm header,
2393 // and it cannot know how many signatures are in
2394 // fact following. Therefore, the message will
2395 // not be well-formed according to the grammar.
2396 // But, since we created the message structure
2397 // during the transformation, we know it is good,
2398 // even if it is a little out of spec.
2399 } else {
2400 t!("Malformed message: {}", err);
2401 return Err(err.context("Malformed OpenPGP message"));
2402 }
2403 }
2404
2405 let sym_algo_hint = match &pp.packet {
2406 Packet::SEIP(SEIP::V2(seip)) => Some(seip.symmetric_algo()),
2407 _ => None,
2408 };
2409
2410 match pp.packet {
2411 Packet::CompressedData(ref p) =>
2412 v.structure.new_compression_layer(p.algo()),
2413 Packet::SEIP(ref seip) if v.mode == Mode::Decrypt => {
2414 t!("Found the encryption container");
2415
2416 // Bail early (and provide a useful error message)
2417 // if we can't decrypt the SEIP packet.
2418 if let SEIP::V2(seipv2) = seip {
2419 if ! seipv2.symmetric_algo().is_supported() {
2420 return Err(Error::UnsupportedSymmetricAlgorithm(
2421 seipv2.symmetric_algo()).into());
2422 }
2423 if ! seipv2.aead().is_supported() {
2424 return Err(Error::UnsupportedAEADAlgorithm(
2425 seipv2.aead()).into());
2426 }
2427 }
2428
2429 // Get the symmetric algorithm from the decryption
2430 // proxy function. This is necessary because we
2431 // cannot get the algorithm from the SEIP packet.
2432 let mut sym_algo = None;
2433 {
2434 let mut decryption_proxy = |algo, secret: &SessionKey| {
2435 // Take the algo from the SEIPDv2 packet over
2436 // the dummy one from the SKESK6 packet.
2437 let algo = sym_algo_hint.or(algo);
2438 let result = pp.decrypt(algo, secret);
2439 t!("pp.decrypt({:?}, {:?}) => {:?}",
2440 algo, secret, result);
2441 if let Ok(_) = result {
2442 sym_algo = Some(algo);
2443 true
2444 } else {
2445 false
2446 }
2447 };
2448
2449 v.identity =
2450 v.helper.decrypt(&pkesks[..], &skesks[..],
2451 sym_algo_hint,
2452 &mut decryption_proxy)?
2453 .map(|cert| cert.fingerprint());
2454 }
2455 if ! pp.processed() {
2456 return Err(
2457 Error::MissingSessionKey(
2458 "No session key decrypted".into()).into());
2459 }
2460
2461 let sym_algo = if let Some(Some(a)) = sym_algo {
2462 a
2463 } else {
2464 return Err(Error::InvalidOperation(
2465 "No symmetric algorithm known".into()).into());
2466 };
2467
2468 v.policy.symmetric_algorithm(sym_algo)?;
2469 if let Packet::SEIP(SEIP::V2(p)) = &pp.packet {
2470 v.policy.aead_algorithm(p.aead())?;
2471 }
2472
2473 v.structure.new_encryption_layer(
2474 pp.recursion_depth(),
2475 pp.packet.tag() == packet::Tag::SEIP
2476 && pp.packet.version() == Some(1),
2477 sym_algo,
2478 if let Packet::SEIP(SEIP::V2(p)) = &pp.packet {
2479 Some(p.aead())
2480 } else {
2481 None
2482 });
2483 },
2484 Packet::OnePassSig(ref ops) => {
2485 v.structure.push_ops(ops);
2486 v.push_issuer(ops.issuer().clone());
2487 },
2488 Packet::Literal(_) => {
2489 v.structure.insert_missing_signature_group();
2490 v.oppr = Some(PacketParserResult::Some(pp));
2491 v.finish_maybe()?;
2492
2493 return Ok(v);
2494 },
2495 #[allow(deprecated)]
2496 Packet::MDC(ref mdc) => if ! mdc.valid() {
2497 return Err(Error::ManipulatedMessage.into());
2498 },
2499 _ => (),
2500 }
2501
2502 let (p, ppr_tmp) = pp.recurse()?;
2503 match p {
2504 Packet::PKESK(pkesk) => pkesks.push(pkesk),
2505 Packet::SKESK(skesk) => skesks.push(skesk),
2506 Packet::Signature(sig) => {
2507 // The following structure is allowed:
2508 //
2509 // SIG LITERAL
2510 //
2511 // In this case, we get the issuer from the
2512 // signature itself.
2513 sig.get_issuers().into_iter()
2514 .for_each(|i| v.push_issuer(i));
2515 v.structure.push_bare_signature(Ok(sig));
2516 },
2517
2518 Packet::Unknown(u) if u.tag() == packet::Tag::Signature => {
2519 v.structure.push_bare_signature(Err(u));
2520 },
2521
2522 _ => (),
2523 }
2524 ppr = ppr_tmp;
2525 }
2526
2527 if v.mode == Mode::VerifyDetached && !v.structure.layers.is_empty() {
2528 return Ok(v);
2529 }
2530
2531 // We can only get here if we didn't encounter a literal data
2532 // packet.
2533 Err(Error::MalformedMessage(
2534 "Malformed OpenPGP message".into()).into())
2535 }
2536
2537 /// Verifies the given data in detached verification mode.
2538 fn verify_detached<'d>(&mut self,
2539 data: Box<dyn BufferedReader<Cookie> + 'd>)
2540 -> Result<()>
2541 {
2542 assert_eq!(self.mode, Mode::VerifyDetached);
2543
2544 let sigs = if let IMessageLayer::SignatureGroup {
2545 sigs, .. } = &mut self.structure.layers[0] {
2546 sigs
2547 } else {
2548 unreachable!("There is exactly one signature group layer")
2549 };
2550
2551 // Compute the necessary hashes.
2552 let algos: Vec<_> = sigs.iter().filter_map(|s| {
2553 let s = s.as_ref().ok()?;
2554 let h = s.hash_algo();
2555 Some(HashingMode::for_signature(h, s))
2556 }).collect();
2557 let hashes =
2558 crate::parse::hashed_reader::hash_buffered_reader(data, &algos)?;
2559
2560 // Attach the digests.
2561 for sig in sigs.iter_mut().filter_map(|s| s.as_ref().ok()) {
2562 let need_hash =
2563 HashingMode::for_signature(sig.hash_algo(), sig);
2564 // Note: |hashes| < 10, most likely 1.
2565 for mode in hashes.iter()
2566 .filter(|m| m.map(|c| c.algo()) == need_hash)
2567 {
2568 // Clone the hash context, update it with the
2569 // signature.
2570 use crate::crypto::hash::Hash;
2571 let mut hash = mode.as_ref().clone();
2572 sig.hash(&mut hash)?;
2573
2574 // Attach digest to the signature.
2575 let mut digest = vec![0; hash.digest_size()];
2576 let _ = hash.digest(&mut digest);
2577 sig.set_computed_digest(Some(digest));
2578 }
2579 }
2580
2581 self.verify_signatures()
2582 }
2583
2584 /// Stashes the given Signature (if it is one) for later
2585 /// verification.
2586 fn push_sig(&mut self, p: Packet) -> Result<()> {
2587 match p {
2588 Packet::Signature(sig) => {
2589 sig.get_issuers().into_iter().for_each(|i| self.push_issuer(i));
2590 self.structure.push_signature(
2591 Ok(sig), self.processing_csf_message.expect("set by now"));
2592 },
2593 Packet::Unknown(sig) if sig.tag() == packet::Tag::Signature => {
2594 self.structure.push_signature(
2595 Err(sig), self.processing_csf_message.expect("set by now"));
2596 },
2597 _ => (),
2598 }
2599 Ok(())
2600 }
2601
2602 /// Records the issuer for the later certificate lookup.
2603 fn push_issuer<I: Into<KeyHandle>>(&mut self, issuer: I) {
2604 let issuer = issuer.into();
2605 match issuer {
2606 KeyHandle::KeyID(id) if id.is_wildcard() => {
2607 // Ignore, they are not useful for lookups.
2608 },
2609
2610 KeyHandle::KeyID(_) => {
2611 for known in self.issuers.iter() {
2612 if known.aliases(&issuer) {
2613 return;
2614 }
2615 }
2616
2617 // Unknown, record.
2618 self.issuers.push(issuer);
2619 },
2620
2621 KeyHandle::Fingerprint(_) => {
2622 for known in self.issuers.iter_mut() {
2623 if known.aliases(&issuer) {
2624 // Replace. We may upgrade a KeyID to a
2625 // Fingerprint.
2626 *known = issuer;
2627 return;
2628 }
2629 }
2630
2631 // Unknown, record.
2632 self.issuers.push(issuer);
2633 },
2634 }
2635 }
2636
2637 // If the amount of remaining data does not exceed the reserve,
2638 // finish processing the OpenPGP packet sequence.
2639 //
2640 // Note: once this call succeeds, you may not call it again.
2641 fn finish_maybe(&mut self) -> Result<()> {
2642 tracer!(TRACE, "Decryptor::finish_maybe", TRACE_INDENT);
2643 if let Some(PacketParserResult::Some(mut pp)) = self.oppr.take() {
2644 // Check if we hit EOF.
2645 let data_len = pp.data(self.buffer_size + 1)?.len();
2646 if data_len - self.cursor <= self.buffer_size {
2647 // Stash the reserve.
2648 t!("Hit eof with {} bytes of the current buffer consumed.",
2649 self.cursor);
2650 pp.consume(self.cursor);
2651 self.cursor = 0;
2652 self.reserve = Some(pp.steal_eof()?);
2653
2654 // Process the rest of the packets.
2655 let mut ppr = PacketParserResult::Some(pp);
2656 let mut first = true;
2657 while let PacketParserResult::Some(pp) = ppr {
2658 t!("Found a {:?} at depth {}", pp.packet.tag(),
2659 pp.recursion_depth());
2660
2661 // The literal data packet was already inspected.
2662 if first {
2663 assert_eq!(pp.packet.tag(), packet::Tag::Literal);
2664 first = false;
2665 } else {
2666 self.helper.inspect(&pp)?;
2667 }
2668
2669 let possible_message = pp.possible_message();
2670
2671 // If we are ascending, and the packet was the
2672 // last packet in a SEIP container, we need to be
2673 // extra careful with reporting errors to avoid
2674 // creating a decryption oracle.
2675
2676 let last_recursion_depth = pp.recursion_depth();
2677 let (p, ppr_tmp) = match pp.recurse() {
2678 Ok(v) => v,
2679 Err(e) => {
2680 // Assuming we just tried to ascend,
2681 // should there have been a MDC packet?
2682 // If so, this may be an attack.
2683 if self.structure.expect_mdc_at(
2684 last_recursion_depth - 1)
2685 {
2686 return Err(Error::ManipulatedMessage.into());
2687 } else {
2688 return Err(e);
2689 }
2690 },
2691 };
2692 ppr = ppr_tmp;
2693 let recursion_depth = ppr.as_ref()
2694 .map(|pp| pp.recursion_depth()).unwrap_or(0);
2695
2696 // Did we just ascend?
2697 if recursion_depth + 1 == last_recursion_depth
2698 && self.structure.expect_mdc_at(recursion_depth)
2699 {
2700 match &p {
2701 #[allow(deprecated)]
2702 Packet::MDC(mdc) if mdc.valid() =>
2703 (), // Good.
2704 _ => // Bad.
2705 return Err(Error::ManipulatedMessage.into()),
2706 }
2707
2708 if possible_message.is_err() {
2709 return Err(Error::ManipulatedMessage.into());
2710 }
2711 }
2712
2713 if let Err(_err) = possible_message {
2714 if self.processing_csf_message.expect("set by now") {
2715 // CSF transformation creates slightly out
2716 // of spec message structure. See above
2717 // for longer explanation.
2718 } else {
2719 return Err(Error::ManipulatedMessage.into());
2720 }
2721 }
2722
2723 self.push_sig(p)?;
2724 }
2725
2726 // If we finished parsing, validate the message structure.
2727 if let PacketParserResult::EOF(eof) = ppr {
2728 // If we parse a signed message synthesized from a
2729 // cleartext signature framework message, we don't
2730 // quite get the structure right, so relax the
2731 // requirement in this case.
2732 if ! self.processing_csf_message.expect("set by now") {
2733 eof.is_message()?;
2734 }
2735 }
2736
2737 self.verify_signatures()
2738 } else {
2739 t!("Didn't hit EOF.");
2740 self.oppr = Some(PacketParserResult::Some(pp));
2741 Ok(())
2742 }
2743 } else {
2744 panic!("No ppr.");
2745 }
2746 }
2747
2748 /// Verifies the signatures.
2749 fn verify_signatures(&mut self) -> Result<()> {
2750 tracer!(TRACE, "Decryptor::verify_signatures", TRACE_INDENT);
2751 t!("called");
2752
2753 self.certs = self.helper.get_certs(&self.issuers)?;
2754 t!("VerificationHelper::get_certs produced {} certs", self.certs.len());
2755
2756 let mut results = MessageStructure::new();
2757 for layer in self.structure.layers.iter_mut() {
2758 match layer {
2759 IMessageLayer::Compression { algo } =>
2760 results.new_compression_layer(*algo),
2761 IMessageLayer::Encryption { sym_algo, aead_algo, .. } =>
2762 results.new_encryption_layer(*sym_algo, *aead_algo),
2763 IMessageLayer::SignatureGroup { sigs, .. } => {
2764 results.new_signature_group();
2765 'sigs: for sig in sigs.iter_mut() {
2766 let sig = match sig {
2767 Ok(s) => s,
2768 Err(u) => {
2769 // Unparsablee signature.
2770 t!("Unparsablee signature: {}", u.error());
2771 results.push_verification_result(
2772 Err(VerificationError::UnknownSignature {
2773 sig: u,
2774 }));
2775 continue;
2776 }
2777 };
2778
2779 let sigid = *sig.digest_prefix();
2780
2781 let sig_time = if let Some(t) = sig.signature_creation_time() {
2782 t
2783 } else {
2784 // Invalid signature.
2785 results.push_verification_result(
2786 Err(VerificationError::MalformedSignature {
2787 sig,
2788 error: Error::MalformedPacket(
2789 "missing a Signature Creation Time \
2790 subpacket"
2791 .into()).into(),
2792 }));
2793 t!("{:02X}{:02X}: Missing a signature creation time subpacket",
2794 sigid[0], sigid[1]);
2795 continue;
2796 };
2797
2798 let mut err = VerificationErrorInternal::MissingKey {};
2799
2800 let issuers = sig.get_issuers();
2801 // Note: If there are no issuers, the only way
2802 // to verify the signature is to try every key
2803 // that could possibly have created the
2804 // signature. While this may be feasible if
2805 // the set of potential signing keys is small,
2806 // the use case of hiding the signer's
2807 // identity seems better solved using
2808 // encryption. Furthermore, no other OpenPGP
2809 // implementation seems to support this kind
2810 // of wildcard signatures.
2811 let no_issuers = issuers.is_empty();
2812
2813 for ka in self.certs.iter().flat_map(
2814 |c| c.keys().key_handles(issuers.clone()))
2815 {
2816 if no_issuers {
2817 // Slightly awkward control flow
2818 // change. Below this loop, we still
2819 // have to add this signature to the
2820 // results with the default error,
2821 // `VerificationError::MissingKey`.
2822 break;
2823 }
2824
2825 let cert = ka.cert();
2826 let fingerprint = ka.key().fingerprint();
2827 let ka = match ka.with_policy(self.policy, sig_time) {
2828 Err(policy_err) => {
2829 t!("{:02X}{:02X}: key {} rejected by policy: {}",
2830 sigid[0], sigid[1], fingerprint, policy_err);
2831 err = VerificationErrorInternal::UnboundKey {
2832 cert,
2833 error: policy_err,
2834 };
2835 continue;
2836 }
2837 Ok(ka) => {
2838 t!("{:02X}{:02X}: key {} accepted by policy",
2839 sigid[0], sigid[1], fingerprint);
2840 ka
2841 }
2842 };
2843
2844 err = if let Err(error) = ka.valid_cert().alive() {
2845 t!("{:02X}{:02X}: cert {} not alive: {}",
2846 sigid[0], sigid[1], ka.cert().fingerprint(), error);
2847 VerificationErrorInternal::BadKey {
2848 ka,
2849 error,
2850 }
2851 } else if let Err(error) = ka.alive() {
2852 t!("{:02X}{:02X}: key {} not alive: {}",
2853 sigid[0], sigid[1], ka.key().fingerprint(), error);
2854 VerificationErrorInternal::BadKey {
2855 ka,
2856 error,
2857 }
2858 } else if let
2859 RevocationStatus::Revoked(rev) = ka.valid_cert().revocation_status()
2860 {
2861 t!("{:02X}{:02X}: cert {} revoked: {:?}",
2862 sigid[0], sigid[1], ka.cert().fingerprint(), rev);
2863 VerificationErrorInternal::BadKey {
2864 ka,
2865 error: Error::InvalidKey(
2866 "certificate is revoked".into())
2867 .into(),
2868 }
2869 } else if let
2870 RevocationStatus::Revoked(rev) = ka.revocation_status()
2871 {
2872 t!("{:02X}{:02X}: key {} revoked: {:?}",
2873 sigid[0], sigid[1], ka.key().fingerprint(), rev);
2874 VerificationErrorInternal::BadKey {
2875 ka,
2876 error: Error::InvalidKey(
2877 "signing key is revoked".into())
2878 .into(),
2879 }
2880 } else if ! ka.for_signing() {
2881 t!("{:02X}{:02X}: key {} not signing capable",
2882 sigid[0], sigid[1], ka.key().fingerprint());
2883 VerificationErrorInternal::BadKey {
2884 ka,
2885 error: Error::InvalidKey(
2886 "key is not signing capable".into())
2887 .into(),
2888 }
2889 } else if let Err(error) = sig.signature_alive(
2890 self.time, self.clock_skew_tolerance)
2891 {
2892 t!("{:02X}{:02X}: Signature not alive: {}",
2893 sigid[0], sigid[1], error);
2894 VerificationErrorInternal::BadSignature {
2895 ka,
2896 error,
2897 }
2898 } else if self.identity.as_ref().map(|identity| {
2899 let (have_one, contains_identity) =
2900 sig.intended_recipients()
2901 .fold((false, false),
2902 |(_, contains_one), ir| {
2903 (
2904 true,
2905 contains_one || identity == ir
2906 )
2907 });
2908 have_one && ! contains_identity
2909 }).unwrap_or(false) {
2910 // The signature contains intended
2911 // recipients, but we are not one.
2912 // Treat the signature as bad.
2913 t!("{:02X}{:02X}: not an intended recipient",
2914 sigid[0], sigid[1]);
2915 VerificationErrorInternal::BadSignature {
2916 ka,
2917 error: Error::BadSignature(
2918 "Not an intended recipient".into())
2919 .into(),
2920 }
2921 } else {
2922 match sig.verify_document(ka.key()) {
2923 Ok(()) => {
2924 if let Err(error)
2925 = self.policy.signature(
2926 sig, Default::default())
2927 {
2928 t!("{:02X}{:02X}: signature rejected by policy: {}",
2929 sigid[0], sigid[1], error);
2930 VerificationErrorInternal::BadSignature {
2931 ka,
2932 error,
2933 }
2934 } else {
2935 t!("{:02X}{:02X}: good checksum using {}",
2936 sigid[0], sigid[1], ka.key().fingerprint());
2937 results.push_verification_result(
2938 Ok(GoodChecksum {
2939 sig,
2940 ka,
2941 }));
2942 // Continue to the next sig.
2943 continue 'sigs;
2944 }
2945 }
2946 Err(error) => {
2947 t!("{:02X}{:02X} using {}: error: {}",
2948 sigid[0], sigid[1], ka.key().fingerprint(), error);
2949 VerificationErrorInternal::BadSignature {
2950 ka,
2951 error,
2952 }
2953 }
2954 }
2955 }
2956 }
2957
2958 let err = err.attach_sig(sig);
2959 t!("{:02X}{:02X}: returning: {:?}", sigid[0], sigid[1], err);
2960 results.push_verification_result(Err(err));
2961 }
2962 }
2963 }
2964 }
2965
2966 let r = self.helper.check(results);
2967 t!("-> {:?}", r);
2968 r
2969 }
2970
2971 /// Like `io::Read::read()`, but returns our `Result`.
2972 fn read_helper(&mut self, buf: &mut [u8]) -> Result<usize> {
2973 tracer!(TRACE, "Decryptor::read_helper", TRACE_INDENT);
2974 t!("read(buf of {} bytes)", buf.len());
2975
2976 if buf.is_empty() {
2977 return Ok(0);
2978 }
2979
2980 if let Some(ref mut reserve) = self.reserve {
2981 // The message has been verified. We can now drain the
2982 // reserve.
2983 t!("Message verified, draining reserve.");
2984 assert!(self.oppr.is_none());
2985 assert!(self.cursor <= reserve.len());
2986 let n = cmp::min(buf.len(), reserve.len() - self.cursor);
2987 buf[..n]
2988 .copy_from_slice(&reserve[self.cursor..n + self.cursor]);
2989 self.cursor += n;
2990 return Ok(n);
2991 }
2992
2993 // Read the data from the Literal data packet.
2994 if let Some(PacketParserResult::Some(mut pp)) = self.oppr.take() {
2995 // Be careful to not read from the reserve.
2996 if self.cursor >= self.buffer_size {
2997 // Consume the active part of the buffer.
2998 t!("Consuming first part of the buffer.");
2999 pp.consume(self.buffer_size);
3000 self.cursor -= self.buffer_size;
3001 }
3002
3003 // We request two times what our buffer size is, the first
3004 // part is the one we give out, the second part is the one
3005 // we hold back.
3006 let data_len = pp.data(2 * self.buffer_size)?.len();
3007 t!("Read {} bytes.", data_len);
3008 if data_len - self.cursor <= self.buffer_size {
3009 self.oppr = Some(PacketParserResult::Some(pp));
3010 self.finish_maybe()?;
3011 self.read_helper(buf)
3012 } else {
3013 let data = pp.data(2 * self.buffer_size - self.cursor)?;
3014 assert_eq!(data.len(), data_len);
3015
3016 let n =
3017 buf.len().min(data_len - self.buffer_size - self.cursor);
3018 buf[..n].copy_from_slice(&data[self.cursor..self.cursor + n]);
3019 self.cursor += n;
3020 self.oppr = Some(PacketParserResult::Some(pp));
3021 t!("Copied {} bytes from buffer, cursor is {}.", n, self.cursor);
3022 Ok(n)
3023 }
3024 } else {
3025 panic!("No ppr.");
3026 }
3027 }
3028}
3029
3030impl<'a, H: VerificationHelper + DecryptionHelper> io::Read for Decryptor<'a, H>
3031{
3032 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
3033 match self.read_helper(buf) {
3034 Ok(n) => Ok(n),
3035 Err(e) => match e.downcast::<io::Error>() {
3036 // An io::Error. Pass as-is.
3037 Ok(e) => Err(e),
3038 // A failure. Wrap it.
3039 Err(e) => Err(io::Error::new(io::ErrorKind::Other, e)),
3040 },
3041 }
3042 }
3043}
3044
3045#[cfg(test)]
3046pub(crate) mod test {
3047 use std::io::Read;
3048 use super::*;
3049 use std::convert::TryFrom;
3050 use crate::parse::Parse;
3051 use crate::policy::{NullPolicy as NP, StandardPolicy as P};
3052 use crate::serialize::Serialize;
3053 use crate::{
3054 crypto::Password,
3055 };
3056
3057 /// Verification helper for the tests.
3058 #[derive(Clone)]
3059 pub struct VHelper {
3060 good: usize,
3061 unknown: usize,
3062 bad: usize,
3063 error: usize,
3064 certs: Vec<Cert>,
3065 keys: Vec<Cert>,
3066 passwords: Vec<Password>,
3067 for_decryption: bool,
3068 error_out: bool,
3069 pub packets: Vec<Packet>,
3070 }
3071
3072 impl std::fmt::Debug for VHelper {
3073 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
3074 f.debug_struct("VHelper")
3075 .field("good", &self.good)
3076 .field("unknown", &self.unknown)
3077 .field("bad", &self.bad)
3078 .field("error", &self.error)
3079 .field("error_out", &self.error_out)
3080 .finish()
3081 }
3082 }
3083
3084 impl Default for VHelper {
3085 fn default() -> Self {
3086 VHelper {
3087 good: 0,
3088 unknown: 0,
3089 bad: 0,
3090 error: 0,
3091 certs: Vec::default(),
3092 keys: Vec::default(),
3093 passwords: Default::default(),
3094 for_decryption: false,
3095 error_out: true,
3096 packets: Default::default(),
3097 }
3098 }
3099 }
3100
3101 impl VHelper {
3102 /// Creates a new verification helper.
3103 pub fn new(good: usize, unknown: usize, bad: usize, error: usize,
3104 certs: Vec<Cert>)
3105 -> Self {
3106 VHelper {
3107 good,
3108 unknown,
3109 bad,
3110 error,
3111 certs,
3112 keys: Default::default(),
3113 passwords: Default::default(),
3114 for_decryption: false,
3115 error_out: true,
3116 packets: Default::default(),
3117 }
3118 }
3119
3120 /// Creates a new decryption helper.
3121 pub fn for_decryption(good: usize, unknown: usize, bad: usize,
3122 error: usize,
3123 certs: Vec<Cert>,
3124 keys: Vec<Cert>,
3125 passwords: Vec<Password>)
3126 -> Self {
3127 VHelper {
3128 good,
3129 unknown,
3130 bad,
3131 error,
3132 certs,
3133 keys,
3134 passwords,
3135 for_decryption: true,
3136 error_out: true,
3137 packets: Default::default(),
3138 }
3139 }
3140
3141 /// Compares the stats.
3142 pub fn assert_stats_eq(&self, other: &Self) {
3143 assert_eq!(self.good, other.good);
3144 assert_eq!(self.unknown, other.unknown);
3145 assert_eq!(self.bad, other.bad);
3146 assert_eq!(self.error, other.error);
3147 }
3148 }
3149
3150 impl VerificationHelper for VHelper {
3151 fn inspect(&mut self, pp: &PacketParser<'_>) -> Result<()> {
3152 self.packets.push(pp.packet.clone());
3153 Ok(())
3154 }
3155
3156 fn get_certs(&mut self, _ids: &[crate::KeyHandle]) -> Result<Vec<Cert>> {
3157 Ok(self.certs.clone())
3158 }
3159
3160 fn check(&mut self, structure: MessageStructure) -> Result<()> {
3161 use self::VerificationError::*;
3162 for layer in structure.iter() {
3163 match layer {
3164 MessageLayer::SignatureGroup { ref results } =>
3165 for result in results {
3166 match result {
3167 Ok(_) => self.good += 1,
3168 Err(MissingKey { .. }) => self.unknown += 1,
3169 Err(UnboundKey { .. }) => self.unknown += 1,
3170 Err(MalformedSignature { .. }) => self.bad += 1,
3171 Err(UnknownSignature { .. }) => self.bad += 1,
3172 Err(BadKey { .. }) => self.bad += 1,
3173 Err(BadSignature { error, .. }) => {
3174 eprintln!("error: {}", error);
3175 self.bad += 1;
3176 },
3177 }
3178 }
3179 MessageLayer::Compression { .. } => (),
3180 MessageLayer::Encryption { .. } => (),
3181 }
3182 }
3183
3184 if ! self.error_out || (self.good > 0 && self.bad == 0)
3185 || (self.for_decryption && self.certs.is_empty())
3186 {
3187 Ok(())
3188 } else {
3189 Err(anyhow::anyhow!("Verification failed: {:?}", self))
3190 }
3191 }
3192 }
3193
3194 impl DecryptionHelper for VHelper {
3195 fn decrypt(&mut self, pkesks: &[PKESK], skesks: &[SKESK],
3196 sym_algo: Option<SymmetricAlgorithm>,
3197 decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
3198 -> Result<Option<Cert>>
3199 {
3200 tracer!(TRACE, "VHelper::decrypt", TRACE_INDENT);
3201
3202 let p = P::new();
3203 if ! self.for_decryption {
3204 unreachable!("Shouldn't be called for verifications");
3205 }
3206
3207 t!("Trying SKESKS: {:?}", skesks);
3208 for (i, skesk) in skesks.iter().enumerate() {
3209 for p in &self.passwords {
3210 let r = skesk.decrypt(p);
3211 t!("decrypting SKESK {}: {:?}", i, r);
3212 if let Ok((algo, sk)) = r {
3213 if decrypt(algo, &sk) {
3214 t!("successfully decrypted encryption container");
3215 return Ok(None);
3216 }
3217 }
3218 }
3219 }
3220
3221 t!("Trying PKESKS: {:?}", pkesks);
3222 for pkesk in pkesks.iter().filter(|p| p.recipient().is_some()) {
3223 for key in &self.keys {
3224 for subkey in key.with_policy(&p, None)?.keys().secret()
3225 .key_handles(pkesk.recipient())
3226 {
3227 t!("Trying to decrypt {:?} with {:?}", pkesk, subkey);
3228 if let Some((algo, sk)) =
3229 subkey.key().clone().into_keypair().ok()
3230 .and_then(|mut k| pkesk.decrypt(&mut k, sym_algo))
3231 {
3232 if decrypt(algo, &sk) {
3233 t!("successfully decrypted encryption container");
3234 return Ok(None);
3235 }
3236 }
3237 }
3238 }
3239 }
3240
3241 t!("decryption of session key failed");
3242 Err(Error::MissingSessionKey("Decryption failed".into()).into())
3243 }
3244 }
3245
3246 #[test]
3247 fn verifier() -> Result<()> {
3248 let p = P::new();
3249
3250 let certs = [
3251 "keys/neal.pgp",
3252 "keys/testy-new.pgp",
3253 "keys/emmelie-dorothea-dina-samantha-awina-ed25519.pgp",
3254 "crypto-refresh/v6-minimal-cert.key",
3255 ].iter()
3256 .map(|f| Cert::from_bytes(crate::tests::file(f)).unwrap())
3257 .collect::<Vec<_>>();
3258 let tests = &[
3259 // Signed messages.
3260 (crate::tests::message("signed-1.pgp").to_vec(),
3261 crate::tests::manifesto().to_vec(),
3262 true,
3263 Some(crate::frozen_time()),
3264 VHelper::new(1, 0, 0, 0, certs.clone())),
3265 // The same, but with a marker packet.
3266 ({
3267 let pp = crate::PacketPile::from_bytes(
3268 crate::tests::message("signed-1.pgp"))?;
3269 let mut buf = Vec::new();
3270 Packet::Marker(Default::default()).serialize(&mut buf)?;
3271 pp.serialize(&mut buf)?;
3272 buf
3273 },
3274 crate::tests::manifesto().to_vec(),
3275 true,
3276 Some(crate::frozen_time()),
3277 VHelper::new(1, 0, 0, 0, certs.clone())),
3278 (crate::tests::message("signed-1-sha256-testy.pgp").to_vec(),
3279 crate::tests::manifesto().to_vec(),
3280 true,
3281 Some(crate::frozen_time()),
3282 VHelper::new(0, 1, 0, 0, certs.clone())),
3283 (crate::tests::message("signed-1-notarized-by-ed25519.pgp")
3284 .to_vec(),
3285 crate::tests::manifesto().to_vec(),
3286 true,
3287 Some(crate::frozen_time()),
3288 VHelper::new(2, 0, 0, 0, certs.clone())),
3289 // Signed messages using the Cleartext Signature Framework.
3290 (crate::tests::message("a-cypherpunks-manifesto.txt.cleartext.sig")
3291 .to_vec(),
3292 {
3293 // The test vector, created by GnuPG, does not preserve
3294 // the final newline.
3295 //
3296 // The transformation process trims trailing whitespace,
3297 // and the manifesto has a trailing whitespace right at
3298 // the end.
3299 let mut manifesto = crate::tests::manifesto().to_vec();
3300 assert_eq!(manifesto.pop(), Some(b'\n'));
3301 assert_eq!(manifesto.pop(), Some(b' '));
3302 manifesto
3303 },
3304 false,
3305 None,
3306 VHelper::new(1, 0, 0, 0, certs.clone())),
3307 (crate::tests::message("a-problematic-poem.txt.cleartext.sig")
3308 .to_vec(),
3309 {
3310 // The test vector, created by GnuPG, does not preserve
3311 // the final newline.
3312 let mut reference =
3313 crate::tests::message("a-problematic-poem.txt").to_vec();
3314 assert_eq!(reference.pop(), Some(b'\n'));
3315 reference
3316 },
3317 false,
3318 None,
3319 VHelper::new(1, 0, 0, 0, certs.clone())),
3320 (crate::tests::file("crypto-refresh/cleartext-signed-message.txt")
3321 .to_vec(),
3322 crate::tests::file("crypto-refresh/cleartext-signed-message.txt.plain")
3323 .to_vec(),
3324 false,
3325 None,
3326 VHelper::new(1, 0, 0, 0, certs.clone())),
3327 // A key as example of an invalid message.
3328 (crate::tests::key("neal.pgp").to_vec(),
3329 crate::tests::manifesto().to_vec(),
3330 true,
3331 Some(crate::frozen_time()),
3332 VHelper::new(0, 0, 0, 1, certs.clone())),
3333 // A signed message where the signature type is text and a
3334 // crlf straddles two chunks.
3335 (crate::tests::message("crlf-straddles-chunks.txt.sig").to_vec(),
3336 crate::tests::message("crlf-straddles-chunks.txt").to_vec(),
3337 false,
3338 None,
3339 VHelper::new(1, 0, 0, 0, certs.clone())),
3340 // Like crlf-straddles-chunks, but the signature includes a
3341 // notation with a '\n'. Make sure it is not converted to
3342 // a '\r\n'.
3343 (crate::tests::message("text-signature-notation-has-lf.txt.sig").to_vec(),
3344 crate::tests::message("text-signature-notation-has-lf.txt").to_vec(),
3345 false,
3346 None,
3347 VHelper::new(1, 0, 0, 0, certs.clone())),
3348 ];
3349
3350 for (i, (signed, reference, test_decryptor, time, r))
3351 in tests.iter().enumerate()
3352 {
3353 eprintln!("{}...", i);
3354
3355 // Test Verifier.
3356 let h = VHelper::new(0, 0, 0, 0, certs.clone());
3357 let mut v =
3358 match VerifierBuilder::from_bytes(&signed)?
3359 .with_policy(&p, *time, h) {
3360 Ok(v) => v,
3361 Err(e) => if r.error > 0 || r.unknown > 0 {
3362 // Expected error. No point in trying to read
3363 // something.
3364 continue;
3365 } else {
3366 panic!("{}: {}", i, e);
3367 },
3368 };
3369 assert!(v.message_processed());
3370 r.assert_stats_eq(v.helper_ref());
3371
3372 if v.helper_ref().error > 0 {
3373 // Expected error. No point in trying to read
3374 // something.
3375 continue;
3376 }
3377
3378 let mut content = Vec::new();
3379 v.read_to_end(&mut content).unwrap();
3380 assert_eq!(reference.len(), content.len());
3381 assert_eq!(&reference[..], &content[..]);
3382
3383 if ! test_decryptor {
3384 continue;
3385 }
3386
3387 // Test Decryptor.
3388 let h = VHelper::new(0, 0, 0, 0, certs.clone());
3389 let mut v = match DecryptorBuilder::from_bytes(&signed)?
3390 .with_policy(&p, *time, h) {
3391 Ok(v) => v,
3392 Err(e) => if r.error > 0 || r.unknown > 0 {
3393 // Expected error. No point in trying to read
3394 // something.
3395 continue;
3396 } else {
3397 panic!("{}: {}", i, e);
3398 },
3399 };
3400 assert!(v.message_processed());
3401 r.assert_stats_eq(v.helper_ref());
3402
3403 if v.helper_ref().error > 0 {
3404 // Expected error. No point in trying to read
3405 // something.
3406 continue;
3407 }
3408
3409 let mut content = Vec::new();
3410 v.read_to_end(&mut content).unwrap();
3411 assert_eq!(reference.len(), content.len());
3412 assert_eq!(&reference[..], &content[..]);
3413 }
3414 Ok(())
3415 }
3416
3417 #[test]
3418 fn decryptor() -> Result<()> {
3419 let p = P::new();
3420 for (key_file, message, plaintext) in &[
3421 ("messages/encrypted/rsa.sec.pgp",
3422 "messages/encrypted/rsa.msg.pgp",
3423 "Hello World!\n"),
3424 ("messages/encrypted/elg.sec.pgp",
3425 "messages/encrypted/elg.msg.pgp",
3426 "Hello World!\n"),
3427 ("messages/encrypted/cv25519.sec.pgp",
3428 "messages/encrypted/cv25519.msg.pgp",
3429 "Hello World!\n"),
3430 ("messages/encrypted/cv25519.unclamped.sec.pgp",
3431 "messages/encrypted/cv25519.unclamped.msg.pgp",
3432 "дружба"),
3433 ("messages/encrypted/nistp256.sec.pgp",
3434 "messages/encrypted/nistp256.msg.pgp",
3435 "Hello World!\n"),
3436 ("messages/encrypted/nistp384.sec.pgp",
3437 "messages/encrypted/nistp384.msg.pgp",
3438 "Hello World!\n"),
3439 ("messages/encrypted/nistp521.sec.pgp",
3440 "messages/encrypted/nistp521.msg.pgp",
3441 "Hello World!\n"),
3442 ("messages/encrypted/brainpoolP256r1.sec.pgp",
3443 "messages/encrypted/brainpoolP256r1.msg.pgp",
3444 "Hello World!\n"),
3445 ("messages/encrypted/brainpoolP384r1.sec.pgp",
3446 "messages/encrypted/brainpoolP384r1.msg.pgp",
3447 "Hello World!\n"),
3448 ("messages/encrypted/brainpoolP512r1.sec.pgp",
3449 "messages/encrypted/brainpoolP512r1.msg.pgp",
3450 "Hello World!\n"),
3451 ("messages/encrypted/secp256k1.sec.pgp",
3452 "messages/encrypted/secp256k1.msg.pgp",
3453 "Hello World!\n"),
3454 ("messages/encrypted/x448.sec.pgp",
3455 "messages/encrypted/x448.msg.pgp",
3456 "Hello World!\n"),
3457 ] {
3458 eprintln!("Test vector {:?}...", key_file);
3459 let key = Cert::from_bytes(crate::tests::file(key_file))?;
3460 if ! key.primary_key().key().pk_algo().is_supported() {
3461 eprintln!("Skipping {} because we don't support {}",
3462 key, key.primary_key().key().pk_algo());
3463 continue;
3464 }
3465
3466 if let Some(k) =
3467 key.with_policy(&p, None)?.keys().subkeys().supported().last()
3468 {
3469 use crate::crypto::mpi::PublicKey;
3470 match k.key().mpis() {
3471 PublicKey::ECDH { curve, .. } if ! curve.is_supported() => {
3472 eprintln!("Skipping {} because we don't support \
3473 the curve {}", key_file, curve);
3474 continue;
3475 },
3476 _ => (),
3477 }
3478 } else {
3479 eprintln!("Skipping {} because we don't support the algorithm",
3480 key_file);
3481 continue;
3482 }
3483
3484 let h = VHelper::for_decryption(0, 0, 0, 0, Vec::new(),
3485 vec![key], Vec::new());
3486 let mut d = DecryptorBuilder::from_bytes(crate::tests::file(message))?
3487 .with_policy(&p, None, h)?;
3488 assert!(d.message_processed());
3489
3490 if d.helper_ref().error > 0 {
3491 // Expected error. No point in trying to read
3492 // something.
3493 continue;
3494 }
3495
3496 let mut content = Vec::new();
3497 d.read_to_end(&mut content).unwrap();
3498 let content = String::from_utf8(content).unwrap();
3499 eprintln!("decrypted {:?} using {}", content, key_file);
3500 assert_eq!(&content[..], &plaintext[..]);
3501 }
3502
3503 Ok(())
3504 }
3505
3506 /// Tests legacy two-pass signature scheme, corner cases.
3507 ///
3508 /// XXX: This test needs to be adapted once
3509 /// https://gitlab.com/sequoia-pgp/sequoia/-/issues/128 is
3510 /// implemented.
3511 #[test]
3512 fn verifier_legacy() -> Result<()> {
3513 let packets = crate::PacketPile::from_bytes(
3514 crate::tests::message("signed-1.pgp")
3515 )?
3516 .into_children()
3517 .collect::<Vec<_>>();
3518
3519 fn check(msg: &str, buf: &[u8], expect_good: usize) -> Result<()> {
3520 eprintln!("{}...", msg);
3521 let p = P::new();
3522
3523 let certs = [
3524 "neal.pgp",
3525 ]
3526 .iter()
3527 .map(|f| Cert::from_bytes(crate::tests::key(f)).unwrap())
3528 .collect::<Vec<_>>();
3529
3530 let mut h = VHelper::new(0, 0, 0, 0, certs.clone());
3531 h.error_out = false;
3532 let mut v = VerifierBuilder::from_bytes(buf)?
3533 .with_policy(&p, crate::frozen_time(), h)?;
3534 assert!(v.message_processed());
3535 assert_eq!(v.helper_ref().good, expect_good);
3536
3537 let mut content = Vec::new();
3538 v.read_to_end(&mut content).unwrap();
3539 let reference = crate::tests::manifesto();
3540 assert_eq!(reference.len(), content.len());
3541 assert_eq!(reference, &content[..]);
3542 Ok(())
3543 }
3544
3545 // Bare legacy signed message: SIG Literal
3546 let mut o = Vec::new();
3547 packets[2].serialize(&mut o)?;
3548 packets[1].serialize(&mut o)?;
3549 check("bare", &o, 0 /* XXX: should be 1 once #128 is implemented. */)?;
3550
3551 // Legacy signed message, two signatures: SIG SIG Literal
3552 let mut o = Vec::new();
3553 packets[2].serialize(&mut o)?;
3554 packets[2].serialize(&mut o)?;
3555 packets[1].serialize(&mut o)?;
3556 check("double", &o, 0 /* XXX: should be 2 once #128 is implemented. */)?;
3557
3558 // Weird legacy signed message: OPS SIG Literal SIG
3559 let mut o = Vec::new();
3560 packets[0].serialize(&mut o)?;
3561 packets[2].serialize(&mut o)?;
3562 packets[1].serialize(&mut o)?;
3563 packets[2].serialize(&mut o)?;
3564 check("weird", &o, 0 /* XXX: should be 2 once #128 is implemented. */)?;
3565
3566 // Fubar legacy signed message: SIG OPS Literal SIG
3567 let mut o = Vec::new();
3568 packets[2].serialize(&mut o)?;
3569 packets[0].serialize(&mut o)?;
3570 packets[1].serialize(&mut o)?;
3571 packets[2].serialize(&mut o)?;
3572 check("fubar", &o, 1 /* XXX: should be 2 once #128 is implemented. */)?;
3573
3574 Ok(())
3575 }
3576
3577 /// Tests the order of signatures given to
3578 /// VerificationHelper::check().
3579 #[test]
3580 fn verifier_levels() -> Result<()> {
3581 let p = P::new();
3582
3583 struct VHelper(());
3584 impl VerificationHelper for VHelper {
3585 fn get_certs(&mut self, _ids: &[crate::KeyHandle])
3586 -> Result<Vec<Cert>> {
3587 Ok(Vec::new())
3588 }
3589
3590 fn check(&mut self, structure: MessageStructure) -> Result<()> {
3591 assert_eq!(structure.iter().count(), 2);
3592 for (i, layer) in structure.into_iter().enumerate() {
3593 match layer {
3594 MessageLayer::SignatureGroup { results } => {
3595 assert_eq!(results.len(), 1);
3596 if let Err(VerificationError::MissingKey {
3597 sig, ..
3598 }) = &results[0] {
3599 assert_eq!(
3600 &sig.issuer_fingerprints().next().unwrap()
3601 .to_hex(),
3602 match i {
3603 0 => "8E8C33FA4626337976D97978069C0C348DD82C19",
3604 1 => "C03FA6411B03AE12576461187223B56678E02528",
3605 _ => unreachable!(),
3606 }
3607 );
3608 } else {
3609 unreachable!()
3610 }
3611 },
3612 _ => unreachable!(),
3613 }
3614 }
3615 Ok(())
3616 }
3617 }
3618 impl DecryptionHelper for VHelper {
3619 fn decrypt(&mut self, _: &[PKESK], _: &[SKESK],
3620 _: Option<SymmetricAlgorithm>,
3621 _: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
3622 -> Result<Option<Cert>>
3623 {
3624 unreachable!();
3625 }
3626 }
3627
3628 // Test verifier.
3629 let v = VerifierBuilder::from_bytes(
3630 crate::tests::message("signed-1-notarized-by-ed25519.pgp"))?
3631 .with_policy(&p, crate::frozen_time(), VHelper(()))?;
3632 assert!(v.message_processed());
3633
3634 // Test decryptor.
3635 let v = DecryptorBuilder::from_bytes(
3636 crate::tests::message("signed-1-notarized-by-ed25519.pgp"))?
3637 .with_policy(&p, crate::frozen_time(), VHelper(()))?;
3638 assert!(v.message_processed());
3639 Ok(())
3640 }
3641
3642 #[test]
3643 fn detached_verifier() -> Result<()> {
3644 fn zeros() -> &'static [u8] {
3645 use std::sync::OnceLock;
3646 static ZEROS: OnceLock<Vec<u8>> = OnceLock::new();
3647 ZEROS.get_or_init(|| vec![0; 100 * 1024 * 1024])
3648 }
3649
3650 let p = P::new();
3651
3652 struct Test<'a> {
3653 sig: Vec<u8>,
3654 content: &'a [u8],
3655 reference: time::SystemTime,
3656 }
3657 let tests = [
3658 Test {
3659 sig: crate::tests::message(
3660 "a-cypherpunks-manifesto.txt.ed25519.sig").to_vec(),
3661 content: crate::tests::manifesto(),
3662 reference: crate::frozen_time(),
3663 },
3664 // The same, but with a marker packet.
3665 Test {
3666 sig: {
3667 let sig = crate::PacketPile::from_bytes(
3668 crate::tests::message(
3669 "a-cypherpunks-manifesto.txt.ed25519.sig"))?;
3670 let mut buf = Vec::new();
3671 Packet::Marker(Default::default()).serialize(&mut buf)?;
3672 sig.serialize(&mut buf)?;
3673 buf
3674 },
3675 content: crate::tests::manifesto(),
3676 reference: crate::frozen_time(),
3677 },
3678 Test {
3679 sig: crate::tests::message(
3680 "emmelie-dorothea-dina-samantha-awina-detached-signature-of-100MB-of-zeros.sig")
3681 .to_vec(),
3682 content: zeros(),
3683 reference:
3684 crate::types::Timestamp::try_from(1572602018).unwrap().into(),
3685 },
3686 ];
3687
3688 let certs = [
3689 "emmelie-dorothea-dina-samantha-awina-ed25519.pgp"
3690 ].iter()
3691 .map(|f| Cert::from_bytes(crate::tests::key(f)).unwrap())
3692 .collect::<Vec<_>>();
3693
3694 for test in tests.iter() {
3695 let sig = &test.sig;
3696 let content = test.content;
3697 let reference = test.reference;
3698
3699 let h = VHelper::new(0, 0, 0, 0, certs.clone());
3700 let mut v = DetachedVerifierBuilder::from_bytes(sig).unwrap()
3701 .with_policy(&p, reference, h).unwrap();
3702 v.verify_bytes(content).unwrap();
3703
3704 let h = v.into_helper();
3705 assert_eq!(h.good, 1);
3706 assert_eq!(h.bad, 0);
3707 }
3708 Ok(())
3709 }
3710
3711 #[test]
3712 fn issue_682() -> Result<()> {
3713 let p = P::new();
3714 let sig = crate::tests::message("signature-with-broken-mpis.sig");
3715
3716 let h = VHelper::new(0, 0, 0, 0, vec![]);
3717 let mut v = DetachedVerifierBuilder::from_bytes(sig)?
3718 .with_policy(&p, None, h)?;
3719
3720 assert!(v.verify_bytes(b"").is_err());
3721
3722 let h = v.into_helper();
3723 assert_eq!(h.bad, 1);
3724
3725 Ok(())
3726 }
3727
3728 #[test]
3729 fn verify_long_message() -> Result<()> {
3730 use std::io::Write;
3731 use crate::serialize::stream::{LiteralWriter, Signer, Message};
3732
3733 let p = &P::new();
3734
3735 let (cert, _) = CertBuilder::new()
3736 .set_cipher_suite(CipherSuite::Cv25519)
3737 .add_signing_subkey()
3738 .generate().unwrap();
3739
3740 // sign 3MiB message
3741 let mut buf = vec![];
3742 {
3743 let key = cert.keys().with_policy(p, None).for_signing().next().unwrap().key();
3744 let keypair =
3745 key.clone().parts_into_secret().unwrap()
3746 .into_keypair().unwrap();
3747
3748 let m = Message::new(&mut buf);
3749 let signer = Signer::new(m, keypair)?.build().unwrap();
3750 let mut ls = LiteralWriter::new(signer).build().unwrap();
3751
3752 ls.write_all(&mut vec![42u8; 3 * 1024 * 1024]).unwrap();
3753 ls.finalize().unwrap();
3754 }
3755
3756 // Test Verifier.
3757 let h = VHelper::new(0, 0, 0, 0, vec![cert.clone()]);
3758 let mut v = VerifierBuilder::from_bytes(&buf)?
3759 .buffer_size(2 * 2usize.pow(20))
3760 .with_policy(p, None, h)?;
3761
3762 assert!(!v.message_processed());
3763 assert!(v.helper_ref().good == 0);
3764 assert!(v.helper_ref().bad == 0);
3765 assert!(v.helper_ref().unknown == 0);
3766 assert!(v.helper_ref().error == 0);
3767
3768 let mut message = Vec::new();
3769
3770 v.read_to_end(&mut message).unwrap();
3771
3772 assert!(v.message_processed());
3773 assert_eq!(3 * 1024 * 1024, message.len());
3774 assert!(message.iter().all(|&b| b == 42));
3775 assert!(v.helper_ref().good == 1);
3776 assert!(v.helper_ref().bad == 0);
3777 assert!(v.helper_ref().unknown == 0);
3778 assert!(v.helper_ref().error == 0);
3779
3780 // Try the same, but this time we let .check() fail.
3781 let h = VHelper::new(0, 0, /* makes check() fail: */ 1, 0,
3782 vec![cert.clone()]);
3783 let mut v = VerifierBuilder::from_bytes(&buf)?
3784 .buffer_size(2 * 2usize.pow(20))
3785 .with_policy(p, None, h)?;
3786
3787 assert!(!v.message_processed());
3788 assert!(v.helper_ref().good == 0);
3789 assert!(v.helper_ref().bad == 1);
3790 assert!(v.helper_ref().unknown == 0);
3791 assert!(v.helper_ref().error == 0);
3792
3793 let mut message = Vec::new();
3794 let r = v.read_to_end(&mut message);
3795 assert!(r.is_err());
3796
3797 // Check that we only got a truncated message.
3798 assert!(v.message_processed());
3799 assert!(!message.is_empty());
3800 assert!(message.len() <= 1 * 1024 * 1024);
3801 assert!(message.iter().all(|&b| b == 42));
3802 assert!(v.helper_ref().good == 1);
3803 assert!(v.helper_ref().bad == 1);
3804 assert!(v.helper_ref().unknown == 0);
3805 assert!(v.helper_ref().error == 0);
3806
3807 // Test Decryptor.
3808 let h = VHelper::new(0, 0, 0, 0, vec![cert.clone()]);
3809 let mut v = DecryptorBuilder::from_bytes(&buf)?
3810 .buffer_size(2 * 2usize.pow(20))
3811 .with_policy(p, None, h)?;
3812
3813 assert!(!v.message_processed());
3814 assert!(v.helper_ref().good == 0);
3815 assert!(v.helper_ref().bad == 0);
3816 assert!(v.helper_ref().unknown == 0);
3817 assert!(v.helper_ref().error == 0);
3818
3819 let mut message = Vec::new();
3820
3821 v.read_to_end(&mut message).unwrap();
3822
3823 assert!(v.message_processed());
3824 assert_eq!(3 * 1024 * 1024, message.len());
3825 assert!(message.iter().all(|&b| b == 42));
3826 assert!(v.helper_ref().good == 1);
3827 assert!(v.helper_ref().bad == 0);
3828 assert!(v.helper_ref().unknown == 0);
3829 assert!(v.helper_ref().error == 0);
3830
3831 // Try the same, but this time we let .check() fail.
3832 let h = VHelper::new(0, 0, /* makes check() fail: */ 1, 0,
3833 vec![cert.clone()]);
3834 let mut v = DecryptorBuilder::from_bytes(&buf)?
3835 .buffer_size(2 * 2usize.pow(20))
3836 .with_policy(p, None, h)?;
3837
3838 assert!(!v.message_processed());
3839 assert!(v.helper_ref().good == 0);
3840 assert!(v.helper_ref().bad == 1);
3841 assert!(v.helper_ref().unknown == 0);
3842 assert!(v.helper_ref().error == 0);
3843
3844 let mut message = Vec::new();
3845 let r = v.read_to_end(&mut message);
3846 assert!(r.is_err());
3847
3848 // Check that we only got a truncated message.
3849 assert!(v.message_processed());
3850 assert!(!message.is_empty());
3851 assert!(message.len() <= 1 * 1024 * 1024);
3852 assert!(message.iter().all(|&b| b == 42));
3853 assert!(v.helper_ref().good == 1);
3854 assert!(v.helper_ref().bad == 1);
3855 assert!(v.helper_ref().unknown == 0);
3856 assert!(v.helper_ref().error == 0);
3857 Ok(())
3858 }
3859
3860 /// Checks that tampering with the MDC yields a uniform error
3861 /// response.
3862 #[test]
3863 fn issue_693() -> Result<()> {
3864 struct H();
3865 impl VerificationHelper for H {
3866 fn get_certs(&mut self, _ids: &[crate::KeyHandle])
3867 -> Result<Vec<Cert>> {
3868 Ok(Vec::new())
3869 }
3870
3871 fn check(&mut self, _: MessageStructure)
3872 -> Result<()> {
3873 Ok(())
3874 }
3875 }
3876 impl DecryptionHelper for H {
3877 fn decrypt(&mut self, _: &[PKESK], s: &[SKESK],
3878 _: Option<SymmetricAlgorithm>,
3879 decrypt: &mut dyn FnMut(Option<SymmetricAlgorithm>, &SessionKey) -> bool)
3880 -> Result<Option<Cert>>
3881 {
3882 let (algo, sk) = s[0].decrypt(&"123".into()).unwrap();
3883 let r = decrypt(algo, &sk);
3884 assert!(r);
3885 Ok(None)
3886 }
3887 }
3888
3889 fn check(m: &str) -> Result<()> {
3890 let doit = || -> Result<()> {
3891 let p = &P::new();
3892 let mut decryptor = DecryptorBuilder::from_bytes(m.as_bytes())?
3893 .with_policy(p, None, H())?;
3894 let mut b = Vec::new();
3895 decryptor.read_to_end(&mut b)?;
3896 Ok(())
3897 };
3898
3899 let e = doit().unwrap_err();
3900 match e.downcast::<io::Error>() {
3901 Ok(e) =>
3902 assert_eq!(e.into_inner().unwrap().downcast().unwrap(),
3903 Box::new(Error::ManipulatedMessage)),
3904 Err(e) =>
3905 assert_eq!(e.downcast::<Error>().unwrap(),
3906 Error::ManipulatedMessage),
3907 };
3908 Ok(())
3909 }
3910
3911 // Bad hash.
3912 check("-----BEGIN PGP MESSAGE-----
3913
3914wx4EBwMI7dKRUiOYGCUAWmzhiYGS8Pn/16QkyTous6vSOgFMcilte26C7kej
3915rKhvjj6uYNT+mt+L2Yg/FHFvpgVF3KfP0fb+9jZwgt4qpDkTMY7AWPTK6wXX
3916Jo8=
3917=LS8u
3918-----END PGP MESSAGE-----
3919")?;
3920
3921 // Bad header.
3922 check("-----BEGIN PGP MESSAGE-----
3923
3924wx4EBwMI7sPTdlgQwd8AogIcbF/hLVrYbvVbgj4EC6/SOgGNaCyffrR4Fuwl
3925Ft2w56/hB/gTaGEhCgDGXg8NiFGIURqF3eIwxxdKWghUutYmsGwqOZmdJ49a
39269gE=
3927=DzKF
3928-----END PGP MESSAGE-----
3929")?;
3930
3931 // Bad header matching other packet type.
3932 check("-----BEGIN PGP MESSAGE-----
3933
3934wx4EBwMIhpEGBh3v0oMAYgGcj+4CG1mcWQwmyGIDRdvSOgFSHlL2GZ1ZKeXS
393529kScqGg2U8N6ZF9vmj/9Sn7CFtO5PGXn2owQVsopeUSTofV3BNUBpxaBDCO
3936EK8=
3937=TgeJ
3938-----END PGP MESSAGE-----
3939")?;
3940
3941 Ok(())
3942 }
3943
3944 /// Tests samples of messages signed with the cleartext signature
3945 /// framework.
3946 #[test]
3947 fn csf_verification() -> Result<()> {
3948 struct H(Vec<Cert>, bool);
3949 impl VerificationHelper for H {
3950 fn get_certs(&mut self, _ids: &[crate::KeyHandle])
3951 -> Result<Vec<Cert>> {
3952 Ok(std::mem::take(&mut self.0))
3953 }
3954
3955 fn check(&mut self, m: MessageStructure)
3956 -> Result<()> {
3957 for (i, layer) in m.into_iter().enumerate() {
3958 assert_eq!(i, 0);
3959 if let MessageLayer::SignatureGroup { results } = layer {
3960 assert!(! results.is_empty());
3961 for result in results {
3962 result.unwrap();
3963 }
3964 self.1 = true;
3965 } else {
3966 panic!();
3967 }
3968 }
3969
3970 Ok(())
3971 }
3972 }
3973
3974 for (m, c) in [
3975 ("InRelease", "InRelease.signers.pgp"),
3976 ("InRelease.msft", "InRelease.msft.signers.pgp"),
3977 ("InRelease.v3", "InRelease.v3.signers.pgp"),
3978 ] {
3979 let certs = crate::cert::CertParser::from_bytes(
3980 crate::tests::key(c))?.collect::<Result<Vec<_>>>()?;
3981
3982 // The Microsoft cert uses SHA-1.
3983 let p = unsafe { &NP::new() };
3984 eprintln!("Parsing {}...", m);
3985 let mut verifier = VerifierBuilder::from_bytes(
3986 crate::tests::message(m))?
3987 .with_policy(p, None, H(certs, false))?;
3988 let mut b = Vec::new();
3989 verifier.read_to_end(&mut b)?;
3990 let h = verifier.into_helper();
3991 assert!(h.1);
3992 }
3993
3994 Ok(())
3995 }
3996
3997 /// Tests whether messages using the cleartext signature framework
3998 /// with multiple signatures and signers are correctly handled.
3999 #[test]
4000 fn csf_multiple_signers() -> Result<()> {
4001 struct H(bool);
4002 impl VerificationHelper for H {
4003 fn get_certs(&mut self, _ids: &[crate::KeyHandle])
4004 -> Result<Vec<Cert>> {
4005 crate::cert::CertParser::from_bytes(
4006 crate::tests::key("InRelease.signers.pgp"))?
4007 .collect()
4008 }
4009
4010 fn check(&mut self, m: MessageStructure)
4011 -> Result<()> {
4012 for (i, layer) in m.into_iter().enumerate() {
4013 assert_eq!(i, 0);
4014 if let MessageLayer::SignatureGroup { results } = layer {
4015 assert_eq!(results.len(), 3);
4016 for result in results {
4017 assert!(result.is_ok());
4018 }
4019 self.0 = true;
4020 } else {
4021 panic!();
4022 }
4023 }
4024
4025 Ok(())
4026 }
4027 }
4028
4029 let p = &P::new();
4030 let mut verifier = VerifierBuilder::from_bytes(
4031 crate::tests::message("InRelease"))?
4032 .with_policy(p, None, H(false))?;
4033 let mut b = Vec::new();
4034 verifier.read_to_end(&mut b)?;
4035 let h = verifier.into_helper();
4036 assert!(h.0);
4037 Ok(())
4038 }
4039
4040 /// This sample from our test suite generated using GnuPG.
4041 #[test]
4042 fn v4skesk_v1seip_aes128() -> Result<()> {
4043 test_password_encrypted_message(
4044 SymmetricAlgorithm::AES128,
4045 "messages/encrypted-aes128-password-123456789.pgp",
4046 "123456789",
4047 crate::tests::manifesto())
4048 }
4049
4050 /// This sample from our test suite generated using GnuPG.
4051 #[test]
4052 fn v4skesk_v1seip_aes192() -> Result<()> {
4053 test_password_encrypted_message(
4054 SymmetricAlgorithm::AES192,
4055 "messages/encrypted-aes192-password-123456.pgp",
4056 "123456",
4057 crate::tests::manifesto())
4058 }
4059
4060 /// This sample from our test suite generated using GnuPG.
4061 #[test]
4062 fn v4skesk_v1seip_aes256() -> Result<()> {
4063 test_password_encrypted_message(
4064 SymmetricAlgorithm::AES256,
4065 "messages/encrypted-aes256-password-123.pgp",
4066 "123",
4067 crate::tests::manifesto())
4068 }
4069
4070 fn test_password_encrypted_message(cipher: SymmetricAlgorithm,
4071 name: &str,
4072 password: &str,
4073 plaintext: &[u8])
4074 -> Result<()> {
4075 if ! cipher.is_supported() {
4076 eprintln!("Skipping test vector {:?}...", name);
4077 return Ok(());
4078 }
4079
4080 eprintln!("Test vector {:?}...", name);
4081
4082 let p = &P::new();
4083 let password: Password = String::from(password).into();
4084
4085 let h = VHelper::for_decryption(0, 0, 0, 0, vec![], vec![],
4086 vec![password]);
4087 let mut d = DecryptorBuilder::from_bytes(crate::tests::file(name))?
4088 .with_policy(p, None, h)?;
4089 assert!(d.message_processed());
4090
4091 let mut content = Vec::new();
4092 d.read_to_end(&mut content).unwrap();
4093 assert_eq!(&content, plaintext);
4094
4095 Ok(())
4096 }
4097
4098 /// Checks for a crash with signatures that are unaccounted for.
4099 #[test]
4100 fn unaccounted_signatures() -> Result<()> {
4101 let p = P::new();
4102 let m = b"-----BEGIN PGP MESSAGE-----
4103
4104wgoEAAAAAAB6CkAAxADLBq8AAKurq8IKBCC/CAAAAAD0sA==
4105=KRn6
4106-----END PGP MESSAGE-----
4107";
4108
4109 let mut h = VHelper::new(0, 0, 0, 0, vec![
4110 Cert::from_bytes(crate::tests::key("testy.pgp"))?,
4111 ]);
4112 h.error_out = false;
4113 VerifierBuilder::from_bytes(m)?
4114 .with_policy(&p, None, h)
4115 .unwrap();
4116 Ok(())
4117 }
4118
4119 /// Checks for a crash related to HashedReader's HashingMode.
4120 #[test]
4121 fn csf_hashing_mode_assertion_failure() -> Result<()> {
4122 let p = P::new();
4123 let m = b"-----BEGIN PGP SIGNED MESSAGE-----
4124---BEGIN PGP SIGNATURE
41250iHUEARYIAB0QCyUHMcArrZbte9msAndEO9clJG5wpCAEA2/";
4126
4127 let mut h = VHelper::new(0, 0, 0, 0, vec![
4128 Cert::from_bytes(crate::tests::key("testy.pgp"))?,
4129 ]);
4130 h.error_out = false;
4131 let _ = VerifierBuilder::from_bytes(m)?
4132 .with_policy(&p, None, h);
4133 Ok(())
4134 }
4135
4136 /// Checks for a crash related to HashedReader's assumptions about
4137 /// the number of signature groups.
4138 #[test]
4139 fn csf_sig_group_count_assertion_failure() -> Result<()> {
4140 let p = P::new();
4141 let m = b"-----BEGIN PGP SIGNED MESSAGE-----
4142-----BEGIN PGP SIGNATURE-----
4143xHUDBRY0WIQ+50WENDPP";
4144
4145 let mut h = VHelper::new(0, 0, 0, 0, vec![
4146 Cert::from_bytes(crate::tests::key("testy.pgp"))?,
4147 ]);
4148 h.error_out = false;
4149 let _ = VerifierBuilder::from_bytes(m)?
4150 .with_policy(&p, None, h);
4151 Ok(())
4152 }
4153
4154 /// Tests that the message structure is checked at the end of
4155 /// parsing the packet stream.
4156 #[test]
4157 fn message_grammar_check() -> Result<()> {
4158 let p = P::new();
4159 let certs = vec![Cert::from_bytes(crate::tests::key("neal.pgp"))?];
4160 let helper = VHelper::new(1, 0, 0, 0, certs.clone());
4161
4162 let pp = crate::PacketPile::from_bytes(
4163 crate::tests::message("signed-1-notarized-by-ed25519.pgp"))?;
4164 let mut buf = Vec::new();
4165 assert_eq!(pp.children().count(), 5);
4166 // Drop the last signature packet! Now the OPS and Signature
4167 // packets no longer bracket.
4168 pp.children().take(4).for_each(|p| p.serialize(&mut buf).unwrap());
4169
4170 // Test verifier.
4171 let do_it = || -> Result<()> {
4172 let v = VerifierBuilder::from_bytes(&buf)?
4173 .with_policy(&p, crate::frozen_time(), helper.clone())?;
4174 assert!(v.message_processed());
4175 Ok(())
4176 };
4177 assert!(do_it().is_err());
4178
4179 // Test decryptor.
4180 let do_it = || -> Result<()> {
4181 let v = DecryptorBuilder::from_bytes(&buf)?
4182 .with_policy(&p, crate::frozen_time(), helper)?;
4183 assert!(v.message_processed());
4184 Ok(())
4185 };
4186 assert!(do_it().is_err());
4187
4188 Ok(())
4189 }
4190
4191 /// Tests that an inline-signed message using two different hash
4192 /// algorithms verifies correctly.
4193 #[test]
4194 fn inline_signed_two_hashes() -> Result<()> {
4195 use crate::{
4196 types::{DataFormat, HashAlgorithm, SignatureType},
4197 packet::Literal,
4198 parse::SignatureBuilder,
4199 };
4200 let p = P::new();
4201 let cert = Cert::from_bytes(crate::tests::key("testy-private.pgp"))?;
4202 let helper = VHelper::new(0, 0, 0, 0, vec![cert.clone()]);
4203 let mut signer = cert.primary_key().key().clone().parts_into_secret()?
4204 .into_keypair()?;
4205 let msg = b"Hello, world!";
4206 let sig0 = SignatureBuilder::new(SignatureType::Binary)
4207 .set_signature_creation_time(crate::frozen_time())?
4208 .set_hash_algo(HashAlgorithm::SHA256)
4209 .sign_message(&mut signer, msg)?;
4210 let sig1 = SignatureBuilder::new(SignatureType::Binary)
4211 .set_signature_creation_time(crate::frozen_time())?
4212 .set_hash_algo(HashAlgorithm::SHA512)
4213 .sign_message(&mut signer, msg)?;
4214 let packets: Vec<Packet> = vec![
4215 OnePassSig::try_from(&sig0)?.into(),
4216 {
4217 let mut ops = OnePassSig::try_from(&sig1)?;
4218 ops.set_last(true);
4219 ops.into()
4220 },
4221 {
4222 let mut lit = Literal::new(DataFormat::Binary);
4223 lit.set_body((*msg).into());
4224 lit.into()
4225 },
4226 sig1.into(),
4227 sig0.into(),
4228 ];
4229 let mut buf = Vec::new();
4230 packets.iter().for_each(|p| p.serialize(&mut buf).unwrap());
4231 let v = VerifierBuilder::from_bytes(&buf)?
4232 .with_policy(&p, crate::frozen_time(), helper)?;
4233 assert!(v.message_processed());
4234 assert_eq!(v.helper_ref().good, 2);
4235
4236 Ok(())
4237 }
4238
4239 /// This sample packet is from RFC9580.
4240 #[test]
4241 fn v6skesk_v2seip_aes128_ocb() -> Result<()> {
4242 sample_skesk6_packet(
4243 SymmetricAlgorithm::AES128,
4244 AEADAlgorithm::OCB,
4245 "password",
4246 "crypto-refresh/v6skesk-aes128-ocb.pgp",
4247 b"Hello, world!")
4248 }
4249
4250 /// This sample packet is from RFC9580.
4251 #[test]
4252 fn v6skesk_v2seip_aes128_eax() -> Result<()> {
4253 sample_skesk6_packet(
4254 SymmetricAlgorithm::AES128,
4255 AEADAlgorithm::EAX,
4256 "password",
4257 "crypto-refresh/v6skesk-aes128-eax.pgp",
4258 b"Hello, world!")
4259 }
4260
4261 /// This sample packet is from RFC9580.
4262 #[test]
4263 fn v6skesk_v2seip_aes128_gcm() -> Result<()> {
4264 sample_skesk6_packet(
4265 SymmetricAlgorithm::AES128,
4266 AEADAlgorithm::GCM,
4267 "password",
4268 "crypto-refresh/v6skesk-aes128-gcm.pgp",
4269 b"Hello, world!")
4270 }
4271
4272 fn sample_skesk6_packet(cipher: SymmetricAlgorithm,
4273 aead: AEADAlgorithm,
4274 password: &str,
4275 name: &str,
4276 plaintext: &[u8])
4277 -> Result<()> {
4278 use crate::crypto::backend::{Backend, interface::Aead};
4279 if ! Backend::supports_algo_with_symmetric(aead, cipher)
4280 {
4281 eprintln!("Skipping test vector {:?}...", name);
4282 return Ok(());
4283 }
4284
4285 eprintln!("Test vector {:?}...", name);
4286
4287 let p = &P::new();
4288 let password: Password = String::from(password).into();
4289
4290 let h = VHelper::for_decryption(0, 0, 0, 0, vec![], vec![],
4291 vec![password]);
4292 let mut d = DecryptorBuilder::from_bytes(crate::tests::file(name))?
4293 .with_policy(p, None, h)?;
4294 assert!(d.message_processed());
4295
4296 let mut content = Vec::new();
4297 d.read_to_end(&mut content).unwrap();
4298 assert_eq!(&content, plaintext);
4299
4300 Ok(())
4301 }
4302}