deltachat/
e2ee.rs

1//! End-to-end encryption support.
2
3use std::io::Cursor;
4
5use anyhow::Result;
6use mail_builder::mime::MimePart;
7
8use crate::aheader::{Aheader, EncryptPreference};
9use crate::context::Context;
10use crate::key::{SignedPublicKey, load_self_public_key, load_self_secret_key};
11use crate::pgp;
12
13#[derive(Debug)]
14pub struct EncryptHelper {
15    pub prefer_encrypt: EncryptPreference,
16    pub addr: String,
17    pub public_key: SignedPublicKey,
18}
19
20impl EncryptHelper {
21    pub async fn new(context: &Context) -> Result<EncryptHelper> {
22        let prefer_encrypt = EncryptPreference::Mutual;
23        let addr = context.get_primary_self_addr().await?;
24        let public_key = load_self_public_key(context).await?;
25
26        Ok(EncryptHelper {
27            prefer_encrypt,
28            addr,
29            public_key,
30        })
31    }
32
33    pub fn get_aheader(&self) -> Aheader {
34        Aheader {
35            addr: self.addr.clone(),
36            public_key: self.public_key.clone(),
37            prefer_encrypt: self.prefer_encrypt,
38            verified: false,
39        }
40    }
41
42    /// Tries to encrypt the passed in `mail`.
43    pub async fn encrypt(
44        self,
45        context: &Context,
46        keyring: Vec<SignedPublicKey>,
47        mail_to_encrypt: MimePart<'static>,
48        compress: bool,
49    ) -> Result<String> {
50        let sign_key = load_self_secret_key(context).await?;
51
52        let mut raw_message = Vec::new();
53        let cursor = Cursor::new(&mut raw_message);
54        mail_to_encrypt.clone().write_part(cursor).ok();
55
56        let ctext = pgp::pk_encrypt(raw_message, keyring, Some(sign_key), compress).await?;
57
58        Ok(ctext)
59    }
60
61    /// Signs the passed-in `mail` using the private key from `context`.
62    /// Returns the payload and the signature.
63    pub async fn sign(self, context: &Context, mail: &MimePart<'static>) -> Result<String> {
64        let sign_key = load_self_secret_key(context).await?;
65        let mut buffer = Vec::new();
66        mail.clone().write_part(&mut buffer)?;
67        let signature = pgp::pk_calc_signature(buffer, &sign_key)?;
68        Ok(signature)
69    }
70}
71
72/// Ensures a private key exists for the configured user.
73///
74/// Normally the private key is generated when the first message is
75/// sent but in a few locations there are no such guarantees,
76/// e.g. when exporting keys, and calling this function ensures a
77/// private key will be present.
78// TODO, remove this once deltachat::key::Key no longer exists.
79pub async fn ensure_secret_key_exists(context: &Context) -> Result<()> {
80    load_self_public_key(context).await?;
81    Ok(())
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::chat::send_text_msg;
88    use crate::config::Config;
89    use crate::message::Message;
90    use crate::receive_imf::receive_imf;
91    use crate::test_utils::{TestContext, TestContextManager};
92
93    mod ensure_secret_key_exists {
94        use super::*;
95
96        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
97        async fn test_prexisting() {
98            let t = TestContext::new_alice().await;
99            assert!(ensure_secret_key_exists(&t).await.is_ok());
100        }
101
102        #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
103        async fn test_not_configured() {
104            let t = TestContext::new().await;
105            assert!(ensure_secret_key_exists(&t).await.is_err());
106        }
107    }
108
109    #[test]
110    fn test_mailmime_parse() {
111        let plain = b"Chat-Disposition-Notification-To: hello@world.de
112Chat-Group-ID: CovhGgau8M-
113Chat-Group-Name: Delta Chat Dev
114Subject: =?utf-8?Q?Chat=3A?= Delta Chat =?utf-8?Q?Dev=3A?= sidenote for
115 =?utf-8?Q?all=3A?= rust core master ...
116Content-Type: text/plain; charset=\"utf-8\"; protected-headers=\"v1\"
117Content-Transfer-Encoding: quoted-printable
118
119sidenote for all: things are trick atm recomm=
120end not to try to run with desktop or ios unless you are ready to hunt bugs
121
122-- =20
123Sent with my Delta Chat Messenger: https://delta.chat";
124        let mail = mailparse::parse_mail(plain).expect("failed to parse valid message");
125
126        assert_eq!(mail.headers.len(), 6);
127        assert!(
128            mail.get_body().unwrap().starts_with(
129                "sidenote for all: things are trick atm recommend not to try to run with desktop or ios unless you are ready to hunt bugs")
130        );
131    }
132
133    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
134    async fn test_chatmail_can_send_unencrypted() -> Result<()> {
135        let mut tcm = TestContextManager::new();
136        let bob = &tcm.bob().await;
137        bob.set_config_bool(Config::IsChatmail, true).await?;
138        let bob_chat_id = receive_imf(
139            bob,
140            b"From: alice@example.org\n\
141            To: bob@example.net\n\
142            Message-ID: <2222@example.org>\n\
143            Date: Sun, 22 Mar 3000 22:37:58 +0000\n\
144            \n\
145            Hello\n",
146            false,
147        )
148        .await?
149        .unwrap()
150        .chat_id;
151        bob_chat_id.accept(bob).await?;
152        send_text_msg(bob, bob_chat_id, "hi".to_string()).await?;
153        let sent_msg = bob.pop_sent_msg().await;
154        let msg = Message::load_from_db(bob, sent_msg.sender_msg_id).await?;
155        assert!(!msg.get_showpadlock());
156        Ok(())
157    }
158}