Skip to content

Commit

Permalink
zeroize: Implement Zeroize for CString (RustCrypto#650)
Browse files Browse the repository at this point in the history
This implements Zeroize for std::ffi::CString. As CString is not in
allocate but in std, a new optional std feature is added to depend
on the std library.
  • Loading branch information
robinhundt committed Apr 4, 2022
1 parent 3bd7698 commit b9bd0a7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
1 change: 1 addition & 0 deletions zeroize/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ default = ["alloc"]
aarch64 = []
alloc = []
derive = ["zeroize_derive"]
std = []

[package.metadata.docs.rs]
all-features = true
Expand Down
26 changes: 26 additions & 0 deletions zeroize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@
#[cfg_attr(test, macro_use)]
extern crate alloc;

#[cfg(feature = "std")]
extern crate std;

#[cfg(feature = "zeroize_derive")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize_derive")))]
pub use zeroize_derive::{Zeroize, ZeroizeOnDrop};
Expand All @@ -253,6 +256,9 @@ use core::{ops, ptr, slice::IterMut, sync::atomic};
#[cfg(feature = "alloc")]
use alloc::{boxed::Box, string::String, vec::Vec};

#[cfg(feature = "std")]
use std::ffi::CString;

/// Trait for securely erasing types from memory
pub trait Zeroize {
/// Zero out this object from memory using Rust intrinsics which ensure the
Expand Down Expand Up @@ -511,6 +517,15 @@ impl Zeroize for String {
}
}

#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl Zeroize for CString {
fn zeroize(&mut self) {
let this = std::mem::take(self);
this.into_bytes().zeroize();
}
}

/// Fallible trait for representing cases where zeroization may or may not be
/// possible.
///
Expand Down Expand Up @@ -700,6 +715,9 @@ mod tests {
#[cfg(feature = "alloc")]
use alloc::boxed::Box;

#[cfg(feature = "std")]
use std::ffi::CString;

#[derive(Clone, Debug, PartialEq)]
struct ZeroizedOnDrop(u64);

Expand Down Expand Up @@ -858,6 +876,14 @@ mod tests {
assert!(as_vec.iter().all(|byte| *byte == 0));
}

#[cfg(feature = "std")]
#[test]
fn zeroize_c_string() {
let mut cstring = CString::new("Hello, world!").expect("CString::new failed");
cstring.zeroize();
assert!(cstring.into_bytes().is_empty());
}

#[cfg(feature = "alloc")]
#[test]
fn zeroize_box() {
Expand Down

0 comments on commit b9bd0a7

Please sign in to comment.