deltachat/imex/
key_transfer.rs

1//! # Key transfer via Autocrypt Setup Message.
2use std::io::BufReader;
3
4use anyhow::{Result, bail, ensure};
5
6use crate::blob::BlobObject;
7use crate::chat::{self, ChatId};
8use crate::config::Config;
9use crate::constants::{ASM_BODY, ASM_SUBJECT};
10use crate::contact::ContactId;
11use crate::context::Context;
12use crate::imex::set_self_key;
13use crate::key::{DcKey, load_self_secret_key};
14use crate::message::{Message, MsgId, Viewtype};
15use crate::mimeparser::SystemMessage;
16use crate::param::Param;
17use crate::pgp;
18use crate::tools::open_file_std;
19
20/// Initiates key transfer via Autocrypt Setup Message.
21///
22/// Returns setup code.
23pub async fn initiate_key_transfer(context: &Context) -> Result<String> {
24    let setup_code = create_setup_code(context);
25    /* this may require a keypair to be created. this may take a second ... */
26    let setup_file_content = render_setup_file(context, &setup_code).await?;
27    /* encrypting may also take a while ... */
28    let setup_file_blob = BlobObject::create_and_deduplicate_from_bytes(
29        context,
30        setup_file_content.as_bytes(),
31        "autocrypt-setup-message.html",
32    )?;
33
34    let chat_id = ChatId::create_for_contact(context, ContactId::SELF).await?;
35    let mut msg = Message::new(Viewtype::File);
36    msg.param.set(Param::File, setup_file_blob.as_name());
37    msg.param
38        .set(Param::Filename, "autocrypt-setup-message.html");
39    msg.subject = ASM_SUBJECT.to_owned();
40    msg.param
41        .set(Param::MimeType, "application/autocrypt-setup");
42    msg.param.set_cmd(SystemMessage::AutocryptSetupMessage);
43    msg.force_plaintext();
44    msg.param.set_int(Param::SkipAutocrypt, 1);
45
46    // Enable BCC-self, because transferring a key
47    // means we have a multi-device setup.
48    context.set_config_bool(Config::BccSelf, true).await?;
49
50    chat::send_msg(context, chat_id, &mut msg).await?;
51    Ok(setup_code)
52}
53
54/// Continue key transfer via Autocrypt Setup Message.
55///
56/// `msg_id` is the ID of the received Autocrypt Setup Message.
57/// `setup_code` is the code entered by the user.
58pub async fn continue_key_transfer(
59    context: &Context,
60    msg_id: MsgId,
61    setup_code: &str,
62) -> Result<()> {
63    ensure!(!msg_id.is_special(), "wrong id");
64
65    let msg = Message::load_from_db(context, msg_id).await?;
66    ensure!(
67        msg.is_setupmessage(),
68        "Message is no Autocrypt Setup Message."
69    );
70
71    if let Some(filename) = msg.get_file(context) {
72        let file = open_file_std(context, filename)?;
73        let sc = normalize_setup_code(setup_code);
74        let armored_key = decrypt_setup_file(&sc, BufReader::new(file)).await?;
75        set_self_key(context, &armored_key).await?;
76        context.set_config_bool(Config::BccSelf, true).await?;
77
78        Ok(())
79    } else {
80        bail!("Message is no Autocrypt Setup Message.");
81    }
82}
83
84/// Renders HTML body of a setup file message.
85///
86/// The `passphrase` must be at least 2 characters long.
87pub async fn render_setup_file(context: &Context, passphrase: &str) -> Result<String> {
88    let passphrase_begin = if let Some(passphrase_begin) = passphrase.get(..2) {
89        passphrase_begin
90    } else {
91        bail!("Passphrase must be at least 2 chars long.");
92    };
93    let private_key = load_self_secret_key(context).await?;
94    let ac_headers = Some(("Autocrypt-Prefer-Encrypt", "mutual"));
95    let private_key_asc = private_key.to_asc(ac_headers);
96    let encr = pgp::symm_encrypt_autocrypt_setup(passphrase, private_key_asc.into_bytes())
97        .await?
98        .replace('\n', "\r\n");
99
100    let replacement = format!(
101        concat!(
102            "-----BEGIN PGP MESSAGE-----\r\n",
103            "Passphrase-Format: numeric9x4\r\n",
104            "Passphrase-Begin: {}"
105        ),
106        passphrase_begin
107    );
108    let pgp_msg = encr.replace("-----BEGIN PGP MESSAGE-----", &replacement);
109
110    let msg_subj = ASM_SUBJECT;
111    let msg_body = ASM_BODY.to_string();
112    let msg_body_html = msg_body.replace('\r', "").replace('\n', "<br>");
113    Ok(format!(
114        concat!(
115            "<!DOCTYPE html>\r\n",
116            "<html>\r\n",
117            "  <head>\r\n",
118            "    <title>{}</title>\r\n",
119            "  </head>\r\n",
120            "  <body>\r\n",
121            "    <h1>{}</h1>\r\n",
122            "    <p>{}</p>\r\n",
123            "    <pre>\r\n{}\r\n</pre>\r\n",
124            "  </body>\r\n",
125            "</html>\r\n"
126        ),
127        msg_subj, msg_subj, msg_body_html, pgp_msg
128    ))
129}
130
131/// Creates a new setup code for Autocrypt Setup Message.
132#[expect(clippy::arithmetic_side_effects)]
133fn create_setup_code(_context: &Context) -> String {
134    let mut random_val: u16;
135    let mut ret = String::new();
136
137    for i in 0..9 {
138        loop {
139            random_val = rand::random();
140            if random_val as usize <= 60000 {
141                break;
142            }
143        }
144        random_val = (random_val as usize % 10000) as u16;
145        ret += &format!(
146            "{}{:04}",
147            if 0 != i { "-" } else { "" },
148            random_val as usize
149        );
150    }
151
152    ret
153}
154
155async fn decrypt_setup_file<T: std::fmt::Debug + std::io::BufRead + Send + 'static>(
156    passphrase: &str,
157    file: T,
158) -> Result<String> {
159    let plain_bytes = pgp::symm_decrypt(passphrase, file).await?;
160    let plain_text = std::string::String::from_utf8(plain_bytes)?;
161
162    Ok(plain_text)
163}
164
165fn normalize_setup_code(s: &str) -> String {
166    let mut out = String::new();
167    for c in s.chars() {
168        if c.is_ascii_digit() {
169            out.push(c);
170            if let 4 | 9 | 14 | 19 | 24 | 29 | 34 | 39 = out.len() {
171                out += "-"
172            }
173        }
174    }
175    out
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    use crate::pgp::{HEADER_AUTOCRYPT, HEADER_SETUPCODE, split_armored_data};
183    use crate::receive_imf::receive_imf;
184    use crate::test_utils::{TestContext, TestContextManager};
185    use ::pgp::armor::BlockType;
186
187    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
188    async fn test_render_setup_file() {
189        let t = TestContext::new_alice().await;
190        let msg = render_setup_file(&t, "hello").await.unwrap();
191        println!("{}", &msg);
192        // Check some substrings, indicating things got substituted.
193        assert!(msg.contains("<title>Autocrypt Setup Message</title"));
194        assert!(msg.contains("<h1>Autocrypt Setup Message</h1>"));
195        assert!(msg.contains("<p>This is the Autocrypt Setup Message used to"));
196        assert!(msg.contains("-----BEGIN PGP MESSAGE-----\r\n"));
197        assert!(msg.contains("Passphrase-Format: numeric9x4\r\n"));
198        assert!(msg.contains("Passphrase-Begin: he\r\n"));
199        assert!(msg.contains("-----END PGP MESSAGE-----\r\n"));
200
201        for line in msg.rsplit_terminator('\n') {
202            assert!(line.ends_with('\r'));
203        }
204    }
205
206    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
207    async fn test_render_setup_file_newline_replace() {
208        let t = TestContext::new_alice().await;
209        let msg = render_setup_file(&t, "pw").await.unwrap();
210        println!("{}", &msg);
211        assert!(msg.contains("<p>This is the Autocrypt Setup Message used to transfer your end-to-end setup between clients.<br>"));
212    }
213
214    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
215    async fn test_create_setup_code() {
216        let t = TestContext::new().await;
217        let setupcode = create_setup_code(&t);
218        assert_eq!(setupcode.len(), 44);
219        assert_eq!(setupcode.chars().nth(4).unwrap(), '-');
220        assert_eq!(setupcode.chars().nth(9).unwrap(), '-');
221        assert_eq!(setupcode.chars().nth(14).unwrap(), '-');
222        assert_eq!(setupcode.chars().nth(19).unwrap(), '-');
223        assert_eq!(setupcode.chars().nth(24).unwrap(), '-');
224        assert_eq!(setupcode.chars().nth(29).unwrap(), '-');
225        assert_eq!(setupcode.chars().nth(34).unwrap(), '-');
226        assert_eq!(setupcode.chars().nth(39).unwrap(), '-');
227    }
228
229    #[test]
230    fn test_normalize_setup_code() {
231        let norm = normalize_setup_code("123422343234423452346234723482349234");
232        assert_eq!(norm, "1234-2234-3234-4234-5234-6234-7234-8234-9234");
233
234        let norm =
235            normalize_setup_code("\t1 2 3422343234- foo bar-- 423-45 2 34 6234723482349234      ");
236        assert_eq!(norm, "1234-2234-3234-4234-5234-6234-7234-8234-9234");
237    }
238
239    /* S_EM_SETUPFILE is a AES-256 symm. encrypted setup message created by Enigmail
240    with an "encrypted session key", see RFC 4880.  The code is in S_EM_SETUPCODE */
241    const S_EM_SETUPCODE: &str = "1742-0185-6197-1303-7016-8412-3581-4441-0597";
242    const S_EM_SETUPFILE: &str = include_str!("../../test-data/message/stress.txt");
243
244    // Autocrypt Setup Message payload "encrypted" with plaintext algorithm.
245    const S_PLAINTEXT_SETUPFILE: &str =
246        include_str!("../../test-data/message/plaintext-autocrypt-setup.txt");
247
248    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
249    async fn test_split_and_decrypt() {
250        let buf_1 = S_EM_SETUPFILE.as_bytes().to_vec();
251        let (typ, headers, base64) = split_armored_data(&buf_1).unwrap();
252        assert_eq!(typ, BlockType::Message);
253        assert!(S_EM_SETUPCODE.starts_with(headers.get(HEADER_SETUPCODE).unwrap()));
254        assert!(!headers.contains_key(HEADER_AUTOCRYPT));
255
256        assert!(!base64.is_empty());
257
258        let setup_file = S_EM_SETUPFILE;
259        let decrypted = decrypt_setup_file(S_EM_SETUPCODE, setup_file.as_bytes())
260            .await
261            .unwrap();
262
263        let (typ, headers, _base64) = split_armored_data(decrypted.as_bytes()).unwrap();
264
265        assert_eq!(typ, BlockType::PrivateKey);
266        assert_eq!(headers.get(HEADER_AUTOCRYPT), Some(&"mutual".to_string()));
267        assert!(!headers.contains_key(HEADER_SETUPCODE));
268    }
269
270    /// Tests that Autocrypt Setup Message encrypted with "plaintext" algorithm cannot be
271    /// decrypted.
272    ///
273    /// According to <https://datatracker.ietf.org/doc/html/rfc4880#section-13.4>
274    /// "Implementations MUST NOT use plaintext in Symmetrically Encrypted Data packets".
275    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
276    async fn test_decrypt_plaintext_autocrypt_setup_message() {
277        let setup_file = S_PLAINTEXT_SETUPFILE;
278        let incorrect_setupcode = "0000-0000-0000-0000-0000-0000-0000-0000-0000";
279        assert!(
280            decrypt_setup_file(incorrect_setupcode, setup_file.as_bytes(),)
281                .await
282                .is_err()
283        );
284    }
285
286    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
287    async fn test_key_transfer() -> Result<()> {
288        let mut tcm = TestContextManager::new();
289        let alice = &tcm.alice().await;
290
291        tcm.section("Alice sends Autocrypt setup message");
292        alice.set_config(Config::BccSelf, Some("0")).await?;
293        let setup_code = initiate_key_transfer(alice).await?;
294
295        // Test that sending Autocrypt Setup Message enables `bcc_self`.
296        assert_eq!(alice.get_config_bool(Config::BccSelf).await?, true);
297
298        // Get Autocrypt Setup Message.
299        let sent = alice.pop_sent_msg().await;
300
301        tcm.section("Alice sets up a second device");
302        let alice2 = &tcm.unconfigured().await;
303        alice2.set_name("alice2");
304        alice2.configure_addr("alice@example.org").await;
305        alice2.recv_msg(&sent).await;
306        let msg = alice2.get_last_msg().await;
307        assert!(msg.is_setupmessage());
308        assert_eq!(crate::key::load_self_secret_keyring(alice2).await?.len(), 0);
309
310        // Transfer the key.
311        tcm.section("Alice imports a key from Autocrypt Setup Message");
312        alice2.set_config(Config::BccSelf, Some("0")).await?;
313        continue_key_transfer(alice2, msg.id, &setup_code).await?;
314        assert_eq!(alice2.get_config_bool(Config::BccSelf).await?, true);
315        assert_eq!(crate::key::load_self_secret_keyring(alice2).await?.len(), 1);
316
317        // Alice sends a message to self from the new device.
318        let sent = alice2.send_text(msg.chat_id, "Test").await;
319        let rcvd_msg = alice.recv_msg(&sent).await;
320        assert_eq!(rcvd_msg.get_text(), "Test");
321
322        Ok(())
323    }
324
325    /// Tests that Autocrypt Setup Messages is only clickable if it is self-sent.
326    /// This prevents Bob from tricking Alice into changing the key
327    /// by sending her an Autocrypt Setup Message as long as Alice's server
328    /// does not allow to forge the `From:` header.
329    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
330    async fn test_key_transfer_non_self_sent() -> Result<()> {
331        let mut tcm = TestContextManager::new();
332        let alice = tcm.alice().await;
333        let bob = tcm.bob().await;
334
335        let _setup_code = initiate_key_transfer(&alice).await?;
336
337        // Get Autocrypt Setup Message.
338        let sent = alice.pop_sent_msg().await;
339
340        let rcvd = bob.recv_msg(&sent).await;
341        assert!(!rcvd.is_setupmessage());
342
343        Ok(())
344    }
345
346    /// Tests reception of Autocrypt Setup Message from K-9 6.802.
347    ///
348    /// Unlike Autocrypt Setup Message sent by Delta Chat,
349    /// this message does not contain `Autocrypt-Prefer-Encrypt` header.
350    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
351    async fn test_key_transfer_k_9() -> Result<()> {
352        let t = &TestContext::new().await;
353        t.configure_addr("autocrypt@nine.testrun.org").await;
354
355        let raw = include_bytes!("../../test-data/message/k-9-autocrypt-setup-message.eml");
356        let received = receive_imf(t, raw, false).await?.unwrap();
357
358        let setup_code = "0655-9868-8252-5455-4232-5158-1237-5333-2638";
359        continue_key_transfer(t, *received.msg_ids.last().unwrap(), setup_code).await?;
360
361        Ok(())
362    }
363}