SPB Git

Repository Public Apache-2.0

wipe.rs 4.9 KB 166 lines rust

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SPB Quantum Crypto7// File             : crates/spb-pqc-core/src/ct/wipe.rs8// Module           : Crates9// Repository       : https://git.spboucher.ai/spb-quantum-crypto10// Project Website  : https://pqce.spboucher.ai11// Created          : 2026-12-0312// Last Modified    : 2026-12-0313//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! Memory wiping that resists dead-store elimination.42//!43//! This is one of the two places in the core where `unsafe` is allowed (the44//! other one is the operating-system RNG binding). The only unsafe operation is45//! `core::ptr::write_volatile` on elements of a live, exclusively borrowed slice.46//!47//! Limits (documented in `docs/security/memory.md`): copies made by the48//! compiler (spills, moves of `Copy` data, registers), by the operating system49//! (swap, core dumps) or by a foreign runtime (Swift `Data`, JavaScript typed50//! arrays) are out of reach of this function.51#![allow(unsafe_code)]5253use core::sync::atomic::{compiler_fence, Ordering};5455/// Marker for plain integer types whose all-zero bit pattern is valid.56pub trait Pod: Copy + sealed::Sealed {57    /// The zero value.58    const ZERO: Self;59}6061mod sealed {62    pub trait Sealed {}63}6465macro_rules! pod {66    ($($t:ty),*) => {$(67        impl sealed::Sealed for $t {}68        impl Pod for $t { const ZERO: Self = 0; }69    )*};70}71pod!(u8, u16, u32, u64, i16, i32, i64, usize);7273/// Overwrites every element of `data` with zero using volatile writes.74#[inline(never)]75pub fn wipe<T: Pod>(data: &mut [T]) {76    for elem in data.iter_mut() {77        // SAFETY: `elem` is a valid, aligned, exclusively borrowed `T`; `T` is a78        // plain integer for which zero is a valid value.79        unsafe { core::ptr::write_volatile(elem, T::ZERO) };80    }81    compiler_fence(Ordering::SeqCst);82}8384/// Heap buffer holding secret bytes: wiped on drop, not `Clone`, not `Debug`,85/// never formatted. Used for private keys and shared secrets.86pub struct Secret {87    bytes: Vec<u8>,88}8990impl Secret {91    /// Takes ownership of `bytes`.92    pub fn new(bytes: Vec<u8>) -> Self {93        Secret { bytes }94    }9596    /// A zero-filled secret buffer of `len` bytes.97    pub fn zeroed(len: usize) -> Self {98        Secret {99            bytes: vec![0u8; len],100        }101    }102103    /// Copies `bytes` into a new secret buffer.104    pub fn from_slice(bytes: &[u8]) -> Self {105        Secret {106            bytes: bytes.to_vec(),107        }108    }109110    /// Read access to the secret bytes. The caller must not log or format them.111    pub fn expose(&self) -> &[u8] {112        &self.bytes113    }114115    /// Write access to the secret bytes.116    pub fn expose_mut(&mut self) -> &mut [u8] {117        &mut self.bytes118    }119120    /// Length in bytes (public information).121    pub fn len(&self) -> usize {122        self.bytes.len()123    }124125    /// Whether the buffer is empty.126    pub fn is_empty(&self) -> bool {127        self.bytes.is_empty()128    }129}130131impl Drop for Secret {132    fn drop(&mut self) {133        wipe(&mut self.bytes);134    }135}136137impl core::fmt::Debug for Secret {138    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {139        write!(f, "Secret([REDACTED; {}])", self.bytes.len())140    }141}142143#[cfg(test)]144mod tests {145    use super::*;146147    #[test]148    fn wipes_all_integer_widths() {149        let mut a = [0xAAu8; 37];150        wipe(&mut a);151        assert!(a.iter().all(|&x| x == 0));152        let mut b = [-5i32; 9];153        wipe(&mut b);154        assert!(b.iter().all(|&x| x == 0));155        let mut c = [7u16; 3];156        wipe(&mut c);157        assert!(c.iter().all(|&x| x == 0));158    }159160    #[test]161    fn secret_debug_is_redacted() {162        let s = Secret::from_slice(&[1, 2, 3]);163        assert_eq!(format!("{s:?}"), "Secret([REDACTED; 3])");164    }165}166
Files main
Menu

Theme