Crate secure_types

Source
Expand description

§Secure Types

This crate provides heap-allocated data structures (SecureVec, SecureArray, SecureString) designed to handle sensitive information in memory with enhanced security.

§Core Security Guarantees

The primary goal is to protect secret data (like passwords, private keys, or credentials) from being exposed through common vulnerabilities.

  1. Zeroization on Drop: All secure types implement the Zeroize trait, ensuring their memory is securely overwritten with zeros when they are dropped. This prevents stale data from being recoverable in deallocated memory.

  2. Memory Locking (std only): When compiled with the std feature (the default), the crate uses OS-level primitives to lock memory pages, preventing them from being swapped to disk.

    • On Windows: VirtualLock and VirtualProtect.
    • On Unix: mlock and mprotect.
  3. Memory Encryption (std on Windows only): On Windows, memory is also encrypted in place using CryptProtectMemory, providing an additional layer of protection against memory inspection.

  4. Scoped Access: Data is protected by default. To access it, you must use scoped methods like .unlocked_scope(|slice| { ... }), which temporarily makes the data accessible and automatically re-locks it afterward.

§Usage Example

Here’s a quick example of how to use SecureString:

use secure_types::SecureString;

// Create a string from a sensitive literal.
// The original data is securely zeroized after being copied.
let mut secret = SecureString::from("my_super_secret_password");

// The memory is locked and protected here. Direct access is not possible.

// Use a scope to safely access the content as a &str.
secret.str_scope(|unlocked_str| {
    assert_eq!(unlocked_str, "my_super_secret_password");
    println!("The secret is: {}", unlocked_str);
});

// The memory is automatically locked again when the scope ends.

// When `secret` goes out of scope, its memory will be securely zeroized.

§Feature Flags

  • std (default): Enables all OS-level security features like memory locking and encryption.
  • serde: Enables serialization and deserialization for SecureString and SecureBytes via the Serde framework.
  • no_std: Compiles the crate in a no_std environment. In this mode, only the Zeroize on Drop guarantee is provided. This is useful for embedded systems or WebAssembly.

Re-exports§

pub use array::SecureArray;
pub use string::SecureString;
pub use vec::SecureBytes;
pub use vec::SecureVec;
pub use memsec;

Modules§

array
string
vec

Enums§

Error

Traits§

Zeroize
Trait for securely erasing values from memory.

Functions§

mprotect
page_size