deltachat/
decrypt.rs

1//! Helper functions for decryption.
2//! The actual decryption is done in the [`crate::pgp`] module.
3
4use std::collections::HashSet;
5use std::io::Cursor;
6
7use anyhow::{Context as _, Result, bail};
8use mailparse::ParsedMail;
9use pgp::composed::Esk;
10use pgp::composed::Message;
11use pgp::composed::PlainSessionKey;
12use pgp::composed::SignedSecretKey;
13use pgp::composed::decrypt_session_key_with_password;
14use pgp::packet::SymKeyEncryptedSessionKey;
15use pgp::types::Password;
16use pgp::types::StringToKey;
17
18use crate::chat::ChatId;
19use crate::constants::Chattype;
20use crate::contact::ContactId;
21use crate::context::Context;
22use crate::key::{Fingerprint, SignedPublicKey, load_self_secret_keyring};
23use crate::token::Namespace;
24
25/// Tries to decrypt the message,
26/// returning a tuple of `(decrypted message, fingerprint)`.
27///
28/// If the message wasn't encrypted, returns `Ok(None)`.
29///
30/// If the message was asymmetrically encrypted, returns `Ok((decrypted message, None))`.
31///
32/// If the message was symmetrically encrypted, returns `Ok((decrypted message, Some(fingerprint)))`,
33/// where `fingerprint` denotes which contact is allowed to send encrypted with this symmetric secret.
34/// If the message is not signed by `fingerprint`, it must be dropped.
35///
36/// Otherwise, Eve could send a message to Alice
37/// encrypted with the symmetric secret of someone else's broadcast channel.
38/// If Alice sends an answer (or read receipt),
39/// then Eve would know that Alice is in the broadcast channel.
40pub(crate) async fn decrypt(
41    context: &Context,
42    mail: &mailparse::ParsedMail<'_>,
43) -> Result<Option<(Message<'static>, Option<String>)>> {
44    // `pgp::composed::Message` is huge (>4kb), so, make sure that it is in a Box when held over an await point
45    let Some(msg) = get_encrypted_pgp_message_boxed(mail)? else {
46        return Ok(None);
47    };
48    let expected_sender_fingerprint: Option<String>;
49
50    let plain = if let Message::Encrypted { esk, .. } = &*msg
51        // We only allow one ESK for symmetrically encrypted messages
52        // to avoid dealing with messages that are encrypted to multiple symmetric keys
53        // or a mix of symmetric and asymmetric keys:
54        && let [Esk::SymKeyEncryptedSessionKey(esk)] = &esk[..]
55    {
56        check_symmetric_encryption(esk)?;
57        let (psk, fingerprint) = decrypt_session_key_symmetrically(context, esk)
58            .await
59            .context("decrypt_session_key_symmetrically")?;
60        expected_sender_fingerprint = fingerprint;
61
62        tokio::task::spawn_blocking(move || -> Result<Message<'_>> {
63            let plain = msg
64                .decrypt_with_session_key(psk)
65                .context("decrypt_with_session_key")?;
66
67            let plain: Message<'static> = plain.decompress()?;
68            Ok(plain)
69        })
70        .await??
71    } else {
72        // Message is asymmetrically encrypted
73        let secret_keys: Vec<SignedSecretKey> = load_self_secret_keyring(context).await?;
74        expected_sender_fingerprint = None;
75
76        tokio::task::spawn_blocking(move || -> Result<Message<'_>> {
77            let empty_pw = Password::empty();
78            let secret_keys: Vec<&SignedSecretKey> = secret_keys.iter().collect();
79            let plain = msg
80                .decrypt_with_keys(vec![&empty_pw], secret_keys)
81                .context("decrypt_with_keys")?;
82
83            let plain: Message<'static> = plain.decompress()?;
84            Ok(plain)
85        })
86        .await??
87    };
88
89    Ok(Some((plain, expected_sender_fingerprint)))
90}
91
92async fn decrypt_session_key_symmetrically(
93    context: &Context,
94    esk: &SymKeyEncryptedSessionKey,
95) -> Result<(PlainSessionKey, Option<String>)> {
96    let query_only = true;
97    context
98        .sql
99        .call(query_only, |conn| {
100            // First, try decrypting using AUTH tokens from scanned QR codes, stored in the bobstate,
101            // because usually there will only be 1 or 2 of it, so, it should be fast
102            let res: Option<(PlainSessionKey, String)> = try_decrypt_with_bobstate(esk, conn)?;
103            if let Some((plain_session_key, fingerprint)) = res {
104                return Ok((plain_session_key, Some(fingerprint)));
105            }
106
107            // Then, try decrypting using broadcast secrets
108            let res: Option<(PlainSessionKey, Option<String>)> =
109                try_decrypt_with_broadcast_secret(esk, conn)?;
110            if let Some((plain_session_key, fingerprint)) = res {
111                return Ok((plain_session_key, fingerprint));
112            }
113
114            // Finally, try decrypting using own AUTH tokens
115            // There can be a lot of AUTH tokens,
116            // because a new one is generated every time a QR code is shown
117            let res: Option<PlainSessionKey> = try_decrypt_with_auth_token(esk, conn)?;
118            if let Some(plain_session_key) = res {
119                return Ok((plain_session_key, None));
120            }
121
122            bail!("Could not find symmetric secret for session key")
123        })
124        .await
125}
126
127fn try_decrypt_with_bobstate(
128    esk: &SymKeyEncryptedSessionKey,
129    conn: &mut rusqlite::Connection,
130) -> Result<Option<(PlainSessionKey, String)>> {
131    let mut stmt = conn.prepare("SELECT invite FROM bobstate")?;
132    let mut rows = stmt.query(())?;
133    while let Some(row) = rows.next()? {
134        let invite: crate::securejoin::QrInvite = row.get(0)?;
135        let authcode = invite.authcode().to_string();
136        if let Ok(psk) = decrypt_session_key_with_password(esk, &Password::from(authcode)) {
137            let fingerprint = invite.fingerprint().hex();
138            return Ok(Some((psk, fingerprint)));
139        }
140    }
141    Ok(None)
142}
143
144fn try_decrypt_with_broadcast_secret(
145    esk: &SymKeyEncryptedSessionKey,
146    conn: &mut rusqlite::Connection,
147) -> Result<Option<(PlainSessionKey, Option<String>)>> {
148    let Some((psk, chat_id)) = try_decrypt_with_broadcast_secret_inner(esk, conn)? else {
149        return Ok(None);
150    };
151    let chat_type: Chattype =
152        conn.query_one("SELECT type FROM chats WHERE id=?", (chat_id,), |row| {
153            row.get(0)
154        })?;
155    let fp: Option<String> = if chat_type == Chattype::OutBroadcast {
156        // An attacker who knows the secret will also know who owns it,
157        // and it's easiest code-wise to just return None here.
158        // But we could alternatively return the self fingerprint here
159        None
160    } else if chat_type == Chattype::InBroadcast {
161        let contact_id: ContactId = conn
162            .query_one(
163                "SELECT contact_id FROM chats_contacts WHERE chat_id=? AND contact_id>9",
164                (chat_id,),
165                |row| row.get(0),
166            )
167            .context("Find InBroadcast owner")?;
168        let fp = conn
169            .query_one(
170                "SELECT fingerprint FROM contacts WHERE id=?",
171                (contact_id,),
172                |row| row.get(0),
173            )
174            .context("Find owner fingerprint")?;
175        Some(fp)
176    } else {
177        bail!("Chat {chat_id} is not a broadcast but {chat_type}")
178    };
179    Ok(Some((psk, fp)))
180}
181
182fn try_decrypt_with_broadcast_secret_inner(
183    esk: &SymKeyEncryptedSessionKey,
184    conn: &mut rusqlite::Connection,
185) -> Result<Option<(PlainSessionKey, ChatId)>> {
186    let mut stmt = conn.prepare("SELECT secret, chat_id FROM broadcast_secrets")?;
187    let mut rows = stmt.query(())?;
188    while let Some(row) = rows.next()? {
189        let secret: String = row.get(0)?;
190        if let Ok(psk) = decrypt_session_key_with_password(esk, &Password::from(secret)) {
191            let chat_id: ChatId = row.get(1)?;
192            return Ok(Some((psk, chat_id)));
193        }
194    }
195    Ok(None)
196}
197
198fn try_decrypt_with_auth_token(
199    esk: &SymKeyEncryptedSessionKey,
200    conn: &mut rusqlite::Connection,
201) -> Result<Option<PlainSessionKey>> {
202    // ORDER BY id DESC to query the most-recently saved tokens are returned first.
203    // This improves performance when Bob scans a QR code that was just created.
204    let mut stmt = conn.prepare("SELECT token FROM tokens WHERE namespc=? ORDER BY id DESC")?;
205    let mut rows = stmt.query((Namespace::Auth,))?;
206    while let Some(row) = rows.next()? {
207        let token: String = row.get(0)?;
208        if let Ok(psk) = decrypt_session_key_with_password(esk, &Password::from(token)) {
209            return Ok(Some(psk));
210        }
211    }
212    Ok(None)
213}
214
215/// Returns Ok(()) if we want to try symmetrically decrypting the message,
216/// and Err with a reason if symmetric decryption should not be tried.
217///
218/// A DoS attacker could send a message with a lot of encrypted session keys,
219/// all of which use a very hard-to-compute string2key algorithm.
220/// We would then try to decrypt all of the encrypted session keys
221/// with all of the known shared secrets.
222/// In order to prevent this, we do not try to symmetrically decrypt messages
223/// that use a string2key algorithm other than 'Salted'.
224pub(crate) fn check_symmetric_encryption(esk: &SymKeyEncryptedSessionKey) -> Result<()> {
225    match esk.s2k() {
226        Some(StringToKey::Salted { .. }) => Ok(()),
227        _ => bail!("unsupported string2key algorithm"),
228    }
229}
230
231/// Turns a [`ParsedMail`] into [`pgp::composed::Message`].
232/// [`pgp::composed::Message`] is huge (over 4kb),
233/// so, it is put on the heap using [`Box`].
234pub fn get_encrypted_pgp_message_boxed<'a>(
235    mail: &'a ParsedMail<'a>,
236) -> Result<Option<Box<Message<'static>>>> {
237    let Some(encrypted_data_part) = get_encrypted_mime(mail) else {
238        return Ok(None);
239    };
240    let data = encrypted_data_part.get_body_raw()?;
241    let cursor = Cursor::new(data);
242    let (msg, _headers) = Message::from_armor(cursor)?;
243    Ok(Some(Box::new(msg)))
244}
245
246/// Returns a reference to the encrypted payload of a message.
247pub fn get_encrypted_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
248    get_autocrypt_mime(mail)
249        .or_else(|| get_mixed_up_mime(mail))
250        .or_else(|| get_attachment_mime(mail))
251}
252
253/// Returns a reference to the encrypted payload of a ["Mixed
254/// Up"][pgpmime-message-mangling] message.
255///
256/// According to [RFC 3156] encrypted messages should have
257/// `multipart/encrypted` MIME type and two parts, but Microsoft
258/// Exchange and ProtonMail IMAP/SMTP Bridge are known to mangle this
259/// structure by changing the type to `multipart/mixed` and prepending
260/// an empty part at the start.
261///
262/// ProtonMail IMAP/SMTP Bridge prepends a part literally saying
263/// "Empty Message", so we don't check its contents at all, checking
264/// only for `text/plain` type.
265///
266/// Returns `None` if the message is not a "Mixed Up" message.
267///
268/// [RFC 3156]: https://www.rfc-editor.org/info/rfc3156
269/// [pgpmime-message-mangling]: https://tools.ietf.org/id/draft-dkg-openpgp-pgpmime-message-mangling-00.html
270fn get_mixed_up_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
271    if mail.ctype.mimetype != "multipart/mixed" {
272        return None;
273    }
274    if let [first_part, second_part, third_part] = &mail.subparts[..] {
275        if first_part.ctype.mimetype == "text/plain"
276            && second_part.ctype.mimetype == "application/pgp-encrypted"
277            && third_part.ctype.mimetype == "application/octet-stream"
278        {
279            Some(third_part)
280        } else {
281            None
282        }
283    } else {
284        None
285    }
286}
287
288/// Returns a reference to the encrypted payload of a message turned into attachment.
289///
290/// Google Workspace has an option "Append footer" which appends standard footer defined
291/// by administrator to all outgoing messages. However, there is no plain text part in
292/// encrypted messages sent by Delta Chat, so Google Workspace turns the message into
293/// multipart/mixed MIME, where the first part is an empty plaintext part with a footer
294/// and the second part is the original encrypted message.
295fn get_attachment_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
296    if mail.ctype.mimetype != "multipart/mixed" {
297        return None;
298    }
299    if let [first_part, second_part] = &mail.subparts[..] {
300        if first_part.ctype.mimetype == "text/plain"
301            && second_part.ctype.mimetype == "multipart/encrypted"
302        {
303            get_autocrypt_mime(second_part)
304        } else {
305            None
306        }
307    } else {
308        None
309    }
310}
311
312/// Returns a reference to the encrypted payload of a valid PGP/MIME message.
313///
314/// Returns `None` if the message is not a valid PGP/MIME message.
315fn get_autocrypt_mime<'a, 'b>(mail: &'a ParsedMail<'b>) -> Option<&'a ParsedMail<'b>> {
316    if mail.ctype.mimetype != "multipart/encrypted" {
317        return None;
318    }
319    if let [first_part, second_part] = &mail.subparts[..] {
320        if first_part.ctype.mimetype == "application/pgp-encrypted"
321            && second_part.ctype.mimetype == "application/octet-stream"
322        {
323            Some(second_part)
324        } else {
325            None
326        }
327    } else {
328        None
329    }
330}
331
332/// Validates signatures of Multipart/Signed message part, as defined in RFC 1847.
333///
334/// Returns the signed part and the set of key
335/// fingerprints for which there is a valid signature.
336///
337/// Returns None if the message is not Multipart/Signed or doesn't contain necessary parts.
338pub(crate) fn validate_detached_signature<'a, 'b>(
339    mail: &'a ParsedMail<'b>,
340    public_keyring_for_validate: &[SignedPublicKey],
341) -> Option<(&'a ParsedMail<'b>, HashSet<Fingerprint>)> {
342    if mail.ctype.mimetype != "multipart/signed" {
343        return None;
344    }
345
346    if let [first_part, second_part] = &mail.subparts[..] {
347        // First part is the content, second part is the signature.
348        let content = first_part.raw_bytes;
349        let ret_valid_signatures = match second_part.get_body_raw() {
350            Ok(signature) => {
351                crate::pgp::pk_validate(content, &signature, public_keyring_for_validate)
352                    .unwrap_or_default()
353            }
354            Err(_) => Default::default(),
355        };
356        Some((first_part, ret_valid_signatures))
357    } else {
358        None
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365    use crate::receive_imf::receive_imf;
366    use crate::test_utils::TestContext;
367
368    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
369    async fn test_mixed_up_mime() -> Result<()> {
370        // "Mixed Up" mail as received when sending an encrypted
371        // message using Delta Chat Desktop via ProtonMail IMAP/SMTP
372        // Bridge.
373        let mixed_up_mime = include_bytes!("../test-data/message/protonmail-mixed-up.eml");
374        let mail = mailparse::parse_mail(mixed_up_mime)?;
375        assert!(get_autocrypt_mime(&mail).is_none());
376        assert!(get_mixed_up_mime(&mail).is_some());
377        assert!(get_attachment_mime(&mail).is_none());
378
379        // Same "Mixed Up" mail repaired by Thunderbird 78.9.0.
380        //
381        // It added `X-Enigmail-Info: Fixed broken PGP/MIME message`
382        // header although the repairing is done by the built-in
383        // OpenPGP support, not Enigmail.
384        let repaired_mime = include_bytes!("../test-data/message/protonmail-repaired.eml");
385        let mail = mailparse::parse_mail(repaired_mime)?;
386        assert!(get_autocrypt_mime(&mail).is_some());
387        assert!(get_mixed_up_mime(&mail).is_none());
388        assert!(get_attachment_mime(&mail).is_none());
389
390        // Another form of "Mixed Up" mail created by Google Workspace,
391        // where original message is turned into attachment to empty plaintext message.
392        let attachment_mime = include_bytes!("../test-data/message/google-workspace-mixed-up.eml");
393        let mail = mailparse::parse_mail(attachment_mime)?;
394        assert!(get_autocrypt_mime(&mail).is_none());
395        assert!(get_mixed_up_mime(&mail).is_none());
396        assert!(get_attachment_mime(&mail).is_some());
397
398        let bob = TestContext::new_bob().await;
399        receive_imf(&bob, attachment_mime, false).await?;
400        let msg = bob.get_last_msg().await;
401        // Subject should be prepended because the attachment doesn't have "Chat-Version".
402        assert_eq!(msg.text, "Hello, Bob! – Hello from Thunderbird!");
403
404        Ok(())
405    }
406
407    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
408    async fn test_mixed_up_mime_long() -> Result<()> {
409        // Long "mixed-up" mail as received when sending an encrypted message using Delta Chat
410        // Desktop via MS Exchange (actually made with TB though).
411        let mixed_up_mime = include_bytes!("../test-data/message/mixed-up-long.eml");
412        let bob = TestContext::new_bob().await;
413        receive_imf(&bob, mixed_up_mime, false).await?;
414        let msg = bob.get_last_msg().await;
415        assert!(!msg.get_text().is_empty());
416        assert!(msg.has_html());
417        assert!(msg.id.get_html(&bob).await?.unwrap().len() > 40000);
418        Ok(())
419    }
420}