deltachat/
decrypt.rs

1//! End-to-end decryption support.
2
3use std::collections::HashSet;
4
5use anyhow::Result;
6use mailparse::ParsedMail;
7
8use crate::key::{Fingerprint, SignedPublicKey, SignedSecretKey};
9use crate::pgp;
10
11/// Tries to decrypt a message, but only if it is structured as an Autocrypt message.
12///
13/// If successful and the message was encrypted,
14/// returns the decrypted and decompressed message.
15pub fn try_decrypt<'a>(
16    mail: &'a ParsedMail<'a>,
17    private_keyring: &'a [SignedSecretKey],
18    shared_secrets: &[String],
19) -> Result<Option<::pgp::composed::Message<'static>>> {
20    let Some(encrypted_data_part) = get_encrypted_mime(mail) else {
21        return Ok(None);
22    };
23
24    let data = encrypted_data_part.get_body_raw()?;
25    let msg = pgp::decrypt(data, private_keyring, shared_secrets)?;
26
27    Ok(Some(msg))
28}
29
30/// Returns a reference to the encrypted payload of a message.
31pub(crate) fn get_encrypted_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
32    get_autocrypt_mime(mail)
33        .or_else(|| get_mixed_up_mime(mail))
34        .or_else(|| get_attachment_mime(mail))
35}
36
37/// Returns a reference to the encrypted payload of a ["Mixed
38/// Up"][pgpmime-message-mangling] message.
39///
40/// According to [RFC 3156] encrypted messages should have
41/// `multipart/encrypted` MIME type and two parts, but Microsoft
42/// Exchange and ProtonMail IMAP/SMTP Bridge are known to mangle this
43/// structure by changing the type to `multipart/mixed` and prepending
44/// an empty part at the start.
45///
46/// ProtonMail IMAP/SMTP Bridge prepends a part literally saying
47/// "Empty Message", so we don't check its contents at all, checking
48/// only for `text/plain` type.
49///
50/// Returns `None` if the message is not a "Mixed Up" message.
51///
52/// [RFC 3156]: https://www.rfc-editor.org/info/rfc3156
53/// [pgpmime-message-mangling]: https://tools.ietf.org/id/draft-dkg-openpgp-pgpmime-message-mangling-00.html
54fn get_mixed_up_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
55    if mail.ctype.mimetype != "multipart/mixed" {
56        return None;
57    }
58    if let [first_part, second_part, third_part] = &mail.subparts[..] {
59        if first_part.ctype.mimetype == "text/plain"
60            && second_part.ctype.mimetype == "application/pgp-encrypted"
61            && third_part.ctype.mimetype == "application/octet-stream"
62        {
63            Some(third_part)
64        } else {
65            None
66        }
67    } else {
68        None
69    }
70}
71
72/// Returns a reference to the encrypted payload of a message turned into attachment.
73///
74/// Google Workspace has an option "Append footer" which appends standard footer defined
75/// by administrator to all outgoing messages. However, there is no plain text part in
76/// encrypted messages sent by Delta Chat, so Google Workspace turns the message into
77/// multipart/mixed MIME, where the first part is an empty plaintext part with a footer
78/// and the second part is the original encrypted message.
79fn get_attachment_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
80    if mail.ctype.mimetype != "multipart/mixed" {
81        return None;
82    }
83    if let [first_part, second_part] = &mail.subparts[..] {
84        if first_part.ctype.mimetype == "text/plain"
85            && second_part.ctype.mimetype == "multipart/encrypted"
86        {
87            get_autocrypt_mime(second_part)
88        } else {
89            None
90        }
91    } else {
92        None
93    }
94}
95
96/// Returns a reference to the encrypted payload of a valid PGP/MIME message.
97///
98/// Returns `None` if the message is not a valid PGP/MIME message.
99fn get_autocrypt_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
100    if mail.ctype.mimetype != "multipart/encrypted" {
101        return None;
102    }
103    if let [first_part, second_part] = &mail.subparts[..] {
104        if first_part.ctype.mimetype == "application/pgp-encrypted"
105            && second_part.ctype.mimetype == "application/octet-stream"
106        {
107            Some(second_part)
108        } else {
109            None
110        }
111    } else {
112        None
113    }
114}
115
116/// Validates signatures of Multipart/Signed message part, as defined in RFC 1847.
117///
118/// Returns the signed part and the set of key
119/// fingerprints for which there is a valid signature.
120///
121/// Returns None if the message is not Multipart/Signed or doesn't contain necessary parts.
122pub(crate) fn validate_detached_signature<'a, 'b>(
123    mail: &'a ParsedMail<'b>,
124    public_keyring_for_validate: &[SignedPublicKey],
125) -> Option<(&'a ParsedMail<'b>, HashSet<Fingerprint>)> {
126    if mail.ctype.mimetype != "multipart/signed" {
127        return None;
128    }
129
130    if let [first_part, second_part] = &mail.subparts[..] {
131        // First part is the content, second part is the signature.
132        let content = first_part.raw_bytes;
133        let ret_valid_signatures = match second_part.get_body_raw() {
134            Ok(signature) => pgp::pk_validate(content, &signature, public_keyring_for_validate)
135                .unwrap_or_default(),
136            Err(_) => Default::default(),
137        };
138        Some((first_part, ret_valid_signatures))
139    } else {
140        None
141    }
142}
143
144#[cfg(test)]
145mod tests {
146    use super::*;
147    use crate::receive_imf::receive_imf;
148    use crate::test_utils::TestContext;
149
150    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
151    async fn test_mixed_up_mime() -> Result<()> {
152        // "Mixed Up" mail as received when sending an encrypted
153        // message using Delta Chat Desktop via ProtonMail IMAP/SMTP
154        // Bridge.
155        let mixed_up_mime = include_bytes!("../test-data/message/protonmail-mixed-up.eml");
156        let mail = mailparse::parse_mail(mixed_up_mime)?;
157        assert!(get_autocrypt_mime(&mail).is_none());
158        assert!(get_mixed_up_mime(&mail).is_some());
159        assert!(get_attachment_mime(&mail).is_none());
160
161        // Same "Mixed Up" mail repaired by Thunderbird 78.9.0.
162        //
163        // It added `X-Enigmail-Info: Fixed broken PGP/MIME message`
164        // header although the repairing is done by the built-in
165        // OpenPGP support, not Enigmail.
166        let repaired_mime = include_bytes!("../test-data/message/protonmail-repaired.eml");
167        let mail = mailparse::parse_mail(repaired_mime)?;
168        assert!(get_autocrypt_mime(&mail).is_some());
169        assert!(get_mixed_up_mime(&mail).is_none());
170        assert!(get_attachment_mime(&mail).is_none());
171
172        // Another form of "Mixed Up" mail created by Google Workspace,
173        // where original message is turned into attachment to empty plaintext message.
174        let attachment_mime = include_bytes!("../test-data/message/google-workspace-mixed-up.eml");
175        let mail = mailparse::parse_mail(attachment_mime)?;
176        assert!(get_autocrypt_mime(&mail).is_none());
177        assert!(get_mixed_up_mime(&mail).is_none());
178        assert!(get_attachment_mime(&mail).is_some());
179
180        let bob = TestContext::new_bob().await;
181        receive_imf(&bob, attachment_mime, false).await?;
182        let msg = bob.get_last_msg().await;
183        // Subject should be prepended because the attachment doesn't have "Chat-Version".
184        assert_eq!(msg.text, "Hello, Bob! – Hello from Thunderbird!");
185
186        Ok(())
187    }
188
189    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
190    async fn test_mixed_up_mime_long() -> Result<()> {
191        // Long "mixed-up" mail as received when sending an encrypted message using Delta Chat
192        // Desktop via MS Exchange (actually made with TB though).
193        let mixed_up_mime = include_bytes!("../test-data/message/mixed-up-long.eml");
194        let bob = TestContext::new_bob().await;
195        receive_imf(&bob, mixed_up_mime, false).await?;
196        let msg = bob.get_last_msg().await;
197        assert!(!msg.get_text().is_empty());
198        assert!(msg.has_html());
199        assert!(msg.id.get_html(&bob).await?.unwrap().len() > 40000);
200        Ok(())
201    }
202}