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