bitwarden_crypto/store/mod.rs
1//!
2//! This module contains all the necessary parts to create an in-memory key store that can be used
3//! to securely store key and use them for encryption/decryption operations.
4//!
5//! ## Organization
6//!
7//! ### Key Identifiers
8//! To avoid having to pass key materials over the crate boundaries, the key store API uses key
9//! identifiers in its API. These key identifiers are user-defined types that contain no key
10//! material, and are used to uniquely identify each key in the store. The key store doesn't specify
11//! how these traits should be implemented, but we recommend using `enums`, and we provide an
12//! optional macro ([key_ids](crate::key_ids)) that makes it easier to define them.
13//!
14//! ### Key Store
15//! [KeyStore] is a thread-safe in-memory key store and the main entry point for using this module.
16//! It provides functionality to encrypt and decrypt data using the keys stored in the store. The
17//! store is designed to be used by a single user and should not be shared between users.
18//!
19//! ### Key Store Context
20//! From a [KeyStore], you can also create an instance of [KeyStoreContext], which initializes a
21//! temporary context-local key store for encryption/decryption operations that require the use of
22//! per-item keys (like cipher keys or send keys, for example). Any keys stored in the context-local
23//! store will be cleared when the context is dropped.
24
25use std::sync::{Arc, RwLock};
26
27use rayon::{iter::Either, prelude::*};
28
29use crate::{CompositeEncryptable, Decryptable, IdentifyKey, KeyId, KeyIds};
30
31mod backend;
32mod context;
33
34use backend::{StoreBackend, create_store};
35use context::GlobalKeys;
36pub use context::KeyStoreContext;
37
38mod key_rotation;
39pub use key_rotation::*;
40
41/// An in-memory key store that provides a safe and secure way to store keys and use them for
42/// encryption/decryption operations. The store API is designed to work only on key identifiers
43/// ([KeyId]). These identifiers are user-defined types that contain no key material, which means
44/// the API users don't have to worry about accidentally leaking keys.
45///
46/// Each store is designed to be used by a single user and should not be shared between users, but
47/// the store itself is thread safe and can be cloned to share between threads.
48///
49/// ```rust
50/// # use bitwarden_crypto::*;
51///
52/// // We need to define our own key identifier types. We provide a macro to make this easier.
53/// key_ids! {
54/// #[symmetric]
55/// pub enum SymmKeyId {
56/// User,
57/// #[local]
58/// Local(LocalId),
59/// }
60/// #[asymmetric]
61/// pub enum AsymmKeyId {
62/// UserPrivate,
63/// #[local]
64/// Local(LocalId),
65/// }
66/// #[signing]
67/// pub enum SigningKeyId {
68/// UserSigning,
69/// #[local]
70/// Local(LocalId),
71/// }
72/// pub Ids => SymmKeyId, AsymmKeyId, SigningKeyId;
73/// }
74///
75/// // Initialize the store and insert a test key
76/// let store: KeyStore<Ids> = KeyStore::default();
77///
78/// #[allow(deprecated)]
79/// store.context_mut().set_symmetric_key(SymmKeyId::User, SymmetricCryptoKey::make_aes256_cbc_hmac_key());
80///
81/// // Define some data that needs to be encrypted
82/// struct Data(String);
83/// impl IdentifyKey<SymmKeyId> for Data {
84/// fn key_identifier(&self) -> SymmKeyId {
85/// SymmKeyId::User
86/// }
87/// }
88/// impl CompositeEncryptable<Ids, SymmKeyId, EncString> for Data {
89/// fn encrypt_composite(&self, ctx: &mut KeyStoreContext<Ids>, key: SymmKeyId) -> Result<EncString, CryptoError> {
90/// self.0.encrypt(ctx, key)
91/// }
92/// }
93///
94/// // Encrypt the data
95/// let decrypted = Data("Hello, World!".to_string());
96/// let encrypted = store.encrypt(decrypted).unwrap();
97/// ```
98#[derive(Clone)]
99pub struct KeyStore<Ids: KeyIds> {
100 // We use an Arc<> to make it easier to pass this store around, as we can
101 // clone it instead of passing references
102 inner: Arc<RwLock<KeyStoreInner<Ids>>>,
103}
104
105/// [KeyStore] contains sensitive data, provide a dummy [Debug] implementation.
106impl<Ids: KeyIds> std::fmt::Debug for KeyStore<Ids> {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.debug_struct("KeyStore").finish()
109 }
110}
111
112struct KeyStoreInner<Ids: KeyIds> {
113 symmetric_keys: Box<dyn StoreBackend<Ids::Symmetric>>,
114 asymmetric_keys: Box<dyn StoreBackend<Ids::Asymmetric>>,
115 signing_keys: Box<dyn StoreBackend<Ids::Signing>>,
116 security_state_version: u64,
117}
118
119/// Create a new key store with the best available implementation for the current platform.
120impl<Ids: KeyIds> Default for KeyStore<Ids> {
121 fn default() -> Self {
122 Self {
123 inner: Arc::new(RwLock::new(KeyStoreInner {
124 symmetric_keys: create_store(),
125 asymmetric_keys: create_store(),
126 signing_keys: create_store(),
127 security_state_version: 1,
128 })),
129 }
130 }
131}
132
133impl<Ids: KeyIds> KeyStore<Ids> {
134 /// Clear all keys from the store. This can be used to clear all keys from memory in case of
135 /// lock/logout, and is equivalent to destroying the store and creating a new one.
136 pub fn clear(&self) {
137 let mut keys = self.inner.write().expect("RwLock is poisoned");
138 keys.symmetric_keys.clear();
139 keys.asymmetric_keys.clear();
140 keys.signing_keys.clear();
141 }
142
143 /// Sets the security state version for this store.
144 pub fn set_security_state_version(&self, version: u64) {
145 let mut data = self.inner.write().expect("RwLock is poisoned");
146 data.security_state_version = version;
147 }
148
149 /// Initiate an encryption/decryption context. This context will have read only access to the
150 /// global keys, and will have its own local key stores with read/write access. This
151 /// context-local store will be cleared when the context is dropped.
152 ///
153 /// If you are only looking to encrypt or decrypt items, you should implement
154 /// [CompositeEncryptable]/[Decryptable] and use the [KeyStore::encrypt], [KeyStore::decrypt],
155 /// [KeyStore::encrypt_list] and [KeyStore::decrypt_list] methods instead.
156 ///
157 /// The current implementation of context only clears the keys automatically when the context is
158 /// dropped, and not between operations. This means that if you are using the same context
159 /// for multiple operations, you may want to clear it manually between them. If possible, we
160 /// recommend using [KeyStore::encrypt_list] and [KeyStore::decrypt_list] instead.
161 ///
162 /// [KeyStoreContext] is not [Send] or [Sync] and should not be shared between threads. Note
163 /// that this can also be problematic in async code, and you should take care to ensure that
164 /// you're not holding references to the context across await points, as that would cause the
165 /// future to also not be [Send].
166 ///
167 /// Some other possible use cases for this API and alternative recommendations are:
168 /// - Decrypting or encrypting multiple [Decryptable] or [CompositeEncryptable] items while
169 /// sharing any local keys. This is not recommended as it can lead to fragile and flaky
170 /// decryption/encryption operations. We recommend any local keys to be used only in the
171 /// context of a single [CompositeEncryptable] or [Decryptable] implementation. In the future
172 /// we might enforce this.
173 /// - Obtaining the key material directly. We strongly recommend against doing this as it can
174 /// lead to key material being leaked, but we need to support it for backwards compatibility.
175 /// If you want to access the key material to encrypt it or derive a new key from it, we
176 /// provide functions for that:
177 /// - [KeyStoreContext::wrap_symmetric_key]
178 /// - [KeyStoreContext::encapsulate_key_unsigned]
179 /// - [KeyStoreContext::derive_shareable_key]
180 pub fn context(&'_ self) -> KeyStoreContext<'_, Ids> {
181 let data = self.inner.read().expect("RwLock is poisoned");
182 let security_state_version = data.security_state_version;
183 KeyStoreContext {
184 global_keys: GlobalKeys::ReadOnly(data),
185 local_symmetric_keys: create_store(),
186 local_asymmetric_keys: create_store(),
187 local_signing_keys: create_store(),
188 security_state_version,
189 _phantom: std::marker::PhantomData,
190 }
191 }
192
193 /// <div class="warning">
194 /// This is an advanced API, use with care and ONLY when needing to modify the global keys.
195 ///
196 /// The same pitfalls as [Self::context] apply here, but with the added risk of accidentally
197 /// modifying the global keys and leaving the store in an inconsistent state.
198 /// If you still need to use it, make sure you read this documentation to understand how to use
199 /// it safely. </div>
200 ///
201 /// Initiate an encryption/decryption context. This context will have MUTABLE access to the
202 /// global keys, and will have its own local key stores with read/write access. This
203 /// context-local store will be cleared up when the context is dropped.
204 ///
205 /// The only supported use case for this API is initializing the store with the user's symetric
206 /// and private keys, and setting the organization keys. This method will be marked as
207 /// `pub(crate)` in the future, once we have a safe API for key initialization and updating.
208 ///
209 /// [KeyStoreContext] is not [Send] or [Sync] and should not be shared between threads. Note
210 /// that this can also be problematic in async code, and you should take care to ensure that
211 /// you're not holding references to the context across await points, as that would cause the
212 /// future to also not be [Send].
213 pub fn context_mut(&'_ self) -> KeyStoreContext<'_, Ids> {
214 let inner = self.inner.write().expect("RwLock is poisoned");
215 let security_state_version = inner.security_state_version;
216 KeyStoreContext {
217 global_keys: GlobalKeys::ReadWrite(inner),
218 local_symmetric_keys: create_store(),
219 local_asymmetric_keys: create_store(),
220 local_signing_keys: create_store(),
221 security_state_version,
222 _phantom: std::marker::PhantomData,
223 }
224 }
225
226 /// Decript a single item using this key store. The key returned by `data.key_identifier()` must
227 /// already be present in the store, otherwise this will return an error.
228 /// This method is not parallelized, and is meant for single item decryption.
229 /// If you need to decrypt multiple items, use `decrypt_list` instead.
230 pub fn decrypt<Key: KeyId, Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key>, Output>(
231 &self,
232 data: &Data,
233 ) -> Result<Output, crate::CryptoError> {
234 let key = data.key_identifier();
235 data.decrypt(&mut self.context(), key)
236 }
237
238 /// Encrypt a single item using this key store. The key returned by `data.key_identifier()` must
239 /// already be present in the store, otherwise this will return an error.
240 /// This method is not parallelized, and is meant for single item encryption.
241 /// If you need to encrypt multiple items, use `encrypt_list` instead.
242 pub fn encrypt<
243 Key: KeyId,
244 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key>,
245 Output,
246 >(
247 &self,
248 data: Data,
249 ) -> Result<Output, crate::CryptoError> {
250 let key = data.key_identifier();
251 data.encrypt_composite(&mut self.context(), key)
252 }
253
254 /// Decrypt a list of items using this key store. The keys returned by
255 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
256 /// return an error. This method will try to parallelize the decryption of the items, for
257 /// better performance on large lists.
258 pub fn decrypt_list<
259 Key: KeyId,
260 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
261 Output: Send + Sync,
262 >(
263 &self,
264 data: &[Data],
265 ) -> Result<Vec<Output>, crate::CryptoError> {
266 let res: Result<Vec<_>, _> = data
267 .par_chunks(batch_chunk_size(data.len()))
268 .map(|chunk| {
269 let mut ctx = self.context();
270
271 let mut result = Vec::with_capacity(chunk.len());
272
273 for item in chunk {
274 let key = item.key_identifier();
275 result.push(item.decrypt(&mut ctx, key));
276 ctx.clear_local();
277 }
278
279 result
280 })
281 .flatten()
282 .collect();
283
284 res
285 }
286
287 /// Decrypt a list of items using this key store, returning a tuple of successful and failed
288 /// items.
289 ///
290 /// # Arguments
291 /// * `data` - The list of items to decrypt.
292 ///
293 /// # Returns
294 /// A tuple containing two vectors: the first vector contains the successfully decrypted items,
295 /// and the second vector contains the original items that failed to decrypt.
296 pub fn decrypt_list_with_failures<
297 'a,
298 Key: KeyId,
299 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync + 'a,
300 Output: Send + Sync,
301 >(
302 &self,
303 data: &'a [Data],
304 ) -> (Vec<Output>, Vec<&'a Data>) {
305 let results: (Vec<_>, Vec<_>) = data
306 .par_chunks(batch_chunk_size(data.len()))
307 .flat_map(|chunk| {
308 let mut ctx = self.context();
309
310 chunk
311 .iter()
312 .map(|item| {
313 let result = item
314 .decrypt(&mut ctx, item.key_identifier())
315 .map_err(|_| item);
316 ctx.clear_local();
317 result
318 })
319 .collect::<Vec<_>>()
320 })
321 .partition_map(|result| match result {
322 Ok(output) => Either::Left(output),
323 Err(original_item) => Either::Right(original_item),
324 });
325
326 results
327 }
328
329 /// Encrypt a list of items using this key store. The keys returned by
330 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
331 /// return an error. This method will try to parallelize the encryption of the items, for
332 /// better performance on large lists. This method is not parallelized, and is meant for
333 /// single item encryption.
334 pub fn encrypt_list<
335 Key: KeyId,
336 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
337 Output: Send + Sync,
338 >(
339 &self,
340 data: &[Data],
341 ) -> Result<Vec<Output>, crate::CryptoError> {
342 let res: Result<Vec<_>, _> = data
343 .par_chunks(batch_chunk_size(data.len()))
344 .map(|chunk| {
345 let mut ctx = self.context();
346
347 let mut result = Vec::with_capacity(chunk.len());
348
349 for item in chunk {
350 let key = item.key_identifier();
351 result.push(item.encrypt_composite(&mut ctx, key));
352 ctx.clear_local();
353 }
354
355 result
356 })
357 .flatten()
358 .collect();
359
360 res
361 }
362}
363
364/// Calculate the optimal chunk size for parallelizing encryption/decryption operations.
365fn batch_chunk_size(len: usize) -> usize {
366 // In an optimal scenario with no overhead, we would split the data evenly between
367 // all available threads, rounding up to the nearest integer.
368 let items_per_thread = usize::div_ceil(len, rayon::current_num_threads());
369
370 // Because the addition of each chunk has some overhead (e.g. creating a new context, thread
371 // synchronization), we want to split the data into chunks that are large enough to amortize
372 // this overhead, but not too large that we get no benefit from multithreading. We've chosen
373 // a value more or less arbitrarily, but it seems to work well in practice.
374 const MINIMUM_CHUNK_SIZE: usize = 50;
375
376 // As a result, we pick whichever of the two values is larger.
377 usize::max(items_per_thread, MINIMUM_CHUNK_SIZE)
378}
379
380#[cfg(test)]
381pub(crate) mod tests {
382 use crate::{
383 EncString, PrimitiveEncryptable, SymmetricCryptoKey,
384 store::{KeyStore, KeyStoreContext},
385 traits::tests::{TestIds, TestSymmKey},
386 };
387
388 pub struct DataView(pub String, pub TestSymmKey);
389 pub struct Data(pub EncString, pub TestSymmKey);
390
391 impl crate::IdentifyKey<TestSymmKey> for DataView {
392 fn key_identifier(&self) -> TestSymmKey {
393 self.1
394 }
395 }
396
397 impl crate::IdentifyKey<TestSymmKey> for Data {
398 fn key_identifier(&self) -> TestSymmKey {
399 self.1
400 }
401 }
402
403 impl crate::CompositeEncryptable<TestIds, TestSymmKey, Data> for DataView {
404 fn encrypt_composite(
405 &self,
406 ctx: &mut KeyStoreContext<TestIds>,
407 key: TestSymmKey,
408 ) -> Result<Data, crate::CryptoError> {
409 Ok(Data(self.0.encrypt(ctx, key)?, key))
410 }
411 }
412
413 impl crate::Decryptable<TestIds, TestSymmKey, DataView> for Data {
414 fn decrypt(
415 &self,
416 ctx: &mut KeyStoreContext<TestIds>,
417 key: TestSymmKey,
418 ) -> Result<DataView, crate::CryptoError> {
419 Ok(DataView(self.0.decrypt(ctx, key)?, key))
420 }
421 }
422
423 #[test]
424 fn test_multithread_decrypt_keeps_order() {
425 let store: KeyStore<TestIds> = KeyStore::default();
426
427 // Create a bunch of random keys
428 for n in 0..15 {
429 #[allow(deprecated)]
430 store
431 .context_mut()
432 .set_symmetric_key(
433 TestSymmKey::A(n),
434 SymmetricCryptoKey::make_aes256_cbc_hmac_key(),
435 )
436 .unwrap();
437 }
438
439 // Create some test data
440 let data: Vec<_> = (0..300usize)
441 .map(|n| DataView(format!("Test {n}"), TestSymmKey::A((n % 15) as u8)))
442 .collect();
443
444 // Encrypt the data
445 let encrypted: Vec<_> = store.encrypt_list(&data).unwrap();
446
447 // Decrypt the data
448 let decrypted: Vec<_> = store.decrypt_list(&encrypted).unwrap();
449
450 // Check that the data is the same, and in the same order as the original
451 for (orig, dec) in data.iter().zip(decrypted.iter()) {
452 assert_eq!(orig.0, dec.0);
453 assert_eq!(orig.1, dec.1);
454 }
455 }
456}