Skip to content

Commit c6e08b2

Browse files
authored
[PM-5693] KeyStore implementation (#7)
## 🎟️ Tracking https://bitwarden.atlassian.net/browse/PM-5693 ## 📔 Objective Migrated from bitwarden/sdk-sm#979 I've been looking into using `memfd_secret` to protect keys in memory on Linux. The `memfd_secret` API is similar to malloc in that we get some memory range allocated for us, but this memory is only visible to the process that has access to the file descriptor, which should protect us from any memory dumping from anything other than a kernel driver. https://man.archlinux.org/man/memfd_secret.2.en Using this requires changing how we store keys, so this is the perfect moment to go through removing the raw keys from the API surface. ## Changes - Added a `KeyRef` trait and `SymmetricKeyRef`/`AsymmetricKeyRef` subtraits to represent the key types. Also a small macro to quickly implement them. `KeyRef` implementations are user defined types that implements `Eq+Hash+Copy`, and don't contain any key material - `KeyEncryptable/KeyDecryptable` are now `Decryptable/Encryptable`, and instead of taking the key as parameter, they take a `CryptoServiceContext` and a `KeyRef`. This way keys are never exposed to the clients. - `KeyLocator` trait is replaced by `UsesKey`. This trait only returns the `KeyRef` of the key required to decrypt it, instead of fetching the key itself. - Created a `KeyStore` trait, with some simple CRUD methods. We have two implementations, one based on `memfd_secret` for Linux, and another one based on a Rust boxed slice, that also applies `mlock` if possible. - Because both `mlock` and `memfd_secret` apply their protection over a specified memory area, we need a Rust data structure that is laid out linearly and also doesn't reallocate by itself. Also because `memfd_secret` allocates the memory for us, we can't use a std type like Vec (reason is the Vec must be allocated by the Rust allocator [[ref](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.from_raw_parts)]). This basically only leaves us with a Rust slice, on top of which we'd need to implement insert/get/delete. To allow for reuse and easier testing I've created `SliceKeyStore`, which implements the CRUD methods from the `KeyStore` trait on top of a plain slice. Then the actual `mlock` and `memfd_secret` implementations just need to implement a trait casting their data to a slice. The data is stored as a slice of `Option<(KeyRef, KeyMaterial)>`, and the keys are unique and sorted in the slice for easier lookups. - Created `CryptoService`, which contains the `KeyStore`s and some encrypt/decrypt utility functions. From a `CryptoService` you can also initialize a `CryptoServiceContext` - A `CryptoServiceContext` contains a read only view of the keys inside the `CryptoService`, plus a read-write ephemeral key store, for use by `Decryptable/Encryptable` implementations when they need to temporarily store some keys (Cipher keys, attachment keys, send keys...). Migrated the codebase to use these changes in a separate PR: bitwarden/sdk-sm#1117 ## 📸 Screenshots <!-- Required for any UI changes; delete if not applicable. Use fixed width images for better display. --> ## ⏰ Reminders before review - Contributor guidelines followed - All formatters and local linters executed and passed - Written new unit and / or integration tests where applicable - Protected functional changes with optionality (feature flags) - Used internationalization (i18n) for all UI strings - CI builds passed - Communicated to DevOps any deployment requirements - Updated any necessary documentation (Confluence, contributing docs) or informed the documentation team ## 🦮 Reviewer guidelines <!-- Suggested interactions but feel free to use (or not) as you desire! --> - 👍 (`:+1:`) or similar for great changes - 📝 (`:memo:`) or ℹ️ (`:information_source:`) for notes or general info - ❓ (`:question:`) for questions - 🤔 (`:thinking:`) or 💭 (`:thought_balloon:`) for more open inquiry that's not quite a confirmed issue and could potentially benefit from discussion - 🎨 (`:art:`) for suggestions / improvements - ❌ (`:x:`) or ⚠️ (`:warning:`) for more significant problems or concerns needing attention - 🌱 (`:seedling:`) or ♻️ (`:recycle:`) for future improvements or indications of technical debt - ⛏ (`:pick:`) for minor or nitpick changes
1 parent c3962e5 commit c6e08b2

File tree

11 files changed

+1586
-0
lines changed

11 files changed

+1586
-0
lines changed

crates/bitwarden-crypto/src/error.rs

+4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ pub enum CryptoError {
2323
MissingKey(Uuid),
2424
#[error("The item was missing a required field: {0}")]
2525
MissingField(&'static str),
26+
#[error("Missing Key for Id: {0}")]
27+
MissingKeyId(String),
28+
#[error("Crypto store is read-only")]
29+
ReadOnlyKeyStore,
2630

2731
#[error("Insufficient KDF parameters")]
2832
InsufficientKdfParameters,

crates/bitwarden-crypto/src/lib.rs

+4
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,10 @@ mod util;
8080
pub use util::{generate_random_alphanumeric, generate_random_bytes, pbkdf2};
8181
mod wordlist;
8282
pub use wordlist::EFF_LONG_WORD_LIST;
83+
mod store;
84+
pub use store::{KeyStore, KeyStoreContext};
85+
mod traits;
86+
pub use traits::{Decryptable, Encryptable, IdentifyKey, KeyId, KeyIds};
8387
pub use zeroizing_alloc::ZeroAlloc as ZeroizingAllocator;
8488

8589
#[cfg(feature = "uniffi")]
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
use zeroize::ZeroizeOnDrop;
2+
3+
use crate::{store::backend::StoreBackend, KeyId};
4+
5+
/// This is a basic key store backend that stores keys in a HashMap memory.
6+
/// No protections are provided for the keys stored in this backend, beyond enforcing
7+
/// zeroization on drop.
8+
pub(crate) struct BasicBackend<Key: KeyId> {
9+
keys: std::collections::HashMap<Key, Key::KeyValue>,
10+
}
11+
12+
impl<Key: KeyId> BasicBackend<Key> {
13+
pub fn new() -> Self {
14+
Self {
15+
keys: std::collections::HashMap::new(),
16+
}
17+
}
18+
}
19+
20+
impl<Key: KeyId> StoreBackend<Key> for BasicBackend<Key> {
21+
fn upsert(&mut self, key_id: Key, key: <Key as KeyId>::KeyValue) {
22+
self.keys.insert(key_id, key);
23+
}
24+
25+
fn get(&self, key_id: Key) -> Option<&<Key as KeyId>::KeyValue> {
26+
self.keys.get(&key_id)
27+
}
28+
29+
fn remove(&mut self, key_id: Key) {
30+
self.keys.remove(&key_id);
31+
}
32+
33+
fn clear(&mut self) {
34+
self.keys.clear();
35+
}
36+
37+
fn retain(&mut self, f: fn(Key) -> bool) {
38+
self.keys.retain(|k, _| f(*k));
39+
}
40+
}
41+
42+
/// [KeyId::KeyValue] already implements [ZeroizeOnDrop],
43+
/// so we only need to ensure the map is cleared on drop.
44+
impl<Key: KeyId> ZeroizeOnDrop for BasicBackend<Key> {}
45+
impl<Key: KeyId> Drop for BasicBackend<Key> {
46+
fn drop(&mut self) {
47+
self.clear();
48+
}
49+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
use super::StoreBackend;
2+
use crate::store::KeyId;
3+
4+
mod basic;
5+
6+
/// Initializes a key store backend with the best available implementation for the current platform
7+
pub fn create_store<Key: KeyId>() -> Box<dyn StoreBackend<Key>> {
8+
Box::new(basic::BasicBackend::<Key>::new())
9+
}
10+
11+
#[cfg(test)]
12+
mod tests {
13+
use super::*;
14+
use crate::{traits::tests::TestSymmKey, SymmetricCryptoKey};
15+
16+
#[test]
17+
fn test_creates_a_valid_store() {
18+
let mut store = create_store::<TestSymmKey>();
19+
20+
let key = SymmetricCryptoKey::generate(rand::thread_rng());
21+
store.upsert(TestSymmKey::A(0), key.clone());
22+
23+
assert_eq!(
24+
store.get(TestSymmKey::A(0)).unwrap().to_base64(),
25+
key.to_base64()
26+
);
27+
}
28+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
use zeroize::ZeroizeOnDrop;
2+
3+
use crate::store::KeyId;
4+
5+
mod implementation;
6+
7+
pub use implementation::create_store;
8+
9+
/// This trait represents a platform that can store and return keys. If possible,
10+
/// it will try to enable as many security protections on the keys as it can.
11+
/// The keys themselves implement [ZeroizeOnDrop], so the store will only need to make sure
12+
/// that the keys are dropped when they are no longer needed.
13+
///
14+
/// The default implementation is a basic in-memory store that does not provide any security
15+
/// guarantees.
16+
///
17+
/// We have other implementations in testing using `mlock` and `memfd_secret` for protecting keys in
18+
/// memory.
19+
///
20+
/// Other implementations could use secure enclaves, HSMs or OS provided keychains.
21+
pub trait StoreBackend<Key: KeyId>: ZeroizeOnDrop + Send + Sync {
22+
/// Inserts a key into the store. If the key already exists, it will be replaced.
23+
fn upsert(&mut self, key_id: Key, key: Key::KeyValue);
24+
25+
/// Retrieves a key from the store.
26+
fn get(&self, key_id: Key) -> Option<&Key::KeyValue>;
27+
28+
#[allow(unused)]
29+
/// Removes a key from the store.
30+
fn remove(&mut self, key_id: Key);
31+
32+
/// Removes all keys from the store.
33+
fn clear(&mut self);
34+
35+
/// Retains only the elements specified by the predicate.
36+
/// In other words, remove all keys for which `f` returns false.
37+
fn retain(&mut self, f: fn(Key) -> bool);
38+
}

0 commit comments

Comments
 (0)