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