Skip to content

Commit

Permalink
Respect no-memory-hardening flag
Browse files Browse the repository at this point in the history
  • Loading branch information
dani-garcia committed Sep 24, 2024
1 parent ce2343e commit bcd712f
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 14 deletions.
12 changes: 4 additions & 8 deletions crates/bitwarden-crypto/src/service/key_store/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,18 @@ use zeroize::ZeroizeOnDrop;

use crate::service::KeyRef;

#[cfg(target_os = "linux")]
#[cfg(all(target_os = "linux", not(feature = "no-memory-hardening")))]
mod linux_memfd_secret_impl;
mod rust_impl;
mod util;

#[cfg(target_os = "linux")]
pub(crate) use linux_memfd_secret_impl::LinuxMemfdSecretKeyStore;
pub(crate) use rust_impl::RustKeyStore;

pub(crate) fn create_key_store<Key: KeyRef>() -> Box<dyn KeyStore<Key>> {
#[cfg(target_os = "linux")]
if let Some(key_store) = LinuxMemfdSecretKeyStore::<Key>::new() {
#[cfg(all(target_os = "linux", not(feature = "no-memory-hardening")))]
if let Some(key_store) = linux_memfd_secret_impl::LinuxMemfdSecretKeyStore::<Key>::new() {
return Box::new(key_store);
}

Box::new(RustKeyStore::new().expect("RustKeyStore should always be available"))
Box::new(rust_impl::RustKeyStore::new().expect("RustKeyStore should always be available"))
}

/// This trait represents a platform that can securely store and return keys. The `RustKeyStore`
Expand Down
10 changes: 4 additions & 6 deletions crates/bitwarden-crypto/src/service/key_store/rust_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,15 @@ use super::{
// zeroize the values when dropped.
pub(crate) type RustKeyStore<Key> = SliceKeyStore<Key, RustImplKeyData<Key>>;

const ENABLE_MLOCK: bool = true;

pub(crate) struct RustImplKeyData<Key: KeyRef> {
#[allow(clippy::type_complexity)]
data: Box<[Option<(Key, Key::KeyValue)>]>,
}

impl<Key: KeyRef> Drop for RustImplKeyData<Key> {
fn drop(&mut self) {
#[cfg(not(target_arch = "wasm32"))]
if ENABLE_MLOCK {
#[cfg(any(not(target_arch = "wasm32"), not(feature = "no-memory-hardening")))]
{
let entry_size = std::mem::size_of::<Option<(Key, Key::KeyValue)>>();
unsafe {
memsec::munlock(
Expand Down Expand Up @@ -51,8 +49,8 @@ impl<Key: KeyRef> KeyData<Key> for RustImplKeyData<Key> {
fn with_capacity(capacity: usize) -> Self {
let mut data: Box<_> = std::iter::repeat_with(|| None).take(capacity).collect();

#[cfg(not(target_arch = "wasm32"))]
if ENABLE_MLOCK {
#[cfg(any(not(target_arch = "wasm32"), not(feature = "no-memory-hardening")))]
{
let entry_size = std::mem::size_of::<Option<(Key, Key::KeyValue)>>();
unsafe {
memsec::mlock(data.as_mut_ptr() as *mut u8, capacity * entry_size);
Expand Down

0 comments on commit bcd712f

Please sign in to comment.