main.rs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. /* This file is part of DarkFi (https://dark.fi)
  2. *
  3. * Copyright (C) 2020-2023 Dyne.org foundation
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU Affero General Public License as
  7. * published by the Free Software Foundation, either version 3 of the
  8. * License, or (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU Affero General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Affero General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. //! https://signal.org/docs/specifications/x3dh/x3dh.pdf
  19. //! https://signal.org/docs/specifications/doubleratchet/doubleratchet.pdf
  20. use std::collections::{HashMap, VecDeque};
  21. use aes_gcm_siv::{AeadInPlace, Aes256GcmSiv, KeyInit};
  22. use digest::Update;
  23. use rand::rngs::OsRng;
  24. use sha2::Sha256;
  25. use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519SecretKey};
  26. mod hkdf;
  27. use hkdf::Hkdf;
  28. mod hmac;
  29. use hmac::Hmac;
  30. mod xeddsa;
  31. use xeddsa::{XeddsaSigner, XeddsaVerifier};
  32. const AEAD_TAG_SIZE: usize = 16;
  33. const MESSAGE_KEY_CONSTANT: u8 = 0x01;
  34. const CHAIN_KEY_CONSTANT: u8 = 0x02;
  35. const X3DH_INIT_INFO: &[u8] = b"x3dh_double_ratchet_init";
  36. const BLANK_NONCE: &[u8] = &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  37. // wat do?
  38. const MAX_SKIP: u64 = 500;
  39. /// The server contains published identity keys and prekeys.
  40. #[derive(Default)]
  41. struct Server(HashMap<X25519PublicKey, Keyset>);
  42. impl Server {
  43. pub fn upload(&mut self, ik: X25519PublicKey, keyset: Keyset) {
  44. self.0.insert(ik, keyset);
  45. }
  46. pub fn fetch(&mut self, ik: &X25519PublicKey) -> Option<Bundle> {
  47. if let Some(keyset) = self.0.get_mut(ik) {
  48. // The server should provide one one-time prekey if one exists,
  49. // and then delete it. If all of the one-time prekeys have been
  50. // deleted, the bundle will not contain a one-time prekey.
  51. let onetime_prekey = keyset.onetime_prekeys.pop_front();
  52. return Some(Bundle {
  53. identity_key: *ik,
  54. signed_prekey: keyset.signed_prekey,
  55. prekey_signature: keyset.prekey_signature,
  56. onetime_prekey,
  57. })
  58. }
  59. None
  60. }
  61. }
  62. /// The set of elliptic curve public keys sent uploaded to a server
  63. struct Keyset {
  64. pub signed_prekey: X25519PublicKey,
  65. pub prekey_signature: [u8; 64],
  66. pub onetime_prekeys: VecDeque<X25519PublicKey>,
  67. }
  68. /// The bundle is a structure returned by the server when requesting
  69. /// it for a certain identity key
  70. struct Bundle {
  71. pub identity_key: X25519PublicKey,
  72. pub signed_prekey: X25519PublicKey,
  73. pub prekey_signature: [u8; 64],
  74. pub onetime_prekey: Option<X25519PublicKey>,
  75. }
  76. /// Initial message sent from Alice to Bob (see below how it's used)
  77. struct InitialMessage {
  78. pub identity_key: X25519PublicKey,
  79. pub ephemeral_key: X25519PublicKey,
  80. pub prekey_used: Option<X25519PublicKey>,
  81. pub ciphertext: Vec<u8>,
  82. }
  83. #[derive(Copy, Clone, Debug)]
  84. struct MessageHeader {
  85. /// Ratchet public key
  86. dh: X25519PublicKey,
  87. /// Previous chain length
  88. pn: u64,
  89. /// Message number
  90. n: u64,
  91. }
  92. impl MessageHeader {
  93. /// Creates a new message header containing the DH ratchet public key
  94. /// `dh` the previous chain length `pn`, and the message number `n`.
  95. pub fn new(dh: &X25519SecretKey, pn: u64, n: u64) -> Self {
  96. Self { dh: X25519PublicKey::from(dh), pn, n }
  97. }
  98. pub fn to_bytes(self) -> [u8; 48] {
  99. let mut ret = [0u8; 48];
  100. ret[..32].copy_from_slice(&self.dh.to_bytes());
  101. ret[32..40].copy_from_slice(&self.pn.to_le_bytes());
  102. ret[40..].copy_from_slice(&self.n.to_le_bytes());
  103. ret
  104. }
  105. pub fn from_bytes(arr: [u8; 48]) -> Self {
  106. let pk_bytes: [u8; 32] = arr[..32].try_into().unwrap();
  107. let dh = X25519PublicKey::from(pk_bytes);
  108. let pn = u64::from_le_bytes(arr[32..40].try_into().unwrap());
  109. let n = u64::from_le_bytes(arr[40..].try_into().unwrap());
  110. Self { dh, pn, n }
  111. }
  112. /// Returns the AEAD encryption of the message header with header key `hk`.
  113. /// Because the same `hk` will be used repeatedly, the AEAD nonce must
  114. /// either be a stateful non-repeating value, or must be a random
  115. /// non-repeating value chosen with at least 128 bits of entropy.
  116. pub fn encrypt(&self, hk: [u8; 32], ad: &[u8]) -> Vec<u8> {
  117. // FIXME: BUG: Don't reuse the nonce.
  118. let nonce = [0u8; 12][..].into();
  119. let mut ciphertext = vec![0u8; 48 + AEAD_TAG_SIZE];
  120. ciphertext[..48].copy_from_slice(&self.to_bytes());
  121. Aes256GcmSiv::new(&hk.into()).encrypt_in_place(nonce, ad, &mut ciphertext).unwrap();
  122. ciphertext
  123. }
  124. /// Returns the authenticated decryption of `ciphertext` with header key `hk`.
  125. pub fn decrypt(ciphertext: &[u8], hk: [u8; 32], ad: &[u8]) -> Option<Self> {
  126. // FIXME: BUG: Don't reuse the nonce.
  127. let nonce = [0u8; 12][..].into();
  128. let mut plaintext = vec![0u8; ciphertext.len()];
  129. plaintext.copy_from_slice(ciphertext);
  130. match Aes256GcmSiv::new(&hk.into()).decrypt_in_place(nonce, ad, &mut plaintext) {
  131. Ok(()) => {
  132. plaintext.resize(plaintext.len() - AEAD_TAG_SIZE, 0);
  133. let message_header = Self::from_bytes(plaintext.try_into().unwrap());
  134. Some(message_header)
  135. }
  136. Err(_) => None,
  137. }
  138. }
  139. }
  140. /// Returns a pair (32-byte chain key, 32-byte message key) as the output of
  141. /// applying a KDF keyed by a 32-byte chain key `ck` to some constant.
  142. /// HMAC with SHA256 is recommended, using `ck` as the HMAC key and using
  143. /// separate constants as input (e.g. a single byte 0x01 as input to produce
  144. /// the message key, and a single byte 0x02 as input to produce the next chain
  145. /// key.
  146. fn kdf_ck(ck: [u8; 32]) -> ([u8; 32], [u8; 32]) {
  147. let mut hmac = Hmac::<Sha256>::new_from_slice(&ck);
  148. hmac.update(&[CHAIN_KEY_CONSTANT]);
  149. let chain_key = hmac.finalize();
  150. let mut hmac = Hmac::<Sha256>::new_from_slice(&ck);
  151. hmac.update(&[MESSAGE_KEY_CONSTANT]);
  152. let message_key = hmac.finalize();
  153. (chain_key.into(), message_key.into())
  154. }
  155. /// Returns a new root key, chain key, and next header key as the output
  156. /// of applying a KDF keyed by root key `rk` to a Diffie-Hellman output
  157. /// `dh_out`.
  158. /// This function is recommended to be implemented using HKDF with SHA256
  159. /// using `rk` as HKDF salt, `dh_out` as HKDF input key material, and an
  160. /// application-specific byte sequence as HKDF info. The info value should
  161. /// be chosen to be distinct from other uses of HKDF in the application.
  162. fn kdf_rk(rk: [u8; 32], dh_out: [u8; 32]) -> ([u8; 32], [u8; 32], [u8; 32]) {
  163. const KDF_RK_INFO: &[u8] = b"x3dh_double_ratchet_kdf_rk";
  164. const KDF_HE_INFO: &[u8] = b"x3dh_double_ratchet_kdf_rk_he";
  165. let (_root_key, hkdf) = Hkdf::<Sha256>::extract(&rk, &dh_out);
  166. let mut chain_key = [0u8; 32];
  167. hkdf.expand(KDF_RK_INFO, &mut chain_key).unwrap();
  168. let (root_key, hkdf) = Hkdf::<Sha256>::extract(&rk, &dh_out);
  169. let mut next_header_key = [0u8; 32];
  170. hkdf.expand(KDF_HE_INFO, &mut next_header_key).unwrap();
  171. (root_key.into(), chain_key, next_header_key)
  172. }
  173. #[derive(Clone)]
  174. struct DoubleRatchetSessionState {
  175. /// DH ratchet key pair (the "sending" or "self" ratchet key) (DHRs)
  176. pub dh_sending: X25519SecretKey,
  177. /// DH ratchet public key (the "received" or "remote" key) (DHRr)
  178. pub dh_remote: X25519PublicKey,
  179. /// 32-byte root key (RK)
  180. pub root_key: [u8; 32],
  181. /// 32-byte Chain Key for sending (CKs)
  182. pub chain_key_send: [u8; 32],
  183. /// 32-byte Chain Key for receiving (CKr)
  184. pub chain_key_recv: [u8; 32],
  185. /// Message numbers for sending (Ns)
  186. pub n_send: u64,
  187. /// Message numbers for receiving (Nr)
  188. pub n_recv: u64,
  189. /// Number of messages in previous sending chain (PN)
  190. pub n_prev: u64,
  191. /// Dictionary of skipped-over message keys, indexed by header key
  192. /// and message number. Raises an exception if too many elements
  193. /// are stored.
  194. pub mkskipped: HashMap<([u8; 32], u64), [u8; 32]>,
  195. /// 32-byte Header Key for sending (HKs)
  196. pub header_key_send: [u8; 32],
  197. /// 32-byte Header Key for receiving (HKr)
  198. pub header_key_recv: [u8; 32],
  199. /// 32-byte Next Header Key for sending (NHKs)
  200. pub next_header_key_send: [u8; 32],
  201. /// 32-byte Next Header Key for receiving (NHKr)
  202. pub next_header_key_recv: [u8; 32],
  203. }
  204. impl DoubleRatchetSessionState {
  205. /// This function performs a symmetric-key ratchet step, then encrypts
  206. /// the message with the resulting message key. In addition to the
  207. /// message's _plaintext_ it takes an AD byte sequence which is
  208. /// prepended to the header to form the associated data for the
  209. // underlying AEAD encryption.
  210. pub fn ratchet_encrypt(&mut self, plaintext: &[u8], ad: &[u8]) -> (Vec<u8>, Vec<u8>) {
  211. let (chain_key, message_key) = kdf_ck(self.chain_key_send);
  212. self.chain_key_send = chain_key;
  213. println!("ENCRYPT(): new chain send: {:?}", &chain_key[..5]);
  214. let header = MessageHeader::new(&self.dh_sending, self.n_prev, self.n_send);
  215. let enc_header = header.encrypt(self.header_key_send, &[]);
  216. let mut associated_data = Vec::with_capacity(ad.len() + enc_header.len());
  217. associated_data.extend_from_slice(ad);
  218. associated_data.extend_from_slice(&enc_header);
  219. let mut ciphertext = vec![0u8; plaintext.len() + AEAD_TAG_SIZE];
  220. ciphertext[..plaintext.len()].copy_from_slice(plaintext);
  221. // Because each message key is only used once, the AEAD nonce may be
  222. // handled in several ways:
  223. // * Fixed to a constant
  224. // * Derived from `mk` alongside an independent AEAD encryption key
  225. // * Derived as an additional output from HMAC
  226. // * Chosen randomly and transmitted
  227. // ENCRYPT(message_key, plaintext, (AD || enc_header))
  228. println!("ENCRYPT(): message key: {:?}", &message_key[..5]);
  229. Aes256GcmSiv::new(&message_key.into())
  230. .encrypt_in_place(BLANK_NONCE.into(), &associated_data, &mut ciphertext)
  231. .unwrap();
  232. self.n_send += 1;
  233. (enc_header, ciphertext)
  234. }
  235. /// Decrypt messages. This function does the following:
  236. /// * If the message corresponds to a skipped message key this function
  237. /// decrypts the message, deletes the message key, and returns.
  238. /// * Otherwise, if a new ratchet key has been received, this function
  239. /// stores any skipped message keys from the receiving chain and
  240. /// performs a DH ratchet step to replace the sending and receiving
  241. /// chains.
  242. /// * This function then stores any skipped message keys from the current
  243. /// receiving chain, performs a symmetric-key ratchet step to derive
  244. /// the relevant message key and next chain key, and decrypts the msg.
  245. /// If an exception is raised (e.g. message authentication failure), then
  246. /// the message is discarded and changes to the state object are discarded.
  247. /// Otherwise, the decrypted plaintext is accepted and changes to the state
  248. /// object are stored.
  249. pub fn ratchet_decrypt(&mut self, enc_header: &[u8], ciphertext: &[u8], ad: &[u8]) -> Vec<u8> {
  250. // We clone here so we don't have to worry about mutating the state before
  251. // everything is correct.
  252. let mut state = self.clone();
  253. if let Some(plaintext) = state.try_skipped_message_keys(enc_header, ciphertext, ad) {
  254. println!("found skipped");
  255. *self = state;
  256. return plaintext
  257. }
  258. if let Some((header, dh_ratchet)) = state.decrypt_header(enc_header) {
  259. if dh_ratchet {
  260. state.skip_message_keys(header.pn);
  261. state.dh_ratchet(header);
  262. }
  263. state.skip_message_keys(header.n);
  264. } else {
  265. panic!("couldn't decrypt header")
  266. }
  267. let (chain_key, message_key) = kdf_ck(state.chain_key_recv);
  268. state.chain_key_recv = chain_key;
  269. println!("DECRYPT(): new chain recv: {:?}", &chain_key[..5]);
  270. state.n_recv += 1;
  271. let mut plaintext = vec![0u8; ciphertext.len()];
  272. plaintext.copy_from_slice(ciphertext);
  273. let mut associated_data = Vec::with_capacity(ad.len() + enc_header.len());
  274. associated_data.extend_from_slice(ad);
  275. associated_data.extend_from_slice(enc_header);
  276. // DECRYPT(message_key, ciphertext, (AD || enc_header))
  277. println!("DECRYPT(): message key: {:?}", &message_key[..5]);
  278. Aes256GcmSiv::new(&message_key.into())
  279. .decrypt_in_place(BLANK_NONCE.into(), &associated_data, &mut plaintext)
  280. .unwrap();
  281. // Apply the state change
  282. *self = state;
  283. plaintext.resize(plaintext.len() - AEAD_TAG_SIZE, 0);
  284. plaintext
  285. }
  286. fn try_skipped_message_keys(
  287. &mut self,
  288. enc_header: &[u8],
  289. ciphertext: &[u8],
  290. ad: &[u8],
  291. ) -> Option<Vec<u8>> {
  292. let mut plaintext = ciphertext.to_vec();
  293. let mut rem = None;
  294. for ((hk, n), mk) in self.mkskipped.iter_mut() {
  295. if let Some(header) = MessageHeader::decrypt(enc_header, *hk, &[]) {
  296. if header.n == *n {
  297. rem = Some((*hk, *n));
  298. let mut associated_data = Vec::with_capacity(ad.len() + enc_header.len());
  299. associated_data.extend_from_slice(ad);
  300. associated_data.extend_from_slice(enc_header);
  301. let mk = *mk;
  302. Aes256GcmSiv::new(&mk.into())
  303. .decrypt_in_place(BLANK_NONCE.into(), &associated_data, &mut plaintext)
  304. .unwrap();
  305. plaintext.resize(plaintext.len() - AEAD_TAG_SIZE, 0);
  306. break
  307. }
  308. panic!("Failed to decrypt message from skipped message keys");
  309. }
  310. }
  311. if let Some(found) = rem {
  312. self.mkskipped.remove(&found);
  313. return Some(plaintext)
  314. }
  315. None
  316. }
  317. fn decrypt_header(&mut self, enc_header: &[u8]) -> Option<(MessageHeader, bool)> {
  318. if let Some(header) = MessageHeader::decrypt(enc_header, self.header_key_recv, &[]) {
  319. return Some((header, false))
  320. }
  321. if let Some(header) = MessageHeader::decrypt(enc_header, self.next_header_key_recv, &[]) {
  322. return Some((header, true))
  323. }
  324. println!("Failed to decrypt header");
  325. None
  326. }
  327. fn skip_message_keys(&mut self, until: u64) {
  328. if self.n_recv + MAX_SKIP < until {
  329. panic!("I can't hold all of these lemons");
  330. }
  331. if self.chain_key_recv != [0u8; 32] {
  332. while self.n_recv < until {
  333. let (chain_key_recv, message_key) = kdf_ck(self.chain_key_recv);
  334. self.chain_key_recv = chain_key_recv;
  335. println!("SKIP(): new chain recv: {:?}", &chain_key_recv[..5]);
  336. self.mkskipped.insert((self.header_key_recv, self.n_recv), message_key);
  337. self.n_recv += 1;
  338. }
  339. }
  340. }
  341. fn dh_ratchet(&mut self, header: MessageHeader) {
  342. self.n_prev = self.n_send;
  343. self.n_send = 0;
  344. self.n_recv = 0;
  345. self.header_key_send = self.next_header_key_send;
  346. self.header_key_recv = self.next_header_key_recv;
  347. self.dh_remote = header.dh;
  348. let hkdf_ikm = self.dh_sending.diffie_hellman(&self.dh_remote);
  349. (self.root_key, self.chain_key_recv, self.next_header_key_recv) =
  350. kdf_rk(self.root_key, hkdf_ikm.to_bytes());
  351. let dh_secret_new = X25519SecretKey::random_from_rng(OsRng);
  352. self.dh_sending = dh_secret_new;
  353. let hkdf_ikm = self.dh_sending.diffie_hellman(&self.dh_remote);
  354. (self.root_key, self.chain_key_send, self.next_header_key_send) =
  355. kdf_rk(self.root_key, hkdf_ikm.to_bytes());
  356. }
  357. }
  358. fn main() {
  359. // The "server" contains published identity keys and prekeys.
  360. let mut server = Server::default();
  361. // The X3DH protocol has three phases:
  362. // 1. Bob publishes his identity key and prekeys to a server.
  363. // 2. Alice fetches a "prekey bundle" from the server, and uses
  364. // it to send an initial message to Bob.
  365. // 3. Bob receives and processes Alice's initial message.
  366. // Alice's identity key `IK_A`
  367. let alice_ik_secret = X25519SecretKey::random_from_rng(OsRng);
  368. let alice_ik_public = X25519PublicKey::from(&alice_ik_secret);
  369. // Bob's identity key `IK_B`
  370. let bob_ik_secret = X25519SecretKey::random_from_rng(OsRng);
  371. let bob_ik_public = X25519PublicKey::from(&bob_ik_secret);
  372. // Bob only needs to upload his identity key to the server once.
  373. // However, Bob may upload new one-time prekeys at other times
  374. // (e.g. when the server informs Bob that the server's store
  375. // of one-time prekeys is getting low).
  376. // Bob will also upload a new signed prekey and prekey signature
  377. // at some interval (e.g. once a week/month). The new signed prekey
  378. // and prekey signature will replace the previous values.
  379. // Bob's signed prekey `SPK_B`
  380. let bob_spk_secret = X25519SecretKey::random_from_rng(OsRng);
  381. let bob_public_spk = X25519PublicKey::from(&bob_spk_secret);
  382. // Bob's prekey signature `Sig(IK_b, Encode(SPK_B))`
  383. let nonce = [0_u8; 64];
  384. let bob_spk_signature = bob_ik_secret.xeddsa_sign(&bob_public_spk.to_bytes(), &nonce);
  385. // A set of Bob's one-time prekeys `(OPK_B1, OPK_B2, OPK_B3, ...)`
  386. let mut bob_opk_secrets = vec![
  387. X25519SecretKey::random_from_rng(OsRng),
  388. X25519SecretKey::random_from_rng(OsRng),
  389. X25519SecretKey::random_from_rng(OsRng),
  390. ];
  391. let mut bob_opk_publics = VecDeque::new();
  392. bob_opk_publics.push_back(X25519PublicKey::from(&bob_opk_secrets[0]));
  393. bob_opk_publics.push_back(X25519PublicKey::from(&bob_opk_secrets[1]));
  394. bob_opk_publics.push_back(X25519PublicKey::from(&bob_opk_secrets[2]));
  395. let bob_keyset = Keyset {
  396. signed_prekey: bob_public_spk,
  397. prekey_signature: bob_spk_signature,
  398. onetime_prekeys: bob_opk_publics.clone(),
  399. };
  400. // Bob uploads his keyset to the server.
  401. server.upload(bob_ik_public, bob_keyset);
  402. // To perform an X3DH key agreement with Bob, Alice contacts the server
  403. // and fetches a "prekey bundle" containing the following values:
  404. // * Bob's identity key `IK_B`
  405. // * Bob's signed prekey `SPK_B`
  406. // * Bob's prekey signature `Sig(IK_B, Encode(SPK_B))`
  407. // * (Optionally) Bob's one-time prekey `OPK_B`
  408. let bob_keyset = server.fetch(&bob_ik_public).unwrap();
  409. // Alice verifies the prekey signature and aborts the protocol if
  410. // verification fails.
  411. assert!(bob_keyset
  412. .identity_key
  413. .xeddsa_verify(&bob_keyset.signed_prekey.to_bytes(), &bob_keyset.prekey_signature));
  414. // Alice then generates an ephemeral keypair with public key `EK_A`
  415. let alice_ek_secret = X25519SecretKey::random_from_rng(OsRng);
  416. let alice_ek_public = X25519PublicKey::from(&alice_ek_secret);
  417. // If the bundle does _not_ contain a one-time prekey, she calculates:
  418. // DH1 = DH(IK_A, SPK_B)
  419. // DH2 = DH(EK_A, IK_B)
  420. // DH3 = DH(EK_A, SPK_B)
  421. // SK = KDF(DH1 || DH2 || DH3)
  422. // If the bundle _does_ contain a one-time prekey, additionally she
  423. // does another dh:
  424. // DH4 = DH(EK_A, OPK_B)
  425. // SK = KDF(DH1 || DH2 || DH3 || DH4)
  426. let dh1 = alice_ik_secret.diffie_hellman(&bob_keyset.signed_prekey);
  427. let dh2 = alice_ek_secret.diffie_hellman(&bob_keyset.identity_key);
  428. let dh3 = alice_ek_secret.diffie_hellman(&bob_keyset.signed_prekey);
  429. let mut dh4 = None;
  430. if let Some(opk) = bob_keyset.onetime_prekey {
  431. dh4 = Some(alice_ek_secret.diffie_hellman(&opk));
  432. }
  433. // KDF represents 32 bytes of output from the HKDF algorithm with inputs:
  434. // - HKDF input key material = F || KM, where KM is an input byte sequence
  435. // containing secret key material, and F is a byte sequence containing
  436. // 32 0xFF bytes when the curve is X25519. F is used for cryptographic
  437. // domain separation with XEdDSA.
  438. // - HKDF salt = A zero-filled byte sequence equal to the hash output length.
  439. // - HKDF info - The info parameter.
  440. let salt = [0u8; 32];
  441. let mut ikm = vec![0xFF; 32];
  442. ikm.extend_from_slice(&dh1.to_bytes());
  443. ikm.extend_from_slice(&dh2.to_bytes());
  444. ikm.extend_from_slice(&dh3.to_bytes());
  445. if let Some(ref opk_dh) = dh4 {
  446. ikm.extend_from_slice(&opk_dh.to_bytes());
  447. }
  448. let hkdf = Hkdf::<Sha256>::new(&salt, &ikm);
  449. let mut sk = [0u8; 32];
  450. hkdf.expand(X3DH_INIT_INFO, &mut sk).unwrap();
  451. // After calculating SK, Alice deletes her ephemeral private key and the
  452. // DH outputs.
  453. // TODO: Actually erase
  454. drop(alice_ek_secret);
  455. drop(dh1);
  456. drop(dh2);
  457. drop(dh3);
  458. drop(dh4);
  459. // Alice then calculates an "associated data" byte sequence AD that
  460. // contains identity information for both parties:
  461. // AD = Encode(IK_A) || Encode(IK_B)
  462. // Alice may optionally append additional info to AD, such as Alice
  463. // and Bob's usernames, certificates, or other identifying information.
  464. let mut ad = Vec::with_capacity(64);
  465. ad.extend_from_slice(&alice_ik_public.to_bytes());
  466. ad.extend_from_slice(&bob_ik_public.to_bytes());
  467. // Alice then sends Bob an initial message containing:
  468. // - Alice's identity key IK_A
  469. // - Alice's ephemeral key EK_A
  470. // - Identifiers stating which of Bob's prekeys Alice used
  471. // - An initial ciphertext with some AEAD encryption scheme using AD as
  472. // associated data and using an encryption key which is either SK
  473. // or the output of some cryptographic PRF keyed by SK.
  474. let message = b"ohai bob";
  475. let mut ciphertext = vec![0u8; message.len() + AEAD_TAG_SIZE];
  476. ciphertext[..message.len()].copy_from_slice(message);
  477. Aes256GcmSiv::new(&sk.into())
  478. .encrypt_in_place(BLANK_NONCE.into(), &ad, &mut ciphertext)
  479. .unwrap();
  480. let initial_message = InitialMessage {
  481. identity_key: alice_ik_public,
  482. ephemeral_key: alice_ek_public,
  483. prekey_used: bob_keyset.onetime_prekey,
  484. ciphertext,
  485. };
  486. // Upon receiving Alice's initial message, Bob retrieves Alice's
  487. // identity key and ephemeral key from the message. Bob also loads
  488. // his identity private key, and the private key(s) corresponding
  489. // to whichever signed prekey and one-time prekey (if any) Alice used.
  490. // NOTE: In this example, we assume Bob already knows the latest prekey
  491. // he signed and uploaded to the server.
  492. // Using these keys, Bob repeats the DH and KDF calculations from the
  493. // previous section to derive SK, and then deletes the DH values.
  494. let mut onetime_prekey = None;
  495. if let Some(opk_used) = initial_message.prekey_used {
  496. for i in bob_opk_secrets.clone() {
  497. if X25519PublicKey::from(&i.clone()) == opk_used {
  498. onetime_prekey = Some(i);
  499. }
  500. }
  501. }
  502. let dh1 = bob_spk_secret.diffie_hellman(&initial_message.identity_key);
  503. let dh2 = bob_ik_secret.diffie_hellman(&initial_message.ephemeral_key);
  504. let dh3 = bob_spk_secret.diffie_hellman(&initial_message.ephemeral_key);
  505. let mut dh4 = None;
  506. if let Some(ref opk) = onetime_prekey {
  507. dh4 = Some(opk.diffie_hellman(&initial_message.ephemeral_key));
  508. }
  509. let salt = [0u8; 32];
  510. let mut ikm = vec![0xFF; 32];
  511. ikm.extend_from_slice(&dh1.to_bytes());
  512. ikm.extend_from_slice(&dh2.to_bytes());
  513. ikm.extend_from_slice(&dh3.to_bytes());
  514. if let Some(ref opk_dh) = dh4 {
  515. ikm.extend_from_slice(&opk_dh.to_bytes());
  516. }
  517. // TODO: Erase ephemeral data
  518. let hkdf = Hkdf::<Sha256>::new(&salt, &ikm);
  519. let mut sk2 = [0u8; 32];
  520. hkdf.expand(X3DH_INIT_INFO, &mut sk2).unwrap();
  521. assert_eq!(sk, sk2); // Just to confirm everything's correct
  522. // Bob then constructs the AD byte sequence using IK_A and IK_B
  523. // as Alice did above.
  524. let mut ad = Vec::with_capacity(64);
  525. ad.extend_from_slice(&initial_message.identity_key.to_bytes());
  526. ad.extend_from_slice(&bob_ik_public.to_bytes());
  527. // Finally, Bob attempts to decrypt the initial ciphertext using SK and AD.
  528. // If the initial ciphertext fails to decrypt, Bob aborts the protocol and
  529. // deletes SK.
  530. let mut plaintext = vec![0_u8; initial_message.ciphertext.len()];
  531. plaintext.copy_from_slice(&initial_message.ciphertext);
  532. Aes256GcmSiv::new(&sk2.into())
  533. .decrypt_in_place(BLANK_NONCE.into(), &ad, &mut plaintext)
  534. .unwrap();
  535. plaintext.resize(plaintext.len() - AEAD_TAG_SIZE, 0);
  536. assert_eq!(plaintext, message); // Just to confirm everything's correct
  537. // If the initial ciphertext decrypts successfully, the protocol is complete
  538. // for Bob. Bob deletes any one-time prekey secret key that was used, for
  539. // forward secrecy. Bob may then continue using SK or keys derived from SK
  540. // within the post-X3DH protocol for communication with Alice.
  541. if let Some(opk) = onetime_prekey {
  542. bob_opk_secrets.retain(|x| x.to_bytes() != opk.to_bytes());
  543. }
  544. // =======================+
  545. // Double Ratchet with X3DH
  546. // ========================
  547. // * The SK output from X3DH becomes the SK input to Double Ratchet initialization.
  548. // * The AD output from X3DH becomes the AD input to Double Ratchet {en,de}cryption.
  549. // * Bob's signed prekey SPK_B becomes Bob's initial ratchet public key (and
  550. // corresponding keypair) for Double Ratchet initialization.
  551. // Any Double Ratchet message encrypted using Alice's initial sending chain can
  552. // serve as an "initial ciphertext" for X3DH. To deal with the possibility of
  553. // lost or out-of-order messages, a recommended pattern is for Alice to repeatedly
  554. // send the same X3DH initial message prepended to all of her Double Ratchet
  555. // messages until she receives Bob's first Double Ratchet response message.
  556. // Once Alice and Bob have agreed on SK and Bob's ratchet public key, Alice
  557. // and Bob initialize their states:
  558. // Alice:
  559. let alice_dh_secret = X25519SecretKey::random_from_rng(OsRng);
  560. // The X3DH secret becomes the HKDF salt, and the ikm is the DH output
  561. // of Alice's DH secret and Bob's SPK_B.
  562. let hkdf_ikm = alice_dh_secret.diffie_hellman(&bob_keyset.signed_prekey);
  563. let (root_key, chain_key_send, next_header_key_send) = kdf_rk(sk, hkdf_ikm.to_bytes());
  564. // TODO: We're using SK here as the initial header encryption keys. Perhaps it's not safe?
  565. let mut ars = DoubleRatchetSessionState {
  566. dh_sending: alice_dh_secret,
  567. dh_remote: bob_keyset.signed_prekey,
  568. root_key,
  569. chain_key_send,
  570. chain_key_recv: [0u8; 32],
  571. n_send: 0,
  572. n_recv: 0,
  573. n_prev: 0,
  574. mkskipped: HashMap::default(),
  575. header_key_send: sk,
  576. header_key_recv: [0u8; 32],
  577. next_header_key_send,
  578. next_header_key_recv: sk,
  579. };
  580. // Bob:
  581. let mut brs = DoubleRatchetSessionState {
  582. dh_sending: bob_spk_secret,
  583. dh_remote: X25519PublicKey::from([0u8; 32]),
  584. root_key: sk,
  585. chain_key_send: [0u8; 32],
  586. chain_key_recv: [0u8; 32],
  587. n_send: 0,
  588. n_recv: 0,
  589. n_prev: 0,
  590. mkskipped: HashMap::default(),
  591. header_key_send: [0u8; 32],
  592. header_key_recv: [0u8; 32],
  593. next_header_key_send: sk,
  594. next_header_key_recv: sk,
  595. };
  596. // TODO: What kind of AD should be used?
  597. // Alice sends it to Bob, and Bob decrypts.
  598. let message_to_bob = b"hai bobz";
  599. println!("Alice: n_recv={}, n_send={}, n_prev={}", ars.n_recv, ars.n_send, ars.n_prev);
  600. let (enc_header, ciphertext) = ars.ratchet_encrypt(message_to_bob, &[]);
  601. println!("Bob: n_recv={}, n_send={}, n_prev={}", brs.n_recv, brs.n_send, brs.n_prev);
  602. let plaintext = brs.ratchet_decrypt(&enc_header, &ciphertext, &[]);
  603. assert_eq!(plaintext, message_to_bob);
  604. println!("Bob decrypted message: {}", String::from_utf8_lossy(&plaintext));
  605. // Bob replies to Alice.
  606. let message_to_alice = b"hai alice, what's up?";
  607. println!("Bob: n_recv={}, n_send={}, n_prev={}", brs.n_recv, brs.n_send, brs.n_prev);
  608. let (enc_header, ciphertext) = brs.ratchet_encrypt(message_to_alice, &[]);
  609. println!("Alice: n_recv={}, n_send={}, n_prev={}", ars.n_recv, ars.n_send, ars.n_prev);
  610. let plaintext = ars.ratchet_decrypt(&enc_header, &ciphertext, &[]);
  611. assert_eq!(plaintext, message_to_alice);
  612. println!("Alice decrypted message: {}", String::from_utf8_lossy(&plaintext));
  613. // Alice loves Bob.
  614. let message_to_bob = b"you schizo";
  615. println!("Alice: n_recv={}, n_send={}, n_prev={}", ars.n_recv, ars.n_send, ars.n_prev);
  616. let (enc_header, ciphertext) = ars.ratchet_encrypt(message_to_bob, &[]);
  617. println!("Bob: n_recv={}, n_send={}, n_prev={}", brs.n_recv, brs.n_send, brs.n_prev);
  618. let plaintext = brs.ratchet_decrypt(&enc_header, &ciphertext, &[]);
  619. assert_eq!(plaintext, message_to_bob);
  620. println!("Bob decrypted message: {}", String::from_utf8_lossy(&plaintext));
  621. // Let's try out of order
  622. let message_to_bob1 = b"hello";
  623. let message_to_bob2 = b"jello";
  624. let (enc_header1, ciphertext1) = ars.ratchet_encrypt(message_to_bob1, &[]);
  625. let (enc_header2, ciphertext2) = ars.ratchet_encrypt(message_to_bob2, &[]);
  626. // Slow Bob
  627. let plaintext = brs.ratchet_decrypt(&enc_header2, &ciphertext2, &[]);
  628. assert_eq!(plaintext, message_to_bob2);
  629. let plaintext = brs.ratchet_decrypt(&enc_header1, &ciphertext1, &[]);
  630. assert_eq!(plaintext, message_to_bob1);
  631. let message_to_alice = b"weaponised autism";
  632. let (enc_header, ciphertext) = brs.ratchet_encrypt(message_to_alice, &[]);
  633. let plaintext = ars.ratchet_decrypt(&enc_header, &ciphertext, &[]);
  634. assert_eq!(plaintext, message_to_alice);
  635. }