Skip to main content

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