π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Constant-time secret equality and other small cleanups
Manav Rathi0fe9bedb0ae7
diff --git a/rust/crates/core/src/auth/api.rs b/rust/crates/core/src/auth/api.rsindex 2cf9cf34f0..5093003642 100644--- a/rust/crates/core/src/auth/api.rs+++ b/rust/crates/core/src/auth/api.rs@@ -100,33 +100,6 @@ impl fmt::Debug for GeneratedSrpSetup {}}-fn decrypt_keys_only_secure(- kek: &[u8],- key_attrs: &KeyAttributes,-) -> Result<(SecretVec, SecretVec)> {- let encrypted_key = crypto::decode_b64(&key_attrs.encrypted_key)- .map_err(|e| AuthError::Decode(format!("encrypted_key: {}", e)))?;- let key_nonce = crypto::decode_b64(&key_attrs.key_decryption_nonce)- .map_err(|e| AuthError::Decode(format!("key_decryption_nonce: {}", e)))?;-- let master_key = SecretVec::new(- secretbox::decrypt(&encrypted_key, &key_nonce, kek)- .map_err(|_| AuthError::IncorrectPassword)?,- );-- let encrypted_secret_key = crypto::decode_b64(&key_attrs.encrypted_secret_key)- .map_err(|e| AuthError::Decode(format!("encrypted_secret_key: {}", e)))?;- let secret_key_nonce = crypto::decode_b64(&key_attrs.secret_key_decryption_nonce)- .map_err(|e| AuthError::Decode(format!("secret_key_decryption_nonce: {}", e)))?;-- let secret_key = SecretVec::new(- secretbox::decrypt(&encrypted_secret_key, &secret_key_nonce, &master_key)- .map_err(|_| AuthError::InvalidKeyAttributes)?,- );-- Ok((master_key, secret_key))-}-/// Derive SRP credentials from password.////// This is the first step in the SRP login flow. Call this after password entry@@ -239,7 +212,27 @@ pub fn generate_srp_setup_with_login_key(/// Use this when you only need access to the decrypted keys (e.g. when the/// auth token comes from a different source than a sealed box).pub fn decrypt_keys_only(kek: &[u8], key_attrs: &KeyAttributes) -> Result<(SecretVec, SecretVec)> {- decrypt_keys_only_secure(kek, key_attrs)+ let encrypted_key = crypto::decode_b64(&key_attrs.encrypted_key)+ .map_err(|e| AuthError::Decode(format!("encrypted_key: {}", e)))?;+ let key_nonce = crypto::decode_b64(&key_attrs.key_decryption_nonce)+ .map_err(|e| AuthError::Decode(format!("key_decryption_nonce: {}", e)))?;++ let master_key = SecretVec::new(+ secretbox::decrypt(&encrypted_key, &key_nonce, kek)+ .map_err(|_| AuthError::IncorrectPassword)?,+ );++ let encrypted_secret_key = crypto::decode_b64(&key_attrs.encrypted_secret_key)+ .map_err(|e| AuthError::Decode(format!("encrypted_secret_key: {}", e)))?;+ let secret_key_nonce = crypto::decode_b64(&key_attrs.secret_key_decryption_nonce)+ .map_err(|e| AuthError::Decode(format!("secret_key_decryption_nonce: {}", e)))?;++ let secret_key = SecretVec::new(+ secretbox::decrypt(&encrypted_secret_key, &secret_key_nonce, &master_key)+ .map_err(|_| AuthError::InvalidKeyAttributes)?,+ );++ Ok((master_key, secret_key))}/// Decrypt secrets after successful authentication.@@ -259,7 +252,7 @@ pub fn decrypt_secrets(key_attrs: &KeyAttributes,encrypted_token: &str,) -> Result<DecryptedSecrets> {- let (master_key, secret_key) = decrypt_keys_only_secure(kek, key_attrs)?;+ let (master_key, secret_key) = decrypt_keys_only(kek, key_attrs)?;// Decrypt token with sealed box (public key crypto)let public_key = crypto::decode_b64(&key_attrs.public_key)@@ -483,7 +476,7 @@ mod tests {srp_salt: crypto::encode_b64(&[0u8; 16]),mem_limit: gen_result.key_attributes.mem_limit.unwrap(),ops_limit: gen_result.key_attributes.ops_limit.unwrap(),- kek_salt: gen_result.key_attributes.kek_salt.clone(),+ kek_salt: gen_result.key_attributes.kek_salt,is_email_mfa_enabled: false,};diff --git a/rust/crates/core/src/auth/srp.rs b/rust/crates/core/src/auth/srp.rsindex f4b28a07de..12ad2809e8 100644--- a/rust/crates/core/src/auth/srp.rs+++ b/rust/crates/core/src/auth/srp.rs@@ -301,7 +301,7 @@ mod tests {session.verify_m2(&expected_m2).unwrap();- let mut bad_m2 = expected_m2.clone();+ let mut bad_m2 = expected_m2;bad_m2[0] ^= 0x01;assert!(session.verify_m2(&bad_m2).is_err());}diff --git a/rust/crates/core/src/crypto/blob.rs b/rust/crates/core/src/crypto/blob.rsindex 8c6e102dc6..a296be87e5 100644--- a/rust/crates/core/src/crypto/blob.rs+++ b/rust/crates/core/src/crypto/blob.rs@@ -385,7 +385,7 @@ mod tests {let plaintext = b"Original data";let encrypted = encrypt(plaintext, &key).unwrap();- let mut corrupted = encrypted.clone();+ let mut corrupted = encrypted;// Corrupt a byte in the encrypted datacorrupted.encrypted_data[10] ^= 1;diff --git a/rust/crates/core/src/crypto/mod.rs b/rust/crates/core/src/crypto/mod.rsindex 5c645365ad..8d85aeb1de 100644--- a/rust/crates/core/src/crypto/mod.rs+++ b/rust/crates/core/src/crypto/mod.rs@@ -66,6 +66,7 @@ use std::{fmt,ops::{Deref, DerefMut},};+use subtle::ConstantTimeEq;use zeroize::Zeroize;mod error;@@ -98,9 +99,24 @@ pub fn init() -> Result<()> {/// `SecretVec` zeroizes its contents on drop and requires an explicit/// [`SecretVec::into_vec`] when crossing out of the trusted Rust layer.#[repr(transparent)]-#[derive(Default, Eq, PartialEq, Hash)]+#[derive(Default)]pub struct SecretVec(Vec<u8>);+impl PartialEq for SecretVec {+ /// Constant-time comparison (the length itself is not hidden).+ fn eq(&self, other: &Self) -> bool {+ self.0.ct_eq(&other.0).into()+ }+}++impl Eq for SecretVec {}++impl std::hash::Hash for SecretVec {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ self.0.hash(state);+ }+}+impl SecretVec {/// Wrap a byte vector so it is zeroized on drop.pub fn new(value: Vec<u8>) -> Self {@@ -168,9 +184,24 @@ impl Drop for SecretVec {/// `SecretString` zeroizes its contents on drop and requires an explicit/// [`SecretString::into_string`] when crossing out of the trusted Rust layer.#[repr(transparent)]-#[derive(Default, Eq, PartialEq, Hash)]+#[derive(Default)]pub struct SecretString(String);+impl PartialEq for SecretString {+ /// Constant-time comparison (the length itself is not hidden).+ fn eq(&self, other: &Self) -> bool {+ self.0.as_bytes().ct_eq(other.0.as_bytes()).into()+ }+}++impl Eq for SecretString {}++impl std::hash::Hash for SecretString {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ self.0.hash(state);+ }+}+impl SecretString {/// Wrap a string so it is zeroized on drop.pub fn new(value: String) -> Self {diff --git a/rust/crates/core/src/crypto/stream.rs b/rust/crates/core/src/crypto/stream.rsindex 5b1ff21bf5..add78c2aeb 100644--- a/rust/crates/core/src/crypto/stream.rs+++ b/rust/crates/core/src/crypto/stream.rs@@ -857,10 +857,10 @@ mod tests {// Create a stream with just the header, no encrypted datalet encryptor = StreamEncryptor::new(&key).expect("encryptor creation failed");- let header = encryptor.header.clone();+ let header = encryptor.header;// Don't write any encrypted chunks - just the header- let truncated_data = header.clone();+ let truncated_data = header;let reader = Cursor::new(&truncated_data);let mut decryptor =@@ -1081,7 +1081,7 @@ mod tests {}}- // ============ P2: Expanded unit tests ============+ // Expanded unit tests#[test]fn test_empty_input() {@@ -1638,7 +1638,7 @@ mod tests {));}- // ============ Truncation detection tests for decrypt_file / decrypt ============+ // Truncation detection tests for decrypt_file / decrypt#[test]fn test_decrypt_file_truncation_empty_ciphertext() {@@ -1868,7 +1868,7 @@ mod tests {);}- // ============ Size estimation consistency tests ============+ // Size estimation consistency tests#[test]fn test_encrypt_file_size_matches_estimate_empty() {diff --git a/rust/crates/core/src/http.rs b/rust/crates/core/src/http.rsindex 8ea541ec50..a80ef50af3 100644--- a/rust/crates/core/src/http.rs+++ b/rust/crates/core/src/http.rs@@ -415,7 +415,7 @@ impl HttpClient {}/// POST JSON request.- pub async fn post_json<T: DeserializeOwned, B: Serialize + ?Sized>(+ pub async fn post_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(&self,path: &str,body: &B,@@ -437,7 +437,7 @@ impl HttpClient {}/// POST JSON request expecting an empty response body.- pub async fn post_empty<B: Serialize + ?Sized>(+ pub async fn post_empty<B: Serialize + Sync + ?Sized>(&self,path: &str,body: &B,@@ -459,7 +459,7 @@ impl HttpClient {}/// PUT JSON request.- pub async fn put_json<T: DeserializeOwned, B: Serialize + ?Sized>(+ pub async fn put_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(&self,path: &str,body: &B,@@ -481,7 +481,7 @@ impl HttpClient {}/// PUT JSON request expecting an empty response body.- pub async fn put_empty<B: Serialize + ?Sized>(+ pub async fn put_empty<B: Serialize + Sync + ?Sized>(&self,path: &str,body: &B,