π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Harden remaining Rust auth secret handling
Manav Rathi062537766a4c
diff --git a/rust/cli/src/api/models.rs b/rust/cli/src/api/models.rsindex 381a4351c8..54d9fce47f 100644--- a/rust/cli/src/api/models.rs+++ b/rust/cli/src/api/models.rs@@ -1,3 +1,5 @@+use std::fmt;+use serde::{Deserialize, Serialize};use uuid::Uuid;@@ -73,7 +75,7 @@ pub struct KeyAttributes {pub recovery_key_decryption_nonce: Option<String>,}-#[derive(Debug, Deserialize)]+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct AuthResponse {pub id: i64,@@ -90,6 +92,34 @@ pub struct AuthResponse {pub accounts_url: Option<String>,}+impl fmt::Debug for AuthResponse {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("AuthResponse")+ .field("id", &self.id)+ .field("has_key_attributes", &self.key_attributes.is_some())+ .field(+ "encrypted_token",+ &self.encrypted_token.as_ref().map(|_| "[REDACTED]"),+ )+ .field("token", &self.token.as_ref().map(|_| "[REDACTED]"))+ .field(+ "two_factor_session_id",+ &self.two_factor_session_id.as_ref().map(|_| "[REDACTED]"),+ )+ .field(+ "two_factor_session_id_v2",+ &self.two_factor_session_id_v2.as_ref().map(|_| "[REDACTED]"),+ )+ .field(+ "passkey_session_id",+ &self.passkey_session_id.as_ref().map(|_| "[REDACTED]"),+ )+ .field("srp_m2", &self.srp_m2.as_ref().map(|_| "[REDACTED]"))+ .field("accounts_url", &self.accounts_url)+ .finish()+ }+}+impl AuthResponse {pub fn get_two_factor_session_id(&self) -> Option<&String> {self.two_factor_session_id@@ -119,7 +149,7 @@ pub struct SendOtpRequest {pub purpose: String,}-#[derive(Debug, Serialize)]+#[derive(Serialize)]pub struct VerifyEmailRequest {pub email: String,pub ott: String,@@ -127,13 +157,32 @@ pub struct VerifyEmailRequest {pub source: Option<String>,}-#[derive(Debug, Serialize)]+impl fmt::Debug for VerifyEmailRequest {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("VerifyEmailRequest")+ .field("email", &self.email)+ .field("ott", &"[REDACTED]")+ .field("source", &self.source)+ .finish()+ }+}++#[derive(Serialize)]#[serde(rename_all = "camelCase")]pub struct VerifyTotpRequest {pub session_id: String,pub code: String,}+impl fmt::Debug for VerifyTotpRequest {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("VerifyTotpRequest")+ .field("session_id", &"[REDACTED]")+ .field("code", &"[REDACTED]")+ .finish()+ }+}+#[derive(Debug, Serialize)]#[serde(rename_all = "camelCase")]pub struct SetUserAttributesRequest {@@ -183,14 +232,23 @@ pub struct SessionValidityResponse {pub key_attributes: Option<KeyAttributes>,}-#[derive(Debug, Deserialize)]+#[derive(Deserialize)]#[serde(rename_all = "camelCase")]pub struct TwoFactorSecret {pub secret_code: String,pub qr_code: String,}-#[derive(Debug, Serialize)]+impl fmt::Debug for TwoFactorSecret {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("TwoFactorSecret")+ .field("secret_code", &"[REDACTED]")+ .field("qr_code", &"[REDACTED]")+ .finish()+ }+}++#[derive(Serialize)]#[serde(rename_all = "camelCase")]pub struct EnableTwoFactorRequest {pub code: String,@@ -198,6 +256,16 @@ pub struct EnableTwoFactorRequest {pub two_factor_secret_decryption_nonce: String,}+impl fmt::Debug for EnableTwoFactorRequest {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("EnableTwoFactorRequest")+ .field("code", &"[REDACTED]")+ .field("encrypted_two_factor_secret", &"[REDACTED]")+ .field("two_factor_secret_decryption_nonce", &"[REDACTED]")+ .finish()+ }+}+// ========== User Models ==========#[derive(Debug, Deserialize)]diff --git a/rust/cli/src/auth_flow.rs b/rust/cli/src/auth_flow.rsindex 2cac3d21a8..2325c9d56b 100644--- a/rust/cli/src/auth_flow.rs+++ b/rust/cli/src/auth_flow.rs@@ -23,7 +23,9 @@ use ente_core::{},crypto::{self, SecretVec, secretbox},};+use std::fmt;use uuid::Uuid;+use zeroize::Zeroizing;const SRP_A_LEN: usize = 512; // 4096-bit group@@ -67,27 +69,52 @@ pub trait AuthFlowUi {fn present_totp_secret(&mut self, secret_code: &str, qr_code: &str) -> Result<()>;}-#[derive(Debug)]pub struct CreateAccountParams {pub email: String,- pub password: String,+ pub password: Zeroizing<String>,pub source: Option<String>,}-#[derive(Debug)]+impl fmt::Debug for CreateAccountParams {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("CreateAccountParams")+ .field("email", &self.email)+ .field("password", &"[REDACTED]")+ .field("source", &self.source)+ .finish()+ }+}+pub struct LoginParams {pub email: String,- pub password: String,+ pub password: Zeroizing<String>,+}++impl fmt::Debug for LoginParams {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("LoginParams")+ .field("email", &self.email)+ .field("password", &"[REDACTED]")+ .finish()+ }}-#[derive(Debug)]pub struct SetupTwoFactorParams {pub account_id: String,- pub master_key: Vec<u8>,+ pub master_key: SecretVec,pub key_attributes: Option<KeyAttributes>,}-#[derive(Debug)]+impl fmt::Debug for SetupTwoFactorParams {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("SetupTwoFactorParams")+ .field("account_id", &self.account_id)+ .field("master_key", &"[REDACTED]")+ .field("key_attributes", &self.key_attributes)+ .finish()+ }+}+pub struct AuthenticatedAccount {pub user_id: i64,pub key_attributes: KeyAttributes,@@ -95,13 +122,33 @@ pub struct AuthenticatedAccount {pub recovery_key: Option<String>,}-#[derive(Debug)]+impl fmt::Debug for AuthenticatedAccount {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("AuthenticatedAccount")+ .field("user_id", &self.user_id)+ .field("key_attributes", &self.key_attributes)+ .field("secrets", &self.secrets)+ .field("recovery_key", &"[REDACTED]")+ .finish()+ }+}+pub struct SetupTwoFactorResult {pub secret_code: String,pub qr_code: String,pub recovery_key: String,}+impl fmt::Debug for SetupTwoFactorResult {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("SetupTwoFactorResult")+ .field("secret_code", &"[REDACTED]")+ .field("qr_code", &"[REDACTED]")+ .field("recovery_key", &"[REDACTED]")+ .finish()+ }+}+pub struct AuthFlow<'a, U> {api_client: &'a ApiClient,app: App,@@ -191,7 +238,7 @@ where)?;let secrets = AccountSecrets {- token: decode_plain_token(&token)?,+ token: decode_plain_token(&token)?.into_vec(),master_key: crypto::decode_b64(&key_gen_result.private_key_attributes.key)?,secret_key: crypto::decode_b64(&key_gen_result.private_key_attributes.secret_key)?,public_key: crypto::decode_b64(&key_attributes.public_key)?,@@ -537,11 +584,12 @@ fn to_api_key_attributes(attributes: &CoreKeyAttributes) -> KeyAttributes {}}-fn decode_plain_token(token: &str) -> Result<Vec<u8>> {- URL_SAFE+fn decode_plain_token(token: &str) -> Result<SecretVec> {+ let bytes = URL_SAFE.decode(token).or_else(|_| STANDARD.decode(token))- .map_err(|e| Error::Crypto(format!("token: {e}")))+ .map_err(|e| Error::Crypto(format!("token: {e}")))?;+ Ok(SecretVec::new(bytes))}fn decrypt_auth_response(@@ -556,7 +604,7 @@ fn decrypt_auth_response(Ok(DecryptedSecrets {master_key,secret_key,- token: SecretVec::new(decode_plain_token(token)?),+ token: decode_plain_token(token)?,})} else {Err(Error::AuthenticationFailed("No token in response".into()))@@ -843,7 +891,7 @@ mod tests {let result = flow.login(LoginParams {email: "[email protected]".into(),- password: password.into(),+ password: Zeroizing::new(password.into()),}).await.unwrap();@@ -942,7 +990,7 @@ mod tests {let result = flow.login(LoginParams {email: "[email protected]".into(),- password: password.into(),+ password: Zeroizing::new(password.into()),}).await.unwrap();@@ -1007,7 +1055,7 @@ mod tests {let result = flow.setup_two_factor(SetupTwoFactorParams {account_id: "[email protected]".into(),- master_key,+ master_key: SecretVec::new(master_key),key_attributes: Some(key_attributes),}).await@@ -1219,7 +1267,7 @@ mod tests {let result = flow.create_account(CreateAccountParams {email: email.into(),- password: "correct horse battery staple".into(),+ password: Zeroizing::new("correct horse battery staple".into()),source: Some("testAccount".into()),}).awaitdiff --git a/rust/cli/src/commands/account.rs b/rust/cli/src/commands/account.rsindex 51872eaee3..dd7a9aa08f 100644--- a/rust/cli/src/commands/account.rs+++ b/rust/cli/src/commands/account.rs@@ -13,7 +13,9 @@ use crate::{};use base64::Engine;use dialoguer::{Input, Password, Select};+use ente_core::crypto::SecretVec;use std::{path::PathBuf, str::FromStr};+use zeroize::Zeroizing;pub async fn handle_account_command(cmd: AccountCommand, storage: &Storage) -> Result<()> {match cmd.command {@@ -259,7 +261,7 @@ async fn add_account(let email = prompt_email(email_arg)?;let interactive_password = password_arg.is_none();- let mut password = prompt_password(password_arg, "Enter your password")?;+ let mut password = Zeroizing::new(prompt_password(password_arg, "Enter your password")?);let app = resolve_app(app_arg)?;let second_factor = parse_second_factor(second_factor.as_deref())?;@@ -285,7 +287,7 @@ async fn add_account(Ok(authenticated) => break authenticated,Err(error) if interactive_password && is_retryable_password_error(&error) => {println!("\nIncorrect password. Try again.");- password = prompt_password(None, "Re-enter your password")?;+ password = Zeroizing::new(prompt_password(None, "Re-enter your password")?);}Err(error) => return Err(error),}@@ -319,7 +321,7 @@ async fn create_account(println!("\n=== Create Ente Account ===\n");let email = prompt_email(email_arg)?;- let password = prompt_password(password_arg, "Choose a password")?;+ let password = Zeroizing::new(prompt_password(password_arg, "Choose a password")?);let app = resolve_app(app_arg)?;if let Ok(Some(_)) = storage.accounts().get(&email, app) {@@ -383,7 +385,7 @@ async fn create_account(let result = flow.setup_two_factor(SetupTwoFactorParams {account_id: email.clone(),- master_key: two_factor_master_key,+ master_key: SecretVec::new(two_factor_master_key),key_attributes: Some(two_factor_key_attributes),}).await?;@@ -423,7 +425,7 @@ async fn enable_two_factor(let result = flow.setup_two_factor(SetupTwoFactorParams {account_id: account.email.clone(),- master_key: secrets.master_key.clone(),+ master_key: SecretVec::new(secrets.master_key.clone()),key_attributes: None,}).await?;diff --git a/rust/cli/src/models/account.rs b/rust/cli/src/models/account.rsindex b7b3e0293a..d0dfcc32c8 100644--- a/rust/cli/src/models/account.rs+++ b/rust/cli/src/models/account.rs@@ -63,7 +63,7 @@ impl Account {}}-#[derive(Debug, Serialize, Deserialize, Zeroize)]+#[derive(Serialize, Deserialize, Zeroize)]#[zeroize(drop)]pub struct AccountSecrets {pub token: Vec<u8>,@@ -71,3 +71,36 @@ pub struct AccountSecrets {pub secret_key: Vec<u8>,pub public_key: Vec<u8>,}++impl fmt::Debug for AccountSecrets {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ f.debug_struct("AccountSecrets")+ .field("token", &"[REDACTED]")+ .field("master_key", &"[REDACTED]")+ .field("secret_key", &"[REDACTED]")+ .field("public_key_len", &self.public_key.len())+ .finish()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_account_secrets_debug_redacts_secret_material() {+ let secrets = AccountSecrets {+ token: vec![1, 2, 3],+ master_key: vec![4, 5, 6],+ secret_key: vec![7, 8, 9],+ public_key: vec![10, 11, 12],+ };++ let debug = format!("{secrets:?}");+ assert!(debug.contains("[REDACTED]"));+ assert!(!debug.contains("[1, 2, 3]"));+ assert!(!debug.contains("[4, 5, 6]"));+ assert!(!debug.contains("[7, 8, 9]"));+ assert!(debug.contains("public_key_len"));+ }+}diff --git a/rust/cli/tests/auth_live.rs b/rust/cli/tests/auth_live.rsindex 92b6dbd0f9..2760ddfd82 100644--- a/rust/cli/tests/auth_live.rs+++ b/rust/cli/tests/auth_live.rs@@ -1,5 +1,6 @@use std::time::{Duration, SystemTime, UNIX_EPOCH};+use ente_core::crypto::SecretVec;use ente_rs::{api::ApiClient,auth_flow::{@@ -11,6 +12,7 @@ use ente_rs::{use hmac::{Hmac, Mac};use sha1::Sha1;use uuid::Uuid;+use zeroize::Zeroizing;type HmacSha1 = Hmac<Sha1>;@@ -105,7 +107,7 @@ async fn live_create_login_and_enable_totp() {let mut flow = AuthFlow::new(&create_api, App::Photos, &mut ui);flow.create_account(CreateAccountParams {email: email.clone(),- password: password.clone(),+ password: Zeroizing::new(password.clone()),source: Some("testAccount".into()),}).await@@ -126,7 +128,7 @@ async fn live_create_login_and_enable_totp() {let mut flow = AuthFlow::new(&login_api, App::Photos, &mut ui);flow.login(LoginParams {email: email.clone(),- password: password.clone(),+ password: Zeroizing::new(password.clone()),}).await})@@ -141,7 +143,7 @@ async fn live_create_login_and_enable_totp() {let mut flow = AuthFlow::new(&create_api, App::Photos, &mut ui);flow.setup_two_factor(SetupTwoFactorParams {account_id: email.clone(),- master_key: created_master_key.clone(),+ master_key: SecretVec::new(created_master_key.clone()),key_attributes: Some(created_key_attributes),}).await@@ -162,7 +164,7 @@ async fn live_create_login_and_enable_totp() {let mut flow = AuthFlow::new(&login_after_2fa_api, App::Photos, &mut ui);flow.login(LoginParams {email: email.clone(),- password: password.clone(),+ password: Zeroizing::new(password.clone()),}).await})diff --git a/rust/core/src/auth/srp.rs b/rust/core/src/auth/srp.rsindex 3c8a9797e1..a8f546a302 100644--- a/rust/core/src/auth/srp.rs+++ b/rust/core/src/auth/srp.rs@@ -27,7 +27,7 @@ pub struct SrpSession {salt: Vec<u8>,a_private: SecretVec,a_public: Vec<u8>,- m1: Option<Vec<u8>>,+ m1: Option<SecretVec>,k: Option<SecretVec>,}@@ -126,7 +126,7 @@ impl SrpSession {k_hasher.update(&s_padded);let k = k_hasher.finalize().to_vec();- self.m1 = Some(m1.clone());+ self.m1 = Some(SecretVec::new(m1.clone()));self.k = Some(SecretVec::new(k));// No longer needed after we have computed M1/K.@@ -173,6 +173,9 @@ impl Drop for SrpSession {fn drop(&mut self) {self.login_key.zeroize();self.a_private.zeroize();+ if let Some(m1) = &mut self.m1 {+ m1.zeroize();+ }if let Some(k) = &mut self.k {k.zeroize();}@@ -285,11 +288,11 @@ mod tests {let expected_k = k_hasher.finalize().to_vec();assert_eq!(m1, expected_m1);- assert_eq!(session.m1.as_ref().unwrap(), &expected_m1);assert_eq!(- session.k.as_ref().unwrap().as_ref(),- expected_k.as_slice()+ session.m1.as_ref().unwrap().as_ref(),+ expected_m1.as_slice());+ assert_eq!(session.k.as_ref().unwrap().as_ref(), expected_k.as_slice());let mut m2_hasher = Sha256::new();m2_hasher.update(&a_padded);diff --git a/rust/core/src/crypto/error.rs b/rust/core/src/crypto/error.rsindex fd0e4227ba..d7f3fe8520 100644--- a/rust/core/src/crypto/error.rs+++ b/rust/core/src/crypto/error.rs@@ -102,6 +102,10 @@ pub enum CryptoError {#[error("Hash computation failed")]HashFailed,+ /// JSON serialization or deserialization failed.+ #[error("JSON error: {0}")]+ Json(String),+/// Argon2 error.#[error("Argon2 error: {0:?}")]Argon2(argon2::Error),diff --git a/rust/core/src/crypto/impl_pure/blob.rs b/rust/core/src/crypto/impl_pure/blob.rsindex fd3283ef8f..9999390e3e 100644--- a/rust/core/src/crypto/impl_pure/blob.rs+++ b/rust/core/src/crypto/impl_pure/blob.rs@@ -132,9 +132,8 @@ pub fn decrypt_blob(blob: &EncryptedBlob, key: &[u8]) -> Result<Vec<u8>> {/// # Returns/// An [`EncryptedBlob`] containing the encrypted JSON.pub fn encrypt_json<T: serde::Serialize>(value: &T, key: &[u8]) -> Result<EncryptedBlob> {- let json = serde_json::to_vec(value).map_err(|e| {- CryptoError::InvalidKeyDerivationParams(format!("JSON serialization failed: {}", e))- })?;+ let json = serde_json::to_vec(value)+ .map_err(|e| CryptoError::Json(format!("JSON serialization failed: {}", e)))?;encrypt(&json, key)}@@ -148,9 +147,8 @@ pub fn encrypt_json<T: serde::Serialize>(value: &T, key: &[u8]) -> Result<Encryp/// The deserialized JSON value.pub fn decrypt_json<T: serde::de::DeserializeOwned>(blob: &EncryptedBlob, key: &[u8]) -> Result<T> {let plaintext = decrypt_blob(blob, key)?;- serde_json::from_slice(&plaintext).map_err(|e| {- CryptoError::InvalidKeyDerivationParams(format!("JSON deserialization failed: {}", e))- })+ serde_json::from_slice(&plaintext)+ .map_err(|e| CryptoError::Json(format!("JSON deserialization failed: {}", e)))}#[cfg(test)]diff --git a/rust/core/src/crypto/impl_pure/sealed.rs b/rust/core/src/crypto/impl_pure/sealed.rsindex edbcb96868..9b761cbaf4 100644--- a/rust/core/src/crypto/impl_pure/sealed.rs+++ b/rust/core/src/crypto/impl_pure/sealed.rs@@ -117,7 +117,7 @@ pub fn seal(plaintext: &[u8], recipient_pk: &[u8]) -> Result<Vec<u8>> {}// Derive encryption key- let box_key = derive_box_key(shared_secret.as_bytes());+ let mut box_key = derive_box_key(shared_secret.as_bytes());// Compute noncelet nonce = seal_nonce(ephemeral_public.as_bytes(), &recipient_pk_arr);@@ -127,7 +127,10 @@ pub fn seal(plaintext: &[u8], recipient_pk: &[u8]) -> Result<Vec<u8>> {let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(&box_key));let encrypted = cipher.encrypt(GenericArray::from_slice(&nonce), plaintext)- .map_err(|_| CryptoError::EncryptionFailed)?;+ .map_err(|_| {+ box_key.zeroize();+ CryptoError::EncryptionFailed+ })?;// Build output: ephemeral_pk || MAC || ciphertextlet mut result = Vec::with_capacity(32 + encrypted.len());@@ -136,6 +139,7 @@ pub fn seal(plaintext: &[u8], recipient_pk: &[u8]) -> Result<Vec<u8>> {// Clean up sensitive dataephemeral_secret_bytes.zeroize();+ box_key.zeroize();Ok(result)}@@ -178,10 +182,11 @@ pub fn open(ciphertext: &[u8], recipient_pk: &[u8], recipient_sk: &[u8]) -> Resulet encrypted = &ciphertext[32..]; // MAC || ciphertextlet ephemeral_pk = PublicKey::from(ephemeral_pk_bytes);- let recipient_sk_arr: [u8; 32] = recipient_sk+ let mut recipient_sk_arr: [u8; 32] = recipient_sk.try_into().map_err(|_| CryptoError::ArrayConversion)?;let recipient_sk_key = StaticSecret::from(recipient_sk_arr);+ recipient_sk_arr.zeroize();let recipient_pk_arr: [u8; 32] = recipient_pk.try_into().map_err(|_| CryptoError::ArrayConversion)?;@@ -195,16 +200,21 @@ pub fn open(ciphertext: &[u8], recipient_pk: &[u8], recipient_sk: &[u8]) -> Resu}// Derive encryption key- let box_key = derive_box_key(shared_secret.as_bytes());+ let mut box_key = derive_box_key(shared_secret.as_bytes());// Compute noncelet nonce = seal_nonce(&ephemeral_pk_bytes, &recipient_pk_arr);// Decrypt (RustCrypto expects same format: MAC || ciphertext)let cipher = XSalsa20Poly1305::new(GenericArray::from_slice(&box_key));- cipher+ let plaintext = cipher.decrypt(GenericArray::from_slice(&nonce), encrypted)- .map_err(|_| CryptoError::DecryptionFailed)+ .map_err(|_| {+ box_key.zeroize();+ CryptoError::DecryptionFailed+ })?;+ box_key.zeroize();+ Ok(plaintext)}#[cfg(test)]diff --git a/rust/core/src/crypto/mod.rs b/rust/core/src/crypto/mod.rsindex 176dc9a330..50ae322e40 100644--- a/rust/core/src/crypto/mod.rs+++ b/rust/core/src/crypto/mod.rs@@ -82,7 +82,7 @@ pub use error::{CryptoError, 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(Clone, Default, Eq, PartialEq, Hash)]+#[derive(Default, Eq, PartialEq, Hash)]pub struct SecretVec(Vec<u8>);impl SecretVec {