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/// #[private]
61/// pub enum PrivateKeyId {
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, PrivateKeyId, 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 private_keys: Box<dyn StoreBackend<Ids::Private>>,
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 private_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.private_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::derive_shareable_key]
179 pub fn context(&'_ self) -> KeyStoreContext<'_, Ids> {
180 let data = self.inner.read().expect("RwLock is poisoned");
181 let security_state_version = data.security_state_version;
182 KeyStoreContext {
183 global_keys: GlobalKeys::ReadOnly(data),
184 local_symmetric_keys: create_store(),
185 local_private_keys: create_store(),
186 local_signing_keys: create_store(),
187 security_state_version,
188 _phantom: std::marker::PhantomData,
189 }
190 }
191
192 /// <div class="warning">
193 /// This is an advanced API, use with care and ONLY when needing to modify the global keys.
194 ///
195 /// The same pitfalls as [Self::context] apply here, but with the added risk of accidentally
196 /// modifying the global keys and leaving the store in an inconsistent state.
197 /// If you still need to use it, make sure you read this documentation to understand how to use
198 /// it safely. </div>
199 ///
200 /// Initiate an encryption/decryption context. This context will have MUTABLE access to the
201 /// global keys, and will have its own local key stores with read/write access. This
202 /// context-local store will be cleared up when the context is dropped.
203 ///
204 /// The only supported use case for this API is initializing the store with the user's symetric
205 /// and private keys, and setting the organization keys. This method will be marked as
206 /// `pub(crate)` in the future, once we have a safe API for key initialization and updating.
207 ///
208 /// [KeyStoreContext] is not [Send] or [Sync] and should not be shared between threads. Note
209 /// that this can also be problematic in async code, and you should take care to ensure that
210 /// you're not holding references to the context across await points, as that would cause the
211 /// future to also not be [Send].
212 pub fn context_mut(&'_ self) -> KeyStoreContext<'_, Ids> {
213 let inner = self.inner.write().expect("RwLock is poisoned");
214 let security_state_version = inner.security_state_version;
215 KeyStoreContext {
216 global_keys: GlobalKeys::ReadWrite(inner),
217 local_symmetric_keys: create_store(),
218 local_private_keys: create_store(),
219 local_signing_keys: create_store(),
220 security_state_version,
221 _phantom: std::marker::PhantomData,
222 }
223 }
224
225 /// Decript a single item using this key store. The key returned by `data.key_identifier()` must
226 /// already be present in the store, otherwise this will return an error.
227 /// This method is not parallelized, and is meant for single item decryption.
228 /// If you need to decrypt multiple items, use `decrypt_list` instead.
229 pub fn decrypt<Key: KeyId, Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key>, Output>(
230 &self,
231 data: &Data,
232 ) -> Result<Output, crate::CryptoError> {
233 let key = data.key_identifier();
234 data.decrypt(&mut self.context(), key)
235 }
236
237 /// Encrypt a single item using this key store. The key returned by `data.key_identifier()` must
238 /// already be present in the store, otherwise this will return an error.
239 /// This method is not parallelized, and is meant for single item encryption.
240 /// If you need to encrypt multiple items, use `encrypt_list` instead.
241 pub fn encrypt<
242 Key: KeyId,
243 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key>,
244 Output,
245 >(
246 &self,
247 data: Data,
248 ) -> Result<Output, crate::CryptoError> {
249 let key = data.key_identifier();
250 data.encrypt_composite(&mut self.context(), key)
251 }
252
253 /// Decrypt a list of items using this key store. The keys returned by
254 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
255 /// return an error. This method will try to parallelize the decryption of the items, for
256 /// better performance on large lists.
257 pub fn decrypt_list<
258 Key: KeyId,
259 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
260 Output: Send + Sync,
261 >(
262 &self,
263 data: &[Data],
264 ) -> Result<Vec<Output>, crate::CryptoError> {
265 let res: Result<Vec<_>, _> = data
266 .par_chunks(batch_chunk_size(data.len()))
267 .map(|chunk| {
268 let mut ctx = self.context();
269
270 let mut result = Vec::with_capacity(chunk.len());
271
272 for item in chunk {
273 let key = item.key_identifier();
274 result.push(item.decrypt(&mut ctx, key));
275 ctx.clear_local();
276 }
277
278 result
279 })
280 .flatten()
281 .collect();
282
283 res
284 }
285
286 /// Decrypt a list of items using this key store, returning a tuple of successful and failed
287 /// items.
288 ///
289 /// # Arguments
290 /// * `data` - The list of items to decrypt.
291 ///
292 /// # Returns
293 /// A tuple containing two vectors: the first vector contains the successfully decrypted items,
294 /// and the second vector contains the original items that failed to decrypt.
295 pub fn decrypt_list_with_failures<
296 'a,
297 Key: KeyId,
298 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync + 'a,
299 Output: Send + Sync,
300 >(
301 &self,
302 data: &'a [Data],
303 ) -> (Vec<Output>, Vec<&'a Data>) {
304 let results: (Vec<_>, Vec<_>) = data
305 .par_chunks(batch_chunk_size(data.len()))
306 .flat_map(|chunk| {
307 let mut ctx = self.context();
308
309 chunk
310 .iter()
311 .map(|item| {
312 let result = item
313 .decrypt(&mut ctx, item.key_identifier())
314 .map_err(|_| item);
315 ctx.clear_local();
316 result
317 })
318 .collect::<Vec<_>>()
319 })
320 .partition_map(|result| match result {
321 Ok(output) => Either::Left(output),
322 Err(original_item) => Either::Right(original_item),
323 });
324
325 results
326 }
327
328 /// Encrypt a list of items using this key store. The keys returned by
329 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
330 /// return an error. This method will try to parallelize the encryption of the items, for
331 /// better performance on large lists. This method is not parallelized, and is meant for
332 /// single item encryption.
333 pub fn encrypt_list<
334 Key: KeyId,
335 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
336 Output: Send + Sync,
337 >(
338 &self,
339 data: &[Data],
340 ) -> Result<Vec<Output>, crate::CryptoError> {
341 let res: Result<Vec<_>, _> = data
342 .par_chunks(batch_chunk_size(data.len()))
343 .map(|chunk| {
344 let mut ctx = self.context();
345
346 let mut result = Vec::with_capacity(chunk.len());
347
348 for item in chunk {
349 let key = item.key_identifier();
350 result.push(item.encrypt_composite(&mut ctx, key));
351 ctx.clear_local();
352 }
353
354 result
355 })
356 .flatten()
357 .collect();
358
359 res
360 }
361}
362
363/// Calculate the optimal chunk size for parallelizing encryption/decryption operations.
364fn batch_chunk_size(len: usize) -> usize {
365 // In an optimal scenario with no overhead, we would split the data evenly between
366 // all available threads, rounding up to the nearest integer.
367 let items_per_thread = usize::div_ceil(len, rayon::current_num_threads());
368
369 // Because the addition of each chunk has some overhead (e.g. creating a new context, thread
370 // synchronization), we want to split the data into chunks that are large enough to amortize
371 // this overhead, but not too large that we get no benefit from multithreading. We've chosen
372 // a value more or less arbitrarily, but it seems to work well in practice.
373 const MINIMUM_CHUNK_SIZE: usize = 50;
374
375 // As a result, we pick whichever of the two values is larger.
376 usize::max(items_per_thread, MINIMUM_CHUNK_SIZE)
377}
378
379#[cfg(test)]
380pub(crate) mod tests {
381 use crate::{
382 EncString, PrimitiveEncryptable, SymmetricKeyAlgorithm,
383 store::{KeyStore, KeyStoreContext},
384 traits::tests::{TestIds, TestSymmKey},
385 };
386
387 pub struct DataView(pub String, pub TestSymmKey);
388 pub struct Data(pub EncString, pub TestSymmKey);
389
390 impl crate::IdentifyKey<TestSymmKey> for DataView {
391 fn key_identifier(&self) -> TestSymmKey {
392 self.1
393 }
394 }
395
396 impl crate::IdentifyKey<TestSymmKey> for Data {
397 fn key_identifier(&self) -> TestSymmKey {
398 self.1
399 }
400 }
401
402 impl crate::CompositeEncryptable<TestIds, TestSymmKey, Data> for DataView {
403 fn encrypt_composite(
404 &self,
405 ctx: &mut KeyStoreContext<TestIds>,
406 key: TestSymmKey,
407 ) -> Result<Data, crate::CryptoError> {
408 Ok(Data(self.0.encrypt(ctx, key)?, key))
409 }
410 }
411
412 impl crate::Decryptable<TestIds, TestSymmKey, DataView> for Data {
413 fn decrypt(
414 &self,
415 ctx: &mut KeyStoreContext<TestIds>,
416 key: TestSymmKey,
417 ) -> Result<DataView, crate::CryptoError> {
418 Ok(DataView(self.0.decrypt(ctx, key)?, key))
419 }
420 }
421
422 #[test]
423 fn test_multithread_decrypt_keeps_order() {
424 let store: KeyStore<TestIds> = KeyStore::default();
425
426 // Create a bunch of random keys
427 for n in 0..15 {
428 let mut ctx = store.context_mut();
429 let local_key_id = ctx.make_symmetric_key(SymmetricKeyAlgorithm::Aes256CbcHmac);
430 ctx.persist_symmetric_key(local_key_id, TestSymmKey::A(n))
431 .unwrap();
432 }
433
434 // Create some test data
435 let data: Vec<_> = (0..300usize)
436 .map(|n| DataView(format!("Test {n}"), TestSymmKey::A((n % 15) as u8)))
437 .collect();
438
439 // Encrypt the data
440 let encrypted: Vec<_> = store.encrypt_list(&data).unwrap();
441
442 // Decrypt the data
443 let decrypted: Vec<_> = store.decrypt_list(&encrypted).unwrap();
444
445 // Check that the data is the same, and in the same order as the original
446 for (orig, dec) in data.iter().zip(decrypted.iter()) {
447 assert_eq!(orig.0, dec.0);
448 assert_eq!(orig.1, dec.1);
449 }
450 }
451}