Crate sodium_alloc[][src]

Expand description

Allocator type that allocates memory using Sodium’s secure memory utilities.

Requires nightly Rust, as the Allocator API is not yet stable.

This library implements SodiumAllocator, an Allocator which uses the sodium_malloc and corresponding sodium_free functions to manage memory. When managing sensitive data in memory, there are a number of steps we can take to help harden our software against revealing these secrets.

Sodium’s sodium_malloc implementation introduces many of these hardening steps to the memory management process: Allocated memory is placed at the end of a page boundary, immediately followed by a guard page (a region of memory which is marked as inaccessible, any attempt to access it will result in termination of the program). A canary is placed before the allocated memory, any modifications to which are detected on free, again resulting in program termination, and a guard page is placed before this. sodium_mlock is used to instruct the operating system not to swap the memory to disk, or to include it in core dumps.

When memory is freed with SodiumAllocator, the sodium_free function is called, which will securely zero the memory before marking it as free. This means that for types allocated with SodiumAllocator, there is no need to implement Zeroize or a similar Drop implementation to zero the memory when no longer in use: It will automatically be zeroed when freed.

This library is not suitable for use as a general-purpose allocator or global allocator: The overhead of this API is much greater than Rust’s standard allocator, and the implementation is more likely to encounter errors. It is intended for use when allocating sensitive data types only, for example, a key or password which needs to be stored in memory.


Here we create a standard Rust vector, but use Sodium’s memory management to allocate/grow/free its memory:

// Currently necessary: Allocators are feature-gated on nightly

use std::alloc::Allocator;
use sodium_alloc::SodiumAllocator;

// Allocate a vector using Sodium's memory management functions
let mut my_vec = Vec::with_capacity_in(4, SodiumAllocator);
my_vec.extend_from_slice(&[3, 4]);
println!("{:?}", my_vec);
// Grow the vector, works just like normal :)
// Drop the vector, the SodiumAllocator will securely zero the memory when freed. Dropping like
// this isn't necessary, things going out of scope as normal works too, this is just for
// illustrative purposes.

Boxes also currently support the Allocator API:


use std::alloc::Allocator;
use sodium_alloc::SodiumAllocator;

// Store something on the heap, allocating memory with Sodium
let key = Box::new_in([0xca, 0xfe, 0xba, 0xbe], SodiumAllocator);
println!("{:x?}", key);


An Allocator which allocates and frees memory using Sodium’s secure memory utilities.