lum_ccc_rust/crates/ccc-crypto-wolfssl/src/fips.rs

78 lines
2.3 KiB
Rust

//! FIPS 140-3 status of the linked wolfCrypt.
//!
//! Only a build with the `fips` feature links the commercial wolfCrypt FIPS
//! module; every other build reports `false` without asking the library.
#[cfg(feature = "fips")]
mod ffi {
use std::os::raw::{c_char, c_int};
extern "C" {
/// 0 once the power-on self-test and the in-core integrity check
/// passed; a negative wolfCrypt error code otherwise.
pub fn wolfCrypt_GetStatus_fips() -> c_int;
/// The in-core hash the last integrity check computed (hex).
pub fn wolfCrypt_GetCoreHash_fips() -> *const c_char;
}
}
/// The FIPS module status: `Some(0)` when the self-tests passed, `Some(err)`
/// when they failed, `None` without the `fips` feature.
pub fn fips_status() -> Option<i32> {
#[cfg(feature = "fips")]
{
// SAFETY: a plain status query without arguments.
Some(unsafe { ffi::wolfCrypt_GetStatus_fips() })
}
#[cfg(not(feature = "fips"))]
{
None
}
}
/// `true` only when built with the `fips` feature and the module's
/// power-on self-test (including the in-core integrity check) passed.
pub fn fips_mode() -> bool {
fips_status() == Some(0)
}
/// The in-core hash wolfCrypt computed for this binary, to set as
/// `WOLFSSL_FIPS_CORE_HASH` when the integrity check fails after a relink.
/// `None` without the `fips` feature.
pub fn fips_core_hash() -> Option<String> {
#[cfg(feature = "fips")]
{
// SAFETY: returns NULL or a NUL-terminated static string.
let p = unsafe { ffi::wolfCrypt_GetCoreHash_fips() };
if p.is_null() {
return None;
}
// SAFETY: checked non-null above; wolfCrypt owns the buffer.
let s = unsafe { std::ffi::CStr::from_ptr(p) };
Some(s.to_string_lossy().into_owned())
}
#[cfg(not(feature = "fips"))]
{
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(not(feature = "fips"))]
#[test]
fn open_source_build_is_not_fips() {
assert_eq!(fips_status(), None);
assert!(!fips_mode());
assert_eq!(fips_core_hash(), None);
}
#[cfg(feature = "fips")]
#[test]
fn fips_build_passes_its_self_test() {
assert!(fips_mode(), "status {:?}, core hash {:?}", fips_status(), fips_core_hash());
}
}