16 releases
new 0.3.2 | Mar 9, 2025 |
---|---|
0.3.1 | Mar 9, 2025 |
0.2.2 | Mar 9, 2025 |
0.1.11 |
|
0.1.9 | Feb 26, 2025 |
#66 in Memory management
690 downloads per month
31KB
404 lines
memsafe
One of the most secure cross-platform Rust libraries for securely wrapping data in memory.
This is the official memsafe
crate, hosted at GitHub, and published on crates.io.
memsafe
locks sensitive data in memory, restricts access, and ensures secure cleanup—built from the ground up with simplicity and security in mind.
Usage
use memsafe::MemSafe;
// initialize a 32-bytes buffer in no access state
let secret = MemSafe::new([0_u8; 32]).unwrap();
// make the buffer read-write and write into it
let info = "my-scret-info";
let mut secret = secret.read_write().unwrap();
secret[..info.len()].copy_from_slice(info.as_bytes());
// make array read only read from it
let secret = secret.read_only().unwrap();
println!("Secure data: {:02X?}", *secret);
Features
- Memory Locking: Prevents swapping to disk using
mlock
(Unix) orVirtualLock
(Windows). - Access Restriction: Defaults to no-access mode, with temporary read/write windows.
- Secure Cleanup: Zeroes memory on drop.
- Cross-Platform: Supports Unix (via
libc
) and Windows (viawinapi
) with optional dependencies.
Installation
Run the following in the root of your project:
cargo add memsafe
Security Mechanisms: A Deep Dive for Technical Enthusiasts
The following milestones highlight the technical implementation and security mechanisms completed in memsafe
, ensuring robust memory management for sensitive data in Rust:
-
Secure Memory Wrapper Implementation
- Technical Details: The
MemSafe
struct encapsulates sensitive data within a custom memory region allocated viammap
on Unix-like systems (Linux, macOS) withMAP_PRIVATE | MAP_ANONYMOUS
flags, andVirtualAlloc
on Windows withMEM_COMMIT | MEM_RESERVE
. Memory permissions are controlled usingmprotect
(Unix) andVirtualProtect
(Windows), settingPROT_NONE
/PAGE_NOACCESS
by default to deny all access. Themlock
(Unix) andVirtualLock
(Windows) functions pin the memory in RAM, preventing swap to disk, whilemadvise(MADV_DONTDUMP)
on Unix excludes it from core dumps. - Security Handling: This ensures data remains in physical memory and is inaccessible outside explicit operations, reducing exposure to swap-based attacks and limiting visibility in crash scenarios on Unix systems.
- Technical Details: The
-
Cross-Platform Compatibility with Feature Flags
- Technical Details: Conditional compilation via
#[cfg(unix)]
and#[cfg(windows)]
directives isolates platform-specific code. Theunix
feature activateslibc
for POSIX calls, while thewindows
feature leverageswinapi
for Windows API functions, withdefault = ["unix"]
inCargo.toml
enabling Unix support out of the box. CI testing uses a matrix strategy (ubuntu-latest
,macos-latest
withunix
;windows-latest
withwindows
) to build and test with--no-default-features --features ${{ matrix.features }}
. - Security Handling: This guarantees uniform security behavior across platforms, preventing gaps from missing platform-specific protections (e.g., no
mlock
fallback on Windows) and ensuring dependency minimization.
- Technical Details: Conditional compilation via
-
Secure Memory Cleanup on Drop
- Technical Details: The
Drop
implementation zeroes the memory region usingptr::write_bytes(ptr, 0, len)
before deallocation. On Unix,munlock
releases the memory lock, followed bymunmap
to free the region. On Windows,VirtualUnlock
unlocks the memory, andVirtualFree
withMEM_RELEASE
deallocates it. This process is executed within anunsafe
block to handle raw pointer operations. - Security Handling: By overwriting memory with zeros prior to release, this prevents residual data from being accessed post-deallocation, mitigating risks of memory scraping or reuse attacks.
- Technical Details: The
-
Automated Multi-Platform Testing
- Technical Details: A GitHub Actions workflow triggers on
dev
branch pushes, runningcargo build
andcargo test
with--verbose
across a matrix ofubuntu-latest
,macos-latest
, andwindows-latest
. The matrix excludes invalid feature combinations (e.g.,windows
on Unix) usingexclude
rules. Rust is set up withdtolnay/rust-toolchain@stable
, and Linux requiresbuild-essential
forlibc
linking. - Security Handling: This ensures that memory protection, locking, and access controls function correctly on all platforms, catching platform-specific regressions or misconfigurations early in the development cycle.
- Technical Details: A GitHub Actions workflow triggers on
Milestones
To further harden memsafe
against vulnerabilities, the following technical improvements are targeted:
- Controlled Access Interface: Transition to closure-based
write
andread
methods to enforce strict permission toggling, preventing reads after writes by reverting to an inaccessible state post-operation. - In-Memory Encryption: Integrate encryption to safeguard data at rest against physical or kernel-level breaches.
- Guard Pages: Allocate protective, inaccessible pages around memory to detect and thwart buffer overflows.
- Pre-Allocation Zeroing: Zero memory prior to initial use to eliminate risks from pre-existing data.
- Thread Safety: Add synchronization primitives (e.g.,
Mutex
) for secure multi-threaded access. - Windows Core Dump Protection: Implement mechanisms to exclude memory from Windows crash dumps.
- Anti-Debugging Measures: Restrict debugger attachment to minimize exposure during operations.
- Custom Allocator: Develop a randomized allocator with integrity checks to obscure memory locations.
- Side-Channel Mitigation: Optimize for constant-time operations to resist timing and speculative execution attacks. See the full Milestone in the Milestones.
Repository
Security Notice
Please note that while memsafe
is designed with security best practices in mind, it has not undergone a formal security audit yet. We encourage users to perform their own security assessment for their specific use cases. We are committed to maintaining and improving the security of this library.
License
Licensed under the MIT License. See LICENSE for details.
Contributing
Issues and pull requests are welcome at https://github.com/po0uyan/memsafe. I'll be more than happy to merge enhancements! security updates and any steps towards making software world a better place for everyone.
Dependencies
~215KB