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