Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Harden Space key handling

Anand Baburajand74b11fa158a
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5d4097b70f..eaa6d51ee4 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -2524,6 +2524,7 @@ dependencies = [
"thiserror 2.0.18",
"tokio",
"urlencoding",
+ "zeroize",
]
[[package]]
diff --git a/rust/space/Cargo.toml b/rust/space/Cargo.toml
index ad043cd229..bf51812420 100644
--- a/rust/space/Cargo.toml
+++ b/rust/space/Cargo.toml
@@ -10,6 +10,7 @@ serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "2"
urlencoding = "2"
+zeroize = { version = "1.8", features = ["derive"] }
[dev-dependencies]
mockito = "1.6"
diff --git a/rust/space/src/client/mod.rs b/rust/space/src/client/mod.rs
index 19720c1363..257229d14f 100644
--- a/rust/space/src/client/mod.rs
+++ b/rust/space/src/client/mod.rs
@@ -34,7 +34,7 @@ use crate::transport::{
SpaceKeyVersionResponse, SpaceLookupResponse, SpaceProfileResponse, UpdateSpaceSlugRequest,
};
use ente_core::{
- crypto::{decode_b64, encode_b64},
+ crypto::{SecretVec, decode_b64, encode_b64},
http::{Api, ApiConfig, Auth, Http},
};
const UPLOAD_PURPOSE_AVATAR: &str = "avatar";
@@ -74,28 +74,35 @@ fn profile_object_id_from_key(object_key: &str) -> Result<String> {
.ok_or_else(|| SpaceError::InvalidInput("invalid profile asset object key".into()))
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub(crate) struct ResolvedSpaceAccess {
space_key: Vec<u8>,
key_version: i32,
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub(crate) struct ResolvedOwnedSpaceAccess {
space_key: Vec<u8>,
key_version: i32,
}
-#[derive(Debug, Clone)]
pub(crate) struct SpaceIdentity {
public_key: Vec<u8>,
- secret_key: Vec<u8>,
+ secret_key: SecretVec,
+}
+
+impl Clone for SpaceIdentity {
+ fn clone(&self) -> Self {
+ Self {
+ public_key: self.public_key.clone(),
+ secret_key: SecretVec::new(self.secret_key.to_vec()),
+ }
+ }
}
pub struct AccountSpaceCtx {
api: Api,
- space_root_key: Vec<u8>,
- space_root_key_cache: Mutex<Option<Option<Vec<u8>>>>,
+ space_root_key: SecretVec,
space_identity_cache: Mutex<BTreeMap<String, SpaceIdentity>>,
owned_spaces_cache: Mutex<Option<Vec<SpaceKeyResponse>>>,
friend_shares_cache: Mutex<BTreeMap<String, Vec<DecryptedFriendShare>>>,
@@ -103,6 +110,7 @@ pub struct AccountSpaceCtx {
impl AccountSpaceCtx {
pub fn open(input: OpenAccountSpaceCtxInput) -> Result<Self> {
+ let space_root_key = SecretVec::new(input.space_root_key);
let api = build_api(
&input.base_url,
input.space_session_token,
@@ -112,8 +120,7 @@ impl AccountSpaceCtx {
)?;
Ok(Self {
api,
- space_root_key: input.space_root_key,
- space_root_key_cache: Mutex::new(None),
+ space_root_key,
space_identity_cache: Mutex::new(BTreeMap::new()),
owned_spaces_cache: Mutex::new(None),
friend_shares_cache: Mutex::new(BTreeMap::new()),
@@ -129,14 +136,11 @@ impl AccountSpaceCtx {
}
pub async fn get_space_root_key(&self) -> Result<Option<Vec<u8>>> {
- Ok(Some(self.space_root_key.clone()))
+ Ok(Some(self.space_root_key.to_vec()))
}
pub async fn get_or_create_space_root_key(&self) -> Result<Vec<u8>> {
- let space_root_key = self.space_root_key.clone();
- *cache_lock(&self.space_root_key_cache, "space root key")? =
- Some(Some(space_root_key.clone()));
- Ok(space_root_key)
+ Ok(self.space_root_key.to_vec())
}
pub async fn list_owned_spaces(&self) -> Result<Vec<SpaceKeyResponse>> {
@@ -176,7 +180,7 @@ impl AccountSpaceCtx {
let secret_key = decrypt_secretbox_payload(&self.space_root_key, &encrypted_secret_key)?;
Ok(SpaceIdentity {
public_key,
- secret_key,
+ secret_key: SecretVec::new(secret_key),
})
}
@@ -338,7 +342,7 @@ impl AccountSpaceCtx {
response.space_id.clone(),
SpaceIdentity {
public_key,
- secret_key,
+ secret_key: SecretVec::new(secret_key),
},
);
Ok(CreatedSpace {
@@ -402,7 +406,7 @@ impl AccountSpaceCtx {
&self,
space_id: &str,
) -> Result<Option<ResolvedOwnedSpaceAccess>> {
- let space_root_key = match self.get_space_root_key_cached().await? {
+ let space_root_key = match self.get_space_root_key().await? {
Some(value) => value,
None => return Ok(None),
};
@@ -423,11 +427,11 @@ impl AccountSpaceCtx {
space_id: &str,
) -> Result<Option<ResolvedSpaceAccess>> {
let shares = self.list_all_decrypted_friend_shares().await?;
- let Some(share) = shares.into_iter().find(|value| value.space_id == space_id) else {
+ let Some(mut share) = shares.into_iter().find(|value| value.space_id == space_id) else {
return Ok(None);
};
Ok(Some(ResolvedSpaceAccess {
- space_key: share.space_key,
+ space_key: std::mem::take(&mut share.space_key),
key_version: share.key_version,
}))
}
@@ -450,11 +454,11 @@ impl AccountSpaceCtx {
let shares = self
.list_decrypted_friend_shares_cached(viewer_space_id)
.await?;
- let Some(share) = shares.into_iter().find(|value| value.space_id == space_id) else {
+ let Some(mut share) = shares.into_iter().find(|value| value.space_id == space_id) else {
return Ok(None);
};
Ok(Some(ResolvedSpaceAccess {
- space_key: share.space_key,
+ space_key: std::mem::take(&mut share.space_key),
key_version: share.key_version,
}))
}
@@ -515,15 +519,6 @@ impl AccountSpaceCtx {
Ok(history.get(&target_version).cloned())
}
- pub(crate) async fn get_space_root_key_cached(&self) -> Result<Option<Vec<u8>>> {
- if let Some(value) = cache_lock(&self.space_root_key_cache, "space root key")?.clone() {
- return Ok(value);
- }
- let value = self.get_space_root_key().await?;
- *cache_lock(&self.space_root_key_cache, "space root key")? = Some(value.clone());
- Ok(value)
- }
-
pub(crate) async fn list_owned_spaces_cached(&self) -> Result<Vec<SpaceKeyResponse>> {
if let Some(value) = cache_lock(&self.owned_spaces_cache, "owned spaces")?.clone() {
return Ok(value);
@@ -691,11 +686,12 @@ pub(super) fn build_api(
client_package: Option<String>,
client_version: Option<String>,
) -> Result<Api> {
+ let auth = space_session_token.map(Auth::SpaceSession);
Ok(Api::new(
Http::new()?,
ApiConfig {
origin: base_url.to_owned(),
- auth: space_session_token.map(Auth::SpaceSession),
+ auth,
user_agent,
client_package,
client_version,
diff --git a/rust/space/src/client/test_support.rs b/rust/space/src/client/test_support.rs
index aeabccda60..f1143e29f1 100644
--- a/rust/space/src/client/test_support.rs
+++ b/rust/space/src/client/test_support.rs
@@ -9,7 +9,7 @@ use serde_json::json;
use super::{AccountSpaceCtx, SpaceIdentity, cache_lock, generate_key, generate_keypair};
use crate::crypto::encrypt_secretbox_payload;
use crate::models::OpenAccountSpaceCtxInput;
-use ente_core::crypto::encode_b64;
+use ente_core::crypto::{SecretVec, encode_b64};
/// A WEBP magic-number header, enough for the media sniffer to accept the bytes
/// as a photo.
@@ -45,7 +45,7 @@ pub(crate) fn test_account_ctx_with_space_root_key(
"space_owner_main".to_owned(),
SpaceIdentity {
public_key,
- secret_key,
+ secret_key: SecretVec::new(secret_key),
},
);
ctx
diff --git a/rust/space/src/client/tests.rs b/rust/space/src/client/tests.rs
index 895dee6015..e386aa0946 100644
--- a/rust/space/src/client/tests.rs
+++ b/rust/space/src/client/tests.rs
@@ -14,6 +14,22 @@ use crate::transport::{
use mockito::{Matcher, Server};
use serde_json::json;
+use zeroize::Zeroize;
+
+#[test]
+fn decrypted_friend_share_zeroizes_its_key() {
+ let mut share = DecryptedFriendShare {
+ friend: "[email protected]".to_owned(),
+ space_id: "space-friend".to_owned(),
+ space_slug: "friend".to_owned(),
+ space_key: vec![42; 32],
+ key_version: 1,
+ };
+
+ share.zeroize();
+
+ assert!(share.space_key.is_empty());
+}
#[tokio::test]
async fn account_api_sends_space_session_token_header() {
diff --git a/rust/space/src/models.rs b/rust/space/src/models.rs
index efbf759870..f18414e418 100644
--- a/rust/space/src/models.rs
+++ b/rust/space/src/models.rs
@@ -1,10 +1,11 @@
use serde::{Deserialize, Serialize};
+use zeroize::Zeroize;
use crate::transport::{
PostObjectPayload, ProfileAvatarResponse, ProfileCoverResponse, SpaceActorResponse,
};
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct OpenAccountSpaceCtxInput {
pub base_url: String,
pub space_session_token: Option<String>,
@@ -14,7 +15,7 @@ pub struct OpenAccountSpaceCtxInput {
pub client_version: Option<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct CreatedSpace {
pub space_id: String,
pub space_slug: String,
@@ -36,7 +37,7 @@ pub struct DecryptedSpaceProfile {
pub updated_at: Option<String>,
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct DecryptedPost {
pub post_key: Vec<u8>,
pub caption_plaintext: Option<Vec<u8>>,
@@ -67,13 +68,14 @@ pub struct MessagePayload {
pub text: String,
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct DecryptedMessage {
pub message_key: Vec<u8>,
pub payload: MessagePayload,
}
-#[derive(Debug, Clone)]
+#[derive(Clone, Zeroize)]
+#[zeroize(drop)]
pub struct DecryptedFriendShare {
pub friend: String,
pub space_id: String,
@@ -107,7 +109,7 @@ pub struct FeedPage {
pub next_cursor: String,
}
-#[derive(Debug, Clone)]
+#[derive(Clone)]
pub struct HydratedKeys {
pub owned: Vec<(String, Vec<u8>)>,
pub friends: Vec<DecryptedFriendShare>,