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