message.rs (12719B)
1 use crate::error::RadrootsSimplexSmpCryptoError; 2 use alloc::vec; 3 use alloc::vec::Vec; 4 use getrandom::getrandom; 5 use hkdf::Hkdf; 6 use poly1305::Poly1305; 7 use poly1305::universal_hash::KeyInit as Poly1305KeyInit; 8 use salsa20::cipher::consts::U10; 9 use salsa20::cipher::{KeyIvInit, StreamCipher}; 10 use salsa20::{Salsa20, hsalsa}; 11 use sha2::{Digest, Sha256, Sha512}; 12 use subtle::ConstantTimeEq; 13 use x25519_dalek::{PublicKey, StaticSecret}; 14 15 pub const RADROOTS_SIMPLEX_SMP_NONCE_LENGTH: usize = 24; 16 pub const RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH: usize = 32; 17 const RADROOTS_SIMPLEX_SMP_AUTH_TAG_LENGTH: usize = 16; 18 const RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INIT_INFO: &[u8] = b"SimpleXSbChainInit"; 19 const RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INFO: &[u8] = b"SimpleXSbChain"; 20 const RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_KEY_LENGTH: usize = 32; 21 const RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INIT_OUTPUT_LENGTH: usize = 64; 22 const RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_STEP_OUTPUT_LENGTH: usize = 88; 23 24 type RadrootsSimplexSmpSecretBoxKeyAndNonce = (Vec<u8>, [u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH]); 25 type RadrootsSimplexSmpSecretBoxChainStep = ( 26 RadrootsSimplexSmpSecretBoxKeyAndNonce, 27 RadrootsSimplexSmpSecretBoxChainKey, 28 ); 29 30 #[derive(Debug, Clone, PartialEq, Eq)] 31 pub struct RadrootsSimplexSmpX25519Keypair { 32 pub public_key: Vec<u8>, 33 pub private_key: Vec<u8>, 34 } 35 36 impl RadrootsSimplexSmpX25519Keypair { 37 pub fn generate() -> Result<Self, RadrootsSimplexSmpCryptoError> { 38 let mut secret = [0_u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH]; 39 getrandom(&mut secret).map_err(|_| RadrootsSimplexSmpCryptoError::EntropyUnavailable)?; 40 Ok(Self::from_secret_bytes(secret)) 41 } 42 43 pub fn from_seed(seed: &[u8]) -> Self { 44 let digest = Sha256::digest(seed); 45 let mut secret = [0_u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH]; 46 secret.copy_from_slice(&digest[..RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH]); 47 Self::from_secret_bytes(secret) 48 } 49 50 pub fn public_key_from_private( 51 private_key: &[u8], 52 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 53 let private: [u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH] = 54 private_key.try_into().map_err(|_| { 55 RadrootsSimplexSmpCryptoError::InvalidPrivateKeyLength(private_key.len()) 56 })?; 57 Ok(PublicKey::from(&StaticSecret::from(private)) 58 .as_bytes() 59 .to_vec()) 60 } 61 62 fn from_secret_bytes(secret: [u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH]) -> Self { 63 let private = StaticSecret::from(secret); 64 let public = PublicKey::from(&private); 65 Self { 66 public_key: public.as_bytes().to_vec(), 67 private_key: private.to_bytes().to_vec(), 68 } 69 } 70 } 71 72 #[derive(Debug, Clone, PartialEq, Eq)] 73 pub struct RadrootsSimplexSmpSecretBoxChainKey { 74 bytes: [u8; RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_KEY_LENGTH], 75 } 76 77 impl RadrootsSimplexSmpSecretBoxChainKey { 78 fn from_slice(value: &[u8]) -> Result<Self, RadrootsSimplexSmpCryptoError> { 79 let bytes: [u8; RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_KEY_LENGTH] = 80 value.try_into().map_err(|_| { 81 RadrootsSimplexSmpCryptoError::InvalidSecretBoxChainKeyLength(value.len()) 82 })?; 83 Ok(Self { bytes }) 84 } 85 } 86 87 pub fn init_secretbox_chain( 88 session_identifier: &[u8], 89 shared_secret: &[u8], 90 ) -> Result< 91 ( 92 RadrootsSimplexSmpSecretBoxChainKey, 93 RadrootsSimplexSmpSecretBoxChainKey, 94 ), 95 RadrootsSimplexSmpCryptoError, 96 > { 97 let output = hkdf_expand( 98 session_identifier, 99 shared_secret, 100 RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INIT_INFO, 101 RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INIT_OUTPUT_LENGTH, 102 )?; 103 let (first, second) = output.split_at(RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_KEY_LENGTH); 104 Ok(( 105 RadrootsSimplexSmpSecretBoxChainKey::from_slice(first)?, 106 RadrootsSimplexSmpSecretBoxChainKey::from_slice(second)?, 107 )) 108 } 109 110 pub fn advance_secretbox_chain( 111 chain_key: &RadrootsSimplexSmpSecretBoxChainKey, 112 ) -> Result<RadrootsSimplexSmpSecretBoxChainStep, RadrootsSimplexSmpCryptoError> { 113 let output = hkdf_expand( 114 b"", 115 &chain_key.bytes, 116 RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_INFO, 117 RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_STEP_OUTPUT_LENGTH, 118 )?; 119 let (next_chain_key, remainder) = 120 output.split_at(RADROOTS_SIMPLEX_SMP_SECRETBOX_CHAIN_KEY_LENGTH); 121 let (secretbox_key, nonce_bytes) = 122 remainder.split_at(RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH); 123 Ok(( 124 ( 125 secretbox_key.to_vec(), 126 nonce_bytes.try_into().map_err(|_| { 127 RadrootsSimplexSmpCryptoError::InvalidNonceLength(nonce_bytes.len()) 128 })?, 129 ), 130 RadrootsSimplexSmpSecretBoxChainKey::from_slice(next_chain_key)?, 131 )) 132 } 133 134 pub fn derive_shared_secret( 135 private_key: &[u8], 136 public_key: &[u8], 137 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 138 let private: [u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH] = private_key 139 .try_into() 140 .map_err(|_| RadrootsSimplexSmpCryptoError::InvalidPrivateKeyLength(private_key.len()))?; 141 let public: [u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH] = public_key 142 .try_into() 143 .map_err(|_| RadrootsSimplexSmpCryptoError::InvalidPublicKeyLength(public_key.len()))?; 144 let secret = StaticSecret::from(private).diffie_hellman(&PublicKey::from(public)); 145 Ok(secret.as_bytes().to_vec()) 146 } 147 148 pub fn random_nonce() 149 -> Result<[u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH], RadrootsSimplexSmpCryptoError> { 150 let mut nonce = [0_u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH]; 151 getrandom(&mut nonce).map_err(|_| RadrootsSimplexSmpCryptoError::EntropyUnavailable)?; 152 Ok(nonce) 153 } 154 155 pub fn encrypt_padded( 156 shared_secret: &[u8], 157 nonce: &[u8], 158 plaintext: &[u8], 159 padded_len: usize, 160 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 161 let plaintext_length = u16::try_from(plaintext.len()).map_err(|_| { 162 RadrootsSimplexSmpCryptoError::InvalidMessageLength { 163 actual: plaintext.len(), 164 padded: padded_len, 165 } 166 })?; 167 if plaintext.len().saturating_add(2) > padded_len { 168 return Err(RadrootsSimplexSmpCryptoError::InvalidMessageLength { 169 actual: plaintext.len(), 170 padded: padded_len, 171 }); 172 } 173 let mut padded = Vec::with_capacity(padded_len); 174 padded.extend_from_slice(&plaintext_length.to_be_bytes()); 175 padded.extend_from_slice(plaintext); 176 padded.resize(padded_len, b'#'); 177 encrypt_no_pad(shared_secret, nonce, &padded) 178 } 179 180 pub fn decrypt_padded( 181 shared_secret: &[u8], 182 nonce: &[u8], 183 ciphertext: &[u8], 184 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 185 let padded = decrypt_no_pad(shared_secret, nonce, ciphertext)?; 186 if padded.len() < 2 { 187 return Err(RadrootsSimplexSmpCryptoError::InvalidCiphertextLength( 188 padded.len(), 189 )); 190 } 191 let length = u16::from_be_bytes([padded[0], padded[1]]) as usize; 192 if length > padded.len().saturating_sub(2) { 193 return Err(RadrootsSimplexSmpCryptoError::InvalidCiphertextLength( 194 padded.len(), 195 )); 196 } 197 Ok(padded[2..2 + length].to_vec()) 198 } 199 200 pub fn encrypt_no_pad( 201 shared_secret: &[u8], 202 nonce: &[u8], 203 plaintext: &[u8], 204 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 205 let stream = simplex_secretbox_stream(shared_secret, nonce, plaintext.len())?; 206 let (mac_key, mask) = stream.split_at(RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH); 207 let mut encrypted = Vec::with_capacity(RADROOTS_SIMPLEX_SMP_AUTH_TAG_LENGTH + plaintext.len()); 208 let mut ciphertext = plaintext.to_vec(); 209 xor_in_place(&mut ciphertext, mask); 210 let tag = Poly1305::new(mac_key.into()).compute_unpadded(&ciphertext); 211 encrypted.extend_from_slice(&tag); 212 encrypted.extend_from_slice(&ciphertext); 213 Ok(encrypted) 214 } 215 216 pub fn decrypt_no_pad( 217 shared_secret: &[u8], 218 nonce: &[u8], 219 ciphertext: &[u8], 220 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 221 if ciphertext.len() < RADROOTS_SIMPLEX_SMP_AUTH_TAG_LENGTH { 222 return Err(RadrootsSimplexSmpCryptoError::InvalidCiphertextLength( 223 ciphertext.len(), 224 )); 225 } 226 let (tag_bytes, encrypted) = ciphertext.split_at(RADROOTS_SIMPLEX_SMP_AUTH_TAG_LENGTH); 227 let stream = simplex_secretbox_stream(shared_secret, nonce, encrypted.len())?; 228 let (mac_key, mask) = stream.split_at(RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH); 229 let tag = Poly1305::new(mac_key.into()).compute_unpadded(encrypted); 230 if tag.as_slice().ct_eq(tag_bytes).unwrap_u8() != 1 { 231 return Err(RadrootsSimplexSmpCryptoError::InvalidCiphertextLength( 232 ciphertext.len(), 233 )); 234 } 235 let mut buffer = encrypted.to_vec(); 236 xor_in_place(&mut buffer, mask); 237 Ok(buffer) 238 } 239 240 fn simplex_secretbox_stream( 241 shared_secret: &[u8], 242 nonce: &[u8], 243 plaintext_len: usize, 244 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 245 if shared_secret.len() != RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH { 246 return Err(RadrootsSimplexSmpCryptoError::InvalidSharedSecretLength( 247 shared_secret.len(), 248 )); 249 } 250 let nonce: [u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH] = nonce 251 .try_into() 252 .map_err(|_| RadrootsSimplexSmpCryptoError::InvalidNonceLength(nonce.len()))?; 253 let first_key = hsalsa::<U10>(shared_secret.into(), (&[0_u8; 16]).into()); 254 let second_key = hsalsa::<U10>(&first_key, (&nonce[..16]).into()); 255 let mut cipher = Salsa20::new(&second_key, (&nonce[16..]).into()); 256 let mut stream = vec![0_u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH + plaintext_len]; 257 cipher.apply_keystream(&mut stream); 258 Ok(stream) 259 } 260 261 fn xor_in_place(value: &mut [u8], mask: &[u8]) { 262 for (byte, mask) in value.iter_mut().zip(mask.iter()) { 263 *byte ^= mask; 264 } 265 } 266 267 fn hkdf_expand( 268 salt: &[u8], 269 ikm: &[u8], 270 info: &[u8], 271 output_len: usize, 272 ) -> Result<Vec<u8>, RadrootsSimplexSmpCryptoError> { 273 let hkdf = Hkdf::<Sha512>::new(Some(salt), ikm); 274 let mut output = vec![0_u8; output_len]; 275 hkdf.expand(info, &mut output) 276 .map_err(|_| RadrootsSimplexSmpCryptoError::InvalidKeyDerivationLength(output_len))?; 277 Ok(output) 278 } 279 280 #[cfg(test)] 281 mod tests { 282 use super::*; 283 284 #[test] 285 fn derives_repeatable_keypair_from_seed() { 286 let first = RadrootsSimplexSmpX25519Keypair::from_seed(b"seed"); 287 let second = RadrootsSimplexSmpX25519Keypair::from_seed(b"seed"); 288 assert_eq!(first, second); 289 } 290 291 #[test] 292 fn encrypts_and_decrypts_padded_message() { 293 let alice = RadrootsSimplexSmpX25519Keypair::from_seed(b"alice"); 294 let bob = RadrootsSimplexSmpX25519Keypair::from_seed(b"bob"); 295 let alice_secret = derive_shared_secret(&alice.private_key, &bob.public_key).unwrap(); 296 let bob_secret = derive_shared_secret(&bob.private_key, &alice.public_key).unwrap(); 297 assert_eq!(alice_secret, bob_secret); 298 299 let nonce = [5_u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH]; 300 let ciphertext = encrypt_padded(&alice_secret, &nonce, b"hello", 32).unwrap(); 301 let plaintext = decrypt_padded(&bob_secret, &nonce, &ciphertext).unwrap(); 302 assert_eq!(plaintext, b"hello"); 303 } 304 305 #[test] 306 fn encrypt_padded_uses_simplex_transport_padding() { 307 let key = [7_u8; RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH]; 308 let nonce = [11_u8; RADROOTS_SIMPLEX_SMP_NONCE_LENGTH]; 309 let ciphertext = encrypt_padded(&key, &nonce, b"hello", 12).unwrap(); 310 let padded = decrypt_no_pad(&key, &nonce, &ciphertext).unwrap(); 311 312 assert_eq!(&padded[..7], &[0, 5, b'h', b'e', b'l', b'l', b'o']); 313 assert!(padded[7..].iter().all(|byte| *byte == b'#')); 314 } 315 316 #[test] 317 fn derives_repeatable_secretbox_chain_progression() { 318 let (rcv_first, snd_first) = init_secretbox_chain(b"session", b"shared-secret").unwrap(); 319 let (rcv_second, snd_second) = init_secretbox_chain(b"session", b"shared-secret").unwrap(); 320 assert_eq!(rcv_first, rcv_second); 321 assert_eq!(snd_first, snd_second); 322 323 let ((send_key, send_nonce), next_send) = advance_secretbox_chain(&snd_first).unwrap(); 324 let ((recv_key, recv_nonce), next_recv) = advance_secretbox_chain(&rcv_first).unwrap(); 325 326 assert_eq!(send_key.len(), RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH); 327 assert_eq!(recv_key.len(), RADROOTS_SIMPLEX_SMP_SHARED_SECRET_LENGTH); 328 assert_ne!(send_nonce, recv_nonce); 329 assert_ne!(next_send, snd_first); 330 assert_ne!(next_recv, rcv_first); 331 } 332 }