sequoia_openpgp/parse/
stream.rs

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