matrix_sdk/encryption/secret_storage/secret_store.rs
1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::fmt;
16
17use matrix_sdk_base::crypto::{secret_storage::SecretStorageKey, CrossSigningKeyExport};
18use ruma::{
19 events::{
20 secret::request::SecretName, secret_storage::secret::SecretEventContent,
21 GlobalAccountDataEventType,
22 },
23 serde::Raw,
24};
25use serde_json::value::to_raw_value;
26use tracing::{
27 error,
28 field::{debug, display},
29 info, instrument, warn, Span,
30};
31use zeroize::Zeroize;
32
33use super::{DecryptionError, Result};
34use crate::Client;
35
36#[cfg_attr(doc, aquamarine::aquamarine)]
37/// Secure key/value storage for Matrix users.
38///
39/// The `SecretStore` struct encapsulates the secret storage mechanism for
40/// Matrix users, as it is specified in the [Matrix specification].
41///
42/// This specialized storage is tied to the user's Matrix account and serves as
43/// an encrypted key/value store, backed by [account data] residing on the
44/// homeserver. Any secrets uploaded to the homeserver using the
45/// [`SecretStore::put_secret()`] method are automatically encrypted by the
46/// [`SecretStore`].
47///
48/// [`SecretStore`] enables you to safely manage and access sensitive
49/// information while ensuring that it remains protected from unauthorized
50/// access. It plays a crucial role in maintaining the privacy and security of a
51/// Matrix user's data.
52///
53/// **Data Flow Overview:**
54/// ```mermaid
55/// flowchart LR
56/// subgraph Client
57/// SecretStore
58/// end
59/// subgraph Homeserver
60/// data[Account Data]
61/// end
62/// SecretStore <== Encrypted ==> data
63/// ```
64///
65/// **Note**: It's important to emphasize that the `SecretStore` should not be
66/// used for storing large volumes of data due to its nature as a key/value
67/// store for sensitive information.
68///
69/// # Examples
70///
71/// ```no_run
72/// # use matrix_sdk::Client;
73/// # use url::Url;
74/// # async {
75/// # let homeserver = Url::parse("http://example.com")?;
76/// # let client = Client::new(homeserver).await?;
77/// use ruma::events::secret::request::SecretName;
78///
79/// let secret_store = client
80/// .encryption()
81/// .secret_storage()
82/// .open_secret_store("It's a secret to everybody")
83/// .await?;
84///
85/// let my_secret = "Top secret secret";
86/// let my_secret_name = SecretName::from("m.treasure");
87///
88/// secret_store.put_secret(my_secret_name, my_secret);
89///
90/// # anyhow::Ok(()) };
91/// ```
92///
93/// [Matrix specification]: https://spec.matrix.org/v1.8/client-server-api/#secret-storage
94/// [account data]: https://spec.matrix.org/v1.8/client-server-api/#client-config
95pub struct SecretStore {
96 pub(super) client: Client,
97 pub(super) key: SecretStorageKey,
98}
99
100impl SecretStore {
101 /// Export the [`SecretStorageKey`] of this [`SecretStore`] as a
102 /// base58-encoded string as defined in the [spec].
103 ///
104 /// *Note*: This returns a copy of the private key material of the
105 /// [`SecretStorageKey`] as a string. The caller needs to ensure that this
106 /// string is zeroized.
107 ///
108 /// [spec]: https://spec.matrix.org/v1.8/client-server-api/#key-representation
109 pub fn secret_storage_key(&self) -> String {
110 self.key.to_base58()
111 }
112
113 /// Retrieve a secret from the homeserver's account data
114 ///
115 /// This method allows you to retrieve a secret from the account data stored
116 /// on the Matrix homeserver.
117 ///
118 /// # Arguments
119 ///
120 /// - `secret_name`: The name of the secret. The provided `secret_name`
121 /// serves as the event type for the associated account data event.
122 ///
123 /// The `retrieve_secret` method enables you to access and decrypt secrets
124 /// previously stored in the user's account data on the homeserver. You can
125 /// use the `secret_name` parameter to specify the desired secret to
126 /// retrieve.
127 ///
128 /// # Examples
129 ///
130 /// ```no_run
131 /// # use matrix_sdk::Client;
132 /// # use url::Url;
133 /// # async {
134 /// # let homeserver = Url::parse("http://example.com")?;
135 /// # let client = Client::new(homeserver).await?;
136 /// use ruma::events::secret::request::SecretName;
137 ///
138 /// let secret_store = client
139 /// .encryption()
140 /// .secret_storage()
141 /// .open_secret_store("It's a secret to everybody")
142 /// .await?;
143 ///
144 /// let my_secret_name = SecretName::from("m.treasure");
145 ///
146 /// let secret = secret_store.get_secret(my_secret_name).await?;
147 ///
148 /// # anyhow::Ok(()) };
149 /// ```
150 pub async fn get_secret(&self, secret_name: impl Into<SecretName>) -> Result<Option<String>> {
151 let secret_name = secret_name.into();
152 let event_type = GlobalAccountDataEventType::from(secret_name.to_owned());
153
154 if let Some(secret_content) = self.client.account().fetch_account_data(event_type).await? {
155 let mut secret_content = secret_content.deserialize_as::<SecretEventContent>()?;
156
157 // The `SecretEventContent` contains a map from the secret storage key ID to the
158 // ciphertext. Let's try to find a secret which was encrypted using our
159 // [`SecretStorageKey`].
160 if let Some(secret_content) = secret_content.encrypted.remove(self.key.key_id()) {
161 // We found a secret we should be able to decrypt, let's try to do so.
162 let decrypted = self
163 .key
164 .decrypt(&secret_content.try_into()?, &secret_name)
165 .map_err(DecryptionError::from)?;
166
167 let secret = String::from_utf8(decrypted).map_err(DecryptionError::from)?;
168
169 Ok(Some(secret))
170 } else {
171 // We did not find a secret which was encrypted using our [`SecretStorageKey`],
172 // no need to try to decrypt.
173 Ok(None)
174 }
175 } else {
176 Ok(None)
177 }
178 }
179
180 /// Store a secret in the homeserver's account data
181 ///
182 /// This method allows you to securely store a secret on the Matrix
183 /// homeserver as an encrypted account data event.
184 ///
185 /// # Arguments
186 ///
187 /// - `secret_name`: The name of the secret. The provided `secret_name`
188 /// serves as the event type for the account data event on the homeserver.
189 ///
190 /// - `secret`: The secret to be stored on the homeserver. The secret is
191 /// encrypted before being stored, ensuring its confidentiality and
192 /// integrity.
193 ///
194 /// # Examples
195 ///
196 /// ```no_run
197 /// # use matrix_sdk::Client;
198 /// # use url::Url;
199 /// # async {
200 /// # let homeserver = Url::parse("http://example.com")?;
201 /// # let client = Client::new(homeserver).await?;
202 /// use ruma::events::secret::request::SecretName;
203 ///
204 /// let secret_store = client
205 /// .encryption()
206 /// .secret_storage()
207 /// .open_secret_store("It's a secret to everybody")
208 /// .await?;
209 ///
210 /// let my_secret = "Top secret secret";
211 /// let my_secret_name = SecretName::from("m.treasure");
212 ///
213 /// secret_store.put_secret(my_secret_name, my_secret);
214 ///
215 /// # anyhow::Ok(()) };
216 /// ```
217 pub async fn put_secret(&self, secret_name: impl Into<SecretName>, secret: &str) -> Result<()> {
218 // This function does a read/update/store of an account data event stored on the
219 // homeserver. We first fetch the existing account data event, the event
220 // contains a map which gets updated by this method, finally we upload the
221 // modified event.
222 //
223 // To prevent multiple calls to this method trying to update a secret at the
224 // same time, and thus trampling on each other we introduce a lock which
225 // acts as a semaphore.
226 //
227 // Technically there's a low chance of this happening since we're not storing
228 // many secrets and the bigger problem is that another client might be
229 // doing this as well and the server doesn't have a mechanism to protect against
230 // this.
231 //
232 // We could make this lock be per `secret_name` but this is not a performance
233 // critical method.
234 let _guard = self.client.locks().store_secret_lock.lock().await;
235
236 let secret_name = secret_name.into();
237 let event_type = GlobalAccountDataEventType::from(secret_name.to_owned());
238
239 // Get the existing account data event or create a new empty one.
240 let mut secret_content = if let Some(secret_content) =
241 self.client.account().fetch_account_data(event_type.to_owned()).await?
242 {
243 secret_content
244 .deserialize_as::<SecretEventContent>()
245 .unwrap_or_else(|_| SecretEventContent::new(Default::default()))
246 } else {
247 SecretEventContent::new(Default::default())
248 };
249
250 // Encrypt the secret.
251 let secret = secret.as_bytes().to_vec();
252 let encrypted_secret = self.key.encrypt(secret, &secret_name);
253
254 // Insert the encrypted secret into the account data event.
255 secret_content.encrypted.insert(self.key.key_id().to_owned(), encrypted_secret.into());
256 let secret_content = Raw::from_json(to_raw_value(&secret_content)?);
257
258 // Upload the modified account data event, now that the new secret has been
259 // inserted.
260 self.client.account().set_account_data_raw(event_type, secret_content).await?;
261
262 Ok(())
263 }
264
265 /// Get all the well-known private parts/keys of the [`OwnUserIdentity`] as
266 /// a [`CrossSigningKeyExport`].
267 ///
268 /// The export can be imported into the [`OlmMachine`] using
269 /// [`OlmMachine::import_cross_signing_keys()`].
270 async fn get_cross_signing_keys(&self) -> Result<CrossSigningKeyExport> {
271 let mut export = CrossSigningKeyExport::default();
272
273 export.master_key = self.get_secret(SecretName::CrossSigningMasterKey).await?;
274 export.self_signing_key = self.get_secret(SecretName::CrossSigningSelfSigningKey).await?;
275 export.user_signing_key = self.get_secret(SecretName::CrossSigningUserSigningKey).await?;
276
277 Ok(export)
278 }
279
280 async fn put_cross_signing_keys(&self, export: CrossSigningKeyExport) -> Result<()> {
281 if let Some(master_key) = &export.master_key {
282 self.put_secret(SecretName::CrossSigningMasterKey, master_key).await?;
283 }
284
285 if let Some(user_signing_key) = &export.user_signing_key {
286 self.put_secret(SecretName::CrossSigningUserSigningKey, user_signing_key).await?;
287 }
288
289 if let Some(self_signing_key) = &export.self_signing_key {
290 self.put_secret(SecretName::CrossSigningSelfSigningKey, self_signing_key).await?;
291 }
292
293 Ok(())
294 }
295
296 async fn maybe_enable_backups(&self) -> Result<()> {
297 if let Some(mut secret) = self.get_secret(SecretName::RecoveryKey).await? {
298 let ret = self.client.encryption().backups().maybe_enable_backups(&secret).await;
299
300 if let Err(e) = &ret {
301 warn!("Could not enable backups from secret storage: {e:?}");
302 }
303
304 secret.zeroize();
305
306 Ok(ret.map(|_| ())?)
307 } else {
308 info!("No backup recovery key found.");
309
310 Ok(())
311 }
312 }
313
314 /// Retrieve and store well-known secrets locally
315 ///
316 /// This method retrieves and stores all well-known secrets from the account
317 /// data on the Matrix homeserver to enhance local security and identity
318 /// verification.
319 ///
320 /// The following secrets are retrieved by this method:
321 ///
322 /// - `m.cross_signing.master`: The master cross-signing key.
323 /// - `m.cross_signing.self_signing`: The self-signing cross-signing key.
324 /// - `m.cross_signing.user_signing`: The user-signing cross-signing key.
325 /// - `m.megolm_backup.v1`: The backup recovery key.
326 ///
327 /// If the `m.cross_signing.self_signing` key is successfully imported, it
328 /// is used to sign our own [`Device`], marking it as verified. This step is
329 /// establishes trust in your own device's identity.
330 ///
331 /// By invoking this method, you ensure that your device has access to
332 /// the necessary secrets for device and identity verification.
333 ///
334 /// # Examples
335 ///
336 /// ```no_run
337 /// # use matrix_sdk::Client;
338 /// # use url::Url;
339 /// # async {
340 /// # let homeserver = Url::parse("http://example.com")?;
341 /// # let client = Client::new(homeserver).await?;
342 /// use ruma::events::secret::request::SecretName;
343 ///
344 /// let secret_store = client
345 /// .encryption()
346 /// .secret_storage()
347 /// .open_secret_store("It's a secret to everybody")
348 /// .await?;
349 ///
350 /// secret_store.import_secrets().await?;
351 ///
352 /// let status = client
353 /// .encryption()
354 /// .cross_signing_status()
355 /// .await
356 /// .expect("We should be able to check out cross-signing status");
357 ///
358 /// println!("Cross-signing status {status:?}");
359 ///
360 /// # anyhow::Ok(()) };
361 /// ```
362 ///
363 /// [`Device`]: crate::encryption::identities::Device
364 #[instrument(fields(user_id, device_id, cross_signing_status))]
365 pub async fn import_secrets(&self) -> Result<()> {
366 let olm_machine = self.client.olm_machine().await;
367 let olm_machine = olm_machine.as_ref().ok_or(crate::Error::NoOlmMachine)?;
368
369 Span::current()
370 .record("user_id", display(olm_machine.user_id()))
371 .record("device_id", display(olm_machine.device_id()));
372
373 info!("Fetching the private cross-signing keys from the secret store");
374
375 // Get all our private cross-signing keys from the secret store.
376 let export = self.get_cross_signing_keys().await?;
377
378 info!(cross_signing_keys = ?export, "Received the cross signing keys from the server");
379
380 // We need to ensure that we have the public parts of the cross-signing keys,
381 // those are represented as the `OwnUserIdentity` struct. The public
382 // parts from the server are compared to the public parts re-derived from the
383 // private parts. We will only import the private parts of the cross-signing
384 // keys if they match to the public parts, otherwise we would risk
385 // importing some stale cross-signing keys leftover in the secret store.
386 let (request_id, request) = olm_machine.query_keys_for_users([olm_machine.user_id()]);
387 self.client.keys_query(&request_id, request.device_keys).await?;
388
389 // Let's now try to import our private cross-signing keys.
390 let status = olm_machine.import_cross_signing_keys(export).await?;
391
392 Span::current().record("cross_signing_status", debug(&status));
393
394 info!("Done importing the cross signing keys");
395
396 if status.has_self_signing {
397 info!("Successfully imported the self-signing key, attempting to sign our own device");
398
399 // Now that we successfully imported them, the self-signing key can be used to
400 // verify our own device so other devices and user identities trust
401 // it if the trust our user identity.
402 if let Some(own_device) = self.client.encryption().get_own_device().await? {
403 own_device.verify().await?;
404
405 // Another /keys/query request to ensure that the signatures we uploaded using
406 // `own_device.verify()` are attached to the `Device` we have in storage.
407 let (request_id, request) =
408 olm_machine.query_keys_for_users([olm_machine.user_id()]);
409 self.client.keys_query(&request_id, request.device_keys).await?;
410
411 info!("Successfully signed our own device, the device is now verified");
412 } else {
413 error!("Couldn't find our own device in the store");
414 }
415 }
416
417 self.maybe_enable_backups().await?;
418
419 Ok(())
420 }
421
422 pub(super) async fn export_secrets(&self) -> Result<()> {
423 let olm_machine = self.client.olm_machine().await;
424 let olm_machine = olm_machine.as_ref().ok_or(crate::Error::NoOlmMachine)?;
425
426 if let Some(cross_signing_keys) = olm_machine.export_cross_signing_keys().await? {
427 self.put_cross_signing_keys(cross_signing_keys).await?;
428 }
429
430 let backup_keys = olm_machine.backup_machine().get_backup_keys().await?;
431
432 if let Some(backup_recovery_key) = backup_keys.decryption_key {
433 let mut key = backup_recovery_key.to_base64();
434 self.put_secret(SecretName::RecoveryKey, &key).await?;
435
436 key.zeroize();
437 }
438
439 Ok(())
440 }
441}
442
443impl fmt::Debug for SecretStore {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 f.debug_struct("SecretStore").field("key", &self.key).finish_non_exhaustive()
446 }
447}