sec_mem/lib.rs
1//! # SecMem
2//!
3//! A high-assurance, attack-resistant cryptographic memory allocator for Rust.
4//!
5//! Designed to aggressively protect sensitive data (cryptographic keys, passwords, PII)
6//! from OS-level exploits, memory dumping, buffer overflows, and side-channel attacks.
7//!
8//! ## Feature Flags
9//!
10//! | Feature | Description | Default |
11//! |---------|-------------|---------|
12//! | `sec_mem` | Enables `SecMem`, the OS-level memory hardening container. Requires `libc` and Linux. | **Yes** |
13//! | `encryption` | Enables ChaCha20/XOR-blinded encrypt-at-rest for `SecMem`. Stores the master key in `memfd_secret`. | **Yes** |
14//!
15//! *(Note: `SecretBox` is always available and fully `no_std` compatible, regardless of features).*
16//!
17//! ## 1. Hardware-Accelerated OS Hardening (`SecMem`)
18//!
19//! Available with the `sec_mem` feature. Uses raw Linux syscalls to create hardware-isolated memory.
20//!
21//! * **XOR-Blinded Encrypt-at-Rest**: Memory is dynamically ChaCha20/XOR masked.
22//! * **Intel MPK**: Grants zero-syscall hardware isolation using `pkey_mprotect` and `WRPKRU`.
23//! * **Memory Sealing**: Uses `mseal` to permanently lock guard pages and permissions.
24//! * **mlock & Anti-Tracing**: Forces `mlock`, `MADV_DONTDUMP`, `MADV_DONTFORK`, and `PR_SET_DUMPABLE(0)`.
25//!
26//! ```rust
27//! # #[cfg(feature = "sec_mem")]
28//! # {
29//! use sec_mem::SecMem;
30//!
31//! let mut secure_key = SecMem::new([0xAAu8; 32]);
32//! secure_key.access_mut(|key| {
33//! key[0] = 0xBB;
34//! }); // Hardware locks instantly engage on closure drop.
35//! # }
36//! ```
37//!
38//! ## 2. Software-Enforced Memory Hardening (`SecretBox`)
39//!
40//! A highly portable, stack-native, software-only wrapper requiring zero OS syscalls.
41//!
42//! * **Dynamic Volatile Canaries**: Generates randomized canaries at startup (`libc::getrandom` or `RDRAND`), verified via `core::ptr::read_volatile`.
43//! * **Strict Exclusive Access**: Enforces `&mut self` to mathematically eliminate concurrency race conditions.
44//! * **Closure-Restricted Lifetimes**: No `expose_secret()`. Uses strictly scoped injection closures (`.with_secret()`).
45//!
46//! ```rust
47//! use sec_mem::SecretBox;
48//!
49//! let mut portable_box = SecretBox::new(42u32);
50//! portable_box.with_secret(|val| {
51//! assert_eq!(*val, 42);
52//! }); // Stack canaries verified via volatile reads!
53//! ```
54
55#![cfg_attr(not(feature = "sec_mem"), no_std)]
56#![cfg_attr(docsrs, feature(doc_cfg))]
57#![warn(missing_debug_implementations, missing_docs, rust_2018_idioms)]
58
59#[cfg(feature = "sec_mem")]
60mod sec_mem;
61mod secret_box;
62
63#[cfg(feature = "sec_mem")]
64pub use sec_mem::{SecMem, SecretAccess, harden_process};
65pub use secret_box::SecretBox;
66pub use zeroize;