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}
117
118/// Create a new key store with the best available implementation for the current platform.
119impl<Ids: KeyIds> Default for KeyStore<Ids> {
120 fn default() -> Self {
121 Self {
122 inner: Arc::new(RwLock::new(KeyStoreInner {
123 symmetric_keys: create_store(),
124 asymmetric_keys: create_store(),
125 signing_keys: create_store(),
126 })),
127 }
128 }
129}
130
131impl<Ids: KeyIds> KeyStore<Ids> {
132 /// Clear all keys from the store. This can be used to clear all keys from memory in case of
133 /// lock/logout, and is equivalent to destroying the store and creating a new one.
134 pub fn clear(&self) {
135 let mut keys = self.inner.write().expect("RwLock is poisoned");
136 keys.symmetric_keys.clear();
137 keys.asymmetric_keys.clear();
138 keys.signing_keys.clear();
139 }
140
141 /// Initiate an encryption/decryption context. This context will have read only access to the
142 /// global keys, and will have its own local key stores with read/write access. This
143 /// context-local store will be cleared when the context is dropped.
144 ///
145 /// If you are only looking to encrypt or decrypt items, you should implement
146 /// [CompositeEncryptable]/[Decryptable] and use the [KeyStore::encrypt], [KeyStore::decrypt],
147 /// [KeyStore::encrypt_list] and [KeyStore::decrypt_list] methods instead.
148 ///
149 /// The current implementation of context only clears the keys automatically when the context is
150 /// dropped, and not between operations. This means that if you are using the same context
151 /// for multiple operations, you may want to clear it manually between them. If possible, we
152 /// recommend using [KeyStore::encrypt_list] and [KeyStore::decrypt_list] instead.
153 ///
154 /// [KeyStoreContext] is not [Send] or [Sync] and should not be shared between threads. Note
155 /// that this can also be problematic in async code, and you should take care to ensure that
156 /// you're not holding references to the context across await points, as that would cause the
157 /// future to also not be [Send].
158 ///
159 /// Some other possible use cases for this API and alternative recommendations are:
160 /// - Decrypting or encrypting multiple [Decryptable] or [CompositeEncryptable] items while
161 /// sharing any local keys. This is not recommended as it can lead to fragile and flaky
162 /// decryption/encryption operations. We recommend any local keys to be used only in the
163 /// context of a single [CompositeEncryptable] or [Decryptable] implementation. In the future
164 /// we might enforce this.
165 /// - Obtaining the key material directly. We strongly recommend against doing this as it can
166 /// lead to key material being leaked, but we need to support it for backwards compatibility.
167 /// If you want to access the key material to encrypt it or derive a new key from it, we
168 /// provide functions for that:
169 /// - [KeyStoreContext::wrap_symmetric_key]
170 /// - [KeyStoreContext::encapsulate_key_unsigned]
171 /// - [KeyStoreContext::derive_shareable_key]
172 pub fn context(&'_ self) -> KeyStoreContext<'_, Ids> {
173 KeyStoreContext {
174 global_keys: GlobalKeys::ReadOnly(self.inner.read().expect("RwLock is poisoned")),
175 local_symmetric_keys: create_store(),
176 local_asymmetric_keys: create_store(),
177 local_signing_keys: create_store(),
178 _phantom: std::marker::PhantomData,
179 }
180 }
181
182 /// <div class="warning">
183 /// This is an advanced API, use with care and ONLY when needing to modify the global keys.
184 ///
185 /// The same pitfalls as [Self::context] apply here, but with the added risk of accidentally
186 /// modifying the global keys and leaving the store in an inconsistent state.
187 /// If you still need to use it, make sure you read this documentation to understand how to use
188 /// it safely. </div>
189 ///
190 /// Initiate an encryption/decryption context. This context will have MUTABLE access to the
191 /// global keys, and will have its own local key stores with read/write access. This
192 /// context-local store will be cleared up when the context is dropped.
193 ///
194 /// The only supported use case for this API is initializing the store with the user's symetric
195 /// and private keys, and setting the organization keys. This method will be marked as
196 /// `pub(crate)` in the future, once we have a safe API for key initialization and updating.
197 ///
198 /// [KeyStoreContext] is not [Send] or [Sync] and should not be shared between threads. Note
199 /// that this can also be problematic in async code, and you should take care to ensure that
200 /// you're not holding references to the context across await points, as that would cause the
201 /// future to also not be [Send].
202 pub fn context_mut(&'_ self) -> KeyStoreContext<'_, Ids> {
203 KeyStoreContext {
204 global_keys: GlobalKeys::ReadWrite(self.inner.write().expect("RwLock is poisoned")),
205 local_symmetric_keys: create_store(),
206 local_asymmetric_keys: create_store(),
207 local_signing_keys: create_store(),
208 _phantom: std::marker::PhantomData,
209 }
210 }
211
212 /// Decript a single item using this key store. The key returned by `data.key_identifier()` must
213 /// already be present in the store, otherwise this will return an error.
214 /// This method is not parallelized, and is meant for single item decryption.
215 /// If you need to decrypt multiple items, use `decrypt_list` instead.
216 pub fn decrypt<Key: KeyId, Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key>, Output>(
217 &self,
218 data: &Data,
219 ) -> Result<Output, crate::CryptoError> {
220 let key = data.key_identifier();
221 data.decrypt(&mut self.context(), key)
222 }
223
224 /// Encrypt a single item using this key store. The key returned by `data.key_identifier()` must
225 /// already be present in the store, otherwise this will return an error.
226 /// This method is not parallelized, and is meant for single item encryption.
227 /// If you need to encrypt multiple items, use `encrypt_list` instead.
228 pub fn encrypt<
229 Key: KeyId,
230 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key>,
231 Output,
232 >(
233 &self,
234 data: Data,
235 ) -> Result<Output, crate::CryptoError> {
236 let key = data.key_identifier();
237 data.encrypt_composite(&mut self.context(), key)
238 }
239
240 /// Decrypt a list of items using this key store. The keys returned by
241 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
242 /// return an error. This method will try to parallelize the decryption of the items, for
243 /// better performance on large lists.
244 pub fn decrypt_list<
245 Key: KeyId,
246 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
247 Output: Send + Sync,
248 >(
249 &self,
250 data: &[Data],
251 ) -> Result<Vec<Output>, crate::CryptoError> {
252 let res: Result<Vec<_>, _> = data
253 .par_chunks(batch_chunk_size(data.len()))
254 .map(|chunk| {
255 let mut ctx = self.context();
256
257 let mut result = Vec::with_capacity(chunk.len());
258
259 for item in chunk {
260 let key = item.key_identifier();
261 result.push(item.decrypt(&mut ctx, key));
262 ctx.clear_local();
263 }
264
265 result
266 })
267 .flatten()
268 .collect();
269
270 res
271 }
272
273 /// Decrypt a list of items using this key store, returning a tuple of successful and failed
274 /// items.
275 ///
276 /// # Arguments
277 /// * `data` - The list of items to decrypt.
278 ///
279 /// # Returns
280 /// A tuple containing two vectors: the first vector contains the successfully decrypted items,
281 /// and the second vector contains the original items that failed to decrypt.
282 pub fn decrypt_list_with_failures<
283 'a,
284 Key: KeyId,
285 Data: Decryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync + 'a,
286 Output: Send + Sync,
287 >(
288 &self,
289 data: &'a [Data],
290 ) -> (Vec<Output>, Vec<&'a Data>) {
291 let results: (Vec<_>, Vec<_>) = data
292 .par_chunks(batch_chunk_size(data.len()))
293 .flat_map(|chunk| {
294 let mut ctx = self.context();
295
296 chunk
297 .iter()
298 .map(|item| {
299 let result = item
300 .decrypt(&mut ctx, item.key_identifier())
301 .map_err(|_| item);
302 ctx.clear_local();
303 result
304 })
305 .collect::<Vec<_>>()
306 })
307 .partition_map(|result| match result {
308 Ok(output) => Either::Left(output),
309 Err(original_item) => Either::Right(original_item),
310 });
311
312 results
313 }
314
315 /// Encrypt a list of items using this key store. The keys returned by
316 /// `data[i].key_identifier()` must already be present in the store, otherwise this will
317 /// return an error. This method will try to parallelize the encryption of the items, for
318 /// better performance on large lists. This method is not parallelized, and is meant for
319 /// single item encryption.
320 pub fn encrypt_list<
321 Key: KeyId,
322 Data: CompositeEncryptable<Ids, Key, Output> + IdentifyKey<Key> + Send + Sync,
323 Output: Send + Sync,
324 >(
325 &self,
326 data: &[Data],
327 ) -> Result<Vec<Output>, crate::CryptoError> {
328 let res: Result<Vec<_>, _> = data
329 .par_chunks(batch_chunk_size(data.len()))
330 .map(|chunk| {
331 let mut ctx = self.context();
332
333 let mut result = Vec::with_capacity(chunk.len());
334
335 for item in chunk {
336 let key = item.key_identifier();
337 result.push(item.encrypt_composite(&mut ctx, key));
338 ctx.clear_local();
339 }
340
341 result
342 })
343 .flatten()
344 .collect();
345
346 res
347 }
348}
349
350/// Calculate the optimal chunk size for parallelizing encryption/decryption operations.
351fn batch_chunk_size(len: usize) -> usize {
352 // In an optimal scenario with no overhead, we would split the data evenly between
353 // all available threads, rounding up to the nearest integer.
354 let items_per_thread = usize::div_ceil(len, rayon::current_num_threads());
355
356 // Because the addition of each chunk has some overhead (e.g. creating a new context, thread
357 // synchronization), we want to split the data into chunks that are large enough to amortize
358 // this overhead, but not too large that we get no benefit from multithreading. We've chosen
359 // a value more or less arbitrarily, but it seems to work well in practice.
360 const MINIMUM_CHUNK_SIZE: usize = 50;
361
362 // As a result, we pick whichever of the two values is larger.
363 usize::max(items_per_thread, MINIMUM_CHUNK_SIZE)
364}
365
366#[cfg(test)]
367pub(crate) mod tests {
368 use crate::{
369 EncString, PrimitiveEncryptable, SymmetricCryptoKey,
370 store::{KeyStore, KeyStoreContext},
371 traits::tests::{TestIds, TestSymmKey},
372 };
373
374 pub struct DataView(pub String, pub TestSymmKey);
375 pub struct Data(pub EncString, pub TestSymmKey);
376
377 impl crate::IdentifyKey<TestSymmKey> for DataView {
378 fn key_identifier(&self) -> TestSymmKey {
379 self.1
380 }
381 }
382
383 impl crate::IdentifyKey<TestSymmKey> for Data {
384 fn key_identifier(&self) -> TestSymmKey {
385 self.1
386 }
387 }
388
389 impl crate::CompositeEncryptable<TestIds, TestSymmKey, Data> for DataView {
390 fn encrypt_composite(
391 &self,
392 ctx: &mut KeyStoreContext<TestIds>,
393 key: TestSymmKey,
394 ) -> Result<Data, crate::CryptoError> {
395 Ok(Data(self.0.encrypt(ctx, key)?, key))
396 }
397 }
398
399 impl crate::Decryptable<TestIds, TestSymmKey, DataView> for Data {
400 fn decrypt(
401 &self,
402 ctx: &mut KeyStoreContext<TestIds>,
403 key: TestSymmKey,
404 ) -> Result<DataView, crate::CryptoError> {
405 Ok(DataView(self.0.decrypt(ctx, key)?, key))
406 }
407 }
408
409 #[test]
410 fn test_multithread_decrypt_keeps_order() {
411 let store: KeyStore<TestIds> = KeyStore::default();
412
413 // Create a bunch of random keys
414 for n in 0..15 {
415 #[allow(deprecated)]
416 store
417 .context_mut()
418 .set_symmetric_key(
419 TestSymmKey::A(n),
420 SymmetricCryptoKey::make_aes256_cbc_hmac_key(),
421 )
422 .unwrap();
423 }
424
425 // Create some test data
426 let data: Vec<_> = (0..300usize)
427 .map(|n| DataView(format!("Test {n}"), TestSymmKey::A((n % 15) as u8)))
428 .collect();
429
430 // Encrypt the data
431 let encrypted: Vec<_> = store.encrypt_list(&data).unwrap();
432
433 // Decrypt the data
434 let decrypted: Vec<_> = store.decrypt_list(&encrypted).unwrap();
435
436 // Check that the data is the same, and in the same order as the original
437 for (orig, dec) in data.iter().zip(decrypted.iter()) {
438 assert_eq!(orig.0, dec.0);
439 assert_eq!(orig.1, dec.1);
440 }
441 }
442}