Skip to content

[PM-18100] Add mlock and memfd_secret implementations #125

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 9 additions & 0 deletions crates/bitwarden-crypto/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ no-memory-hardening = [] # Disable memory hardening features

[dependencies]
aes = { version = ">=0.8.2, <0.9", features = ["zeroize"] }
allocator-api2 = ">=0.2.21, <0.3"
argon2 = { version = ">=0.5.0, <0.6", features = [
"std",
"zeroize",
Expand All @@ -35,6 +36,7 @@ ciborium = { version = ">=0.2.2, <0.3" }
coset = { version = ">=0.3.8, <0.4" }
ed25519-dalek = { version = ">=2.1.1, <=2.2.0", features = ["rand_core"] }
generic-array = { version = ">=0.14.7, <1.0", features = ["zeroize"] }
hashbrown = ">=0.15.3, <0.16"
hkdf = ">=0.12.3, <0.13"
hmac = ">=0.12.1, <0.13"
num-bigint = ">=0.4, <0.5"
Expand All @@ -60,6 +62,9 @@ wasm-bindgen = { workspace = true, optional = true }
zeroize = { version = ">=1.7.0, <2.0", features = ["derive", "aarch64"] }
zeroizing-alloc = ">=0.1.0, <0.2"

[target.'cfg(all(not(target_arch = "wasm32"), not(windows)))'.dependencies]
memsec = { version = ">=0.7.0, <0.8", features = ["alloc_ext"] }

[dev-dependencies]
criterion = "0.6.0"
rand_chacha = "0.3.1"
Expand All @@ -77,3 +82,7 @@ required-features = ["no-memory-hardening"]

[lints]
workspace = true

[package.metadata.cargo-udeps.ignore]
# This is unused when using --all-features, as that disables memory-hardening
normal = ["memsec"]
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,10 @@ impl<Key: KeyId> Drop for BasicBackend<Key> {
self.clear();
}
}

#[cfg(test)]
impl<Key: KeyId> super::super::StoreBackendDebug<Key> for BasicBackend<Key> {
fn elements(&self) -> Vec<(Key, &Key::KeyValue)> {
self.keys.iter().map(|(k, v)| (*k, v)).collect()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
use std::{alloc::Layout, ptr::NonNull, sync::LazyLock};

use allocator_api2::alloc::{AllocError, Allocator};

pub(crate) struct LinuxMemfdSecretAlloc;

impl LinuxMemfdSecretAlloc {
pub fn new() -> Option<Self> {
// To test if memfd_secret is supported, we try to allocate a 1 byte and see if that
// succeeds.
static IS_SUPPORTED: LazyLock<bool> = LazyLock::new(|| {
let Some(ptr): Option<NonNull<[u8]>> = (unsafe { memsec::memfd_secret_sized(1) })
else {
return false;

Check warning on line 14 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs#L14

Added line #L14 was not covered by tests
};

// Check that the pointer is readable and writable
let result = unsafe {
let ptr = ptr.as_ptr() as *mut u8;
*ptr = 30;
*ptr += 107;
*ptr == 137
};
Comment on lines +17 to +23
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: what happens if it isn't? What is returned as ptr if memfd_secret isn't supported? Trying to write to an invalid pointer/pointer to memory outside of the process should cause a segmentation fault, right?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In theory it shouldn't happen, the memfd_secret_sized function should return None if it can't allocate or the feature is not supported, and if it returns Some, then the file descripto is valid and open for read/write according to the API: https://man7.org/linux/man-pages/man2/memfd_secret.2.html#DESCRIPTION.

This was added more as a sanity check during development, so it can probably be removed.


unsafe { memsec::free_memfd_secret(ptr) };
result
});

(*IS_SUPPORTED).then_some(Self)
}
}

unsafe impl Allocator for LinuxMemfdSecretAlloc {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
// Note: The allocator_api2 Allocator traits requires us to handle zero-sized allocations.
// We return an invalid pointer as you cannot allocate a zero-sized slice in most
// allocators. This is what allocator_api2::Global does as well:
// https://github.com/zakarumych/allocator-api2/blob/2dde97af85f3559619689cef152e90e6d8a0cee3/src/alloc/global.rs#L24-L29
if layout.size() == 0 {
return Ok(unsafe {
NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(
layout.align() as *mut u8,
0,
))
});

Check warning on line 45 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs#L40-L45

Added lines #L40 - L45 were not covered by tests
}

// Ensure the size we want to allocate is a multiple of the alignment,
// so that both the start and end of the allocation are aligned.
let layout = layout.pad_to_align();

let Some(ptr): Option<NonNull<[u8]>> =
(unsafe { memsec::memfd_secret_sized(layout.size()) })
else {
return Err(AllocError);

Check warning on line 55 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs#L55

Added line #L55 was not covered by tests
};

// The pointer that we return needs to be aligned to the requested alignment.
// If that's not the case, we should free the memory and return an allocation error.
// While we check for this error condition, this should never happen in practice, as the
// pointer returned by `memfd_secret_sized` should be page-aligned (typically 4KB)
// which should be larger than any possible alignment value.
if (ptr.as_ptr() as *mut u8).align_offset(layout.align()) != 0 {
unsafe { memsec::free_memfd_secret(ptr) };
return Err(AllocError);

Check warning on line 65 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs#L64-L65

Added lines #L64 - L65 were not covered by tests
}

Ok(ptr)
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() == 0 {
return;

Check warning on line 73 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/linux_memfd_secret.rs#L73

Added line #L73 was not covered by tests
}

memsec::free_memfd_secret(ptr);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use std::{
alloc::{GlobalAlloc, Layout},
ptr::NonNull,
};

use allocator_api2::alloc::{AllocError, Allocator};

pub(crate) struct MlockAlloc(crate::ZeroizingAllocator<std::alloc::System>);

impl MlockAlloc {
pub fn new() -> Self {
Self(crate::ZeroizingAllocator(std::alloc::System))
}
}

unsafe impl Allocator for MlockAlloc {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
// Note: The allocator_api2 Allocator traits requires us to handle zero-sized allocations.
// We return an invalid pointer as you cannot allocate a zero-sized slice in most
// allocators. This is what allocator_api2::Global does as well:
// https://github.com/zakarumych/allocator-api2/blob/2dde97af85f3559619689cef152e90e6d8a0cee3/src/alloc/global.rs#L24-L29
if layout.size() == 0 {
return Ok(unsafe {
NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(
layout.align() as *mut u8,
0,
))
});

Check warning on line 28 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs#L23-L28

Added lines #L23 - L28 were not covered by tests
}

let ptr = unsafe { self.0.alloc(layout) };

if ptr.is_null() {
return Err(AllocError);

Check warning on line 34 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs#L34

Added line #L34 was not covered by tests
}
unsafe { memsec::mlock(ptr, layout.size()) };
Ok(unsafe {
let slice = std::slice::from_raw_parts_mut(ptr, layout.size());
NonNull::new(slice).expect("slice is never null")
})
}

unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() == 0 {
return;

Check warning on line 45 in crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs

View check run for this annotation

Codecov / codecov/patch

crates/bitwarden-crypto/src/store/backend/implementation/custom_alloc/malloc.rs#L45

Added line #L45 was not covered by tests
}

memsec::munlock(ptr.as_ptr(), layout.size());
self.0.dealloc(ptr.as_ptr(), layout);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
use allocator_api2::alloc::Allocator;
use zeroize::ZeroizeOnDrop;

use crate::{store::backend::StoreBackend, KeyId};

#[cfg(all(not(target_arch = "wasm32"), not(windows)))]
pub(super) mod malloc;

#[cfg(target_os = "linux")]
pub(super) mod linux_memfd_secret;

pub(super) struct CustomAllocBackend<Key: KeyId, Alloc: Allocator + Send + Sync> {
map: hashbrown::HashMap<Key, Key::KeyValue, hashbrown::DefaultHashBuilder, Alloc>,
}

impl<Key: KeyId, Alloc: Allocator + Send + Sync> CustomAllocBackend<Key, Alloc> {
pub(super) fn new(alloc: Alloc) -> Self {
Self {
map: hashbrown::HashMap::new_in(alloc),
}
}
}

impl<Key: KeyId, Alloc: Allocator + Send + Sync> ZeroizeOnDrop for CustomAllocBackend<Key, Alloc> {}

impl<Key: KeyId, Alloc: Allocator + Send + Sync> StoreBackend<Key>
for CustomAllocBackend<Key, Alloc>
{
fn upsert(&mut self, key_id: Key, key: <Key as KeyId>::KeyValue) {
self.map.insert(key_id, key);
}

fn get(&self, key_id: Key) -> Option<&<Key as KeyId>::KeyValue> {
self.map.get(&key_id)
}

fn remove(&mut self, key_id: Key) {
self.map.remove(&key_id);
}

fn clear(&mut self) {
self.map.clear();
}

fn retain(&mut self, f: fn(Key) -> bool) {
self.map.retain(|key, _| f(*key));
}
}

#[cfg(test)]
impl<Key: KeyId, Alloc: Allocator + Send + Sync> super::super::StoreBackendDebug<Key>
for CustomAllocBackend<Key, Alloc>
{
fn elements(&self) -> Vec<(Key, &Key::KeyValue)> {
self.map.iter().map(|(k, v)| (*k, v)).collect()
}
}
Loading
Loading