wolfssl: build against the wolfCrypt FIPS bundle with fips

Release builds need the validated module (D-26); the build fails
when WOLFSSL_FIPS_SOURCE_DIR is missing instead of falling back.

Refs: R3-7
This commit is contained in:
JohnE 2026-11-16 03:54:47 -05:00
parent 64082b98a8
commit e68c3f5d46
2 changed files with 137 additions and 1 deletions

View File

@ -28,3 +28,6 @@ hex = "0.4"
# Enable this when building without the wolfSSL C library # Enable this when building without the wolfSSL C library
# (e.g. on docs.rs, or for type-checking in CI without cmake). # (e.g. on docs.rs, or for type-checking in CI without cmake).
stub_ffi = [] stub_ffi = []
# Build against the commercial wolfCrypt FIPS 140-3 bundle at
# WOLFSSL_FIPS_SOURCE_DIR (required; never falls back to open source).
fips = []

View File

@ -18,6 +18,19 @@
//! Android toolchain. Cargokit/Gradle sets this automatically; when //! Android toolchain. Cargokit/Gradle sets this automatically; when
//! invoking `cargo` directly make sure the variable is exported in your //! invoking `cargo` directly make sure the variable is exported in your
//! shell session. //! shell session.
//!
//! With the `fips` feature (see "FIPS 140-3 builds" in the crate docs):
//!
//! * `WOLFSSL_FIPS_SOURCE_DIR` – Required. The unpacked commercial
//! wolfCrypt FIPS 140-3 bundle. There is no fallback to the open-source
//! tree: the build fails when it is missing or is not a FIPS bundle.
//! * `WOLFSSL_FIPS_VERSION` – `v5` (default; certificate #4718, wolfCrypt
//! 5.2.1) or `v6`; passed as `--enable-fips=<version>`.
//! * `WOLFSSL_FIPS_CORE_HASH` – The in-core integrity hash of the final
//! binary, passed as `-DWOLFCRYPT_FIPS_CORE_HASH_VALUE`. Without it the
//! power-on self-test fails and `fips_mode()` is `false`.
//! * `WOLFSSL_FIPS_CONFIGURE_ARGS` – Extra `configure` arguments, e.g.
//! `--host=aarch64-linux-android` for cross builds.
use std::{ use std::{
env, env,
@ -25,6 +38,11 @@ use std::{
}; };
fn main() { fn main() {
let fips = env::var("CARGO_FEATURE_FIPS").is_ok();
if fips && env::var("CARGO_FEATURE_STUB_FFI").is_ok() {
panic!("\n\nThe `fips` and `stub_ffi` features cannot be combined.\n");
}
// When the `stub_ffi` feature is enabled (e.g. for type-checking without // When the `stub_ffi` feature is enabled (e.g. for type-checking without
// the wolfSSL C library), skip all build steps and write an empty bindings // the wolfSSL C library), skip all build steps and write an empty bindings
// file so the `include!()` in lib.rs still compiles. // file so the `include!()` in lib.rs still compiles.
@ -42,7 +60,10 @@ fn main() {
// ── 1. Locate wolfSSL ──────────────────────────────────────────────────── // ── 1. Locate wolfSSL ────────────────────────────────────────────────────
let (include_dir, lib_dir) = if let Ok(install_dir) = env::var("WOLFSSL_INSTALL_DIR") { let (include_dir, lib_dir) = if fips {
// Never fall back to the open-source build.
build_wolfssl_fips(&out_dir)
} else if let Ok(install_dir) = env::var("WOLFSSL_INSTALL_DIR") {
// Use a pre-installed wolfSSL — skip the CMake build. // Use a pre-installed wolfSSL — skip the CMake build.
let p = PathBuf::from(&install_dir); let p = PathBuf::from(&install_dir);
println!( println!(
@ -89,6 +110,14 @@ fn main() {
// Re-run the build script if any of these change. // Re-run the build script if any of these change.
println!("cargo:rerun-if-env-changed=WOLFSSL_SOURCE_DIR"); println!("cargo:rerun-if-env-changed=WOLFSSL_SOURCE_DIR");
println!("cargo:rerun-if-env-changed=WOLFSSL_INSTALL_DIR"); println!("cargo:rerun-if-env-changed=WOLFSSL_INSTALL_DIR");
for var in [
"WOLFSSL_FIPS_SOURCE_DIR",
"WOLFSSL_FIPS_VERSION",
"WOLFSSL_FIPS_CORE_HASH",
"WOLFSSL_FIPS_CONFIGURE_ARGS",
] {
println!("cargo:rerun-if-env-changed={var}");
}
// ── 3. Generate FFI bindings via bindgen ───────────────────────────────── // ── 3. Generate FFI bindings via bindgen ─────────────────────────────────
@ -201,6 +230,110 @@ fn build_wolfssl_cmake(source_dir: &Path, _out_dir: &Path) -> (PathBuf, PathBuf)
(include_dir, lib_dir) (include_dir, lib_dir)
} }
/// The `fips` feature was asked for but no bundle was given.
const FIPS_SOURCE_MISSING: &str = "\n\n\
The `fips` feature needs the commercial wolfCrypt FIPS 140-3 bundle.\n\
Set WOLFSSL_FIPS_SOURCE_DIR to the unpacked bundle, for example:\n \
export WOLFSSL_FIPS_SOURCE_DIR=$HOME/src/wolfssl-5.2.1-commercial-fips-v5\n\
There is no fallback to the open-source wolfSSL tree.\n";
/// Files only a FIPS bundle has; the open-source tree lacks the first two.
const FIPS_BUNDLE_MARKERS: [&str; 3] =
["wolfcrypt/src/fips.c", "wolfcrypt/src/fips_test.c", "configure"];
/// Build the commercial wolfCrypt FIPS bundle with its own autotools build.
/// wolfSSL's CMake has no FIPS support (its CMakeLists marks it as a TODO),
/// so the bundle's `configure` is the only supported route. Returns
/// `(include_dir, lib_dir)`.
fn build_wolfssl_fips(out_dir: &Path) -> (PathBuf, PathBuf) {
let source = env::var_os("WOLFSSL_FIPS_SOURCE_DIR")
.filter(|v| !v.is_empty())
.map(PathBuf::from)
.unwrap_or_else(|| panic!("{FIPS_SOURCE_MISSING}"));
for marker in FIPS_BUNDLE_MARKERS {
if !source.join(marker).exists() {
panic!(
"\n\nWOLFSSL_FIPS_SOURCE_DIR={} is not a wolfCrypt FIPS bundle \
({marker} is missing).\n{FIPS_SOURCE_MISSING}",
source.display()
);
}
}
if env::var_os("WOLFSSL_INSTALL_DIR").is_some() {
panic!("\n\nWOLFSSL_INSTALL_DIR cannot be used with the `fips` feature.\n");
}
if env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
panic!(
"\n\nFIPS builds for Windows use the bundle's IDE/WIN10 project, \
not this build script.\n"
);
}
let version = env::var("WOLFSSL_FIPS_VERSION").unwrap_or_else(|_| "v5".into());
if !matches!(version.as_str(), "v5" | "v6") {
panic!("\n\nWOLFSSL_FIPS_VERSION must be v5 or v6, not {version:?}.\n");
}
println!(
"cargo:warning=Building wolfCrypt FIPS {version} from {}",
source.display()
);
// configure and make run in a copy: the build writes into the tree.
let tree = out_dir.join("wolfssl-fips-src");
let prefix = out_dir.join("wolfssl-fips-install");
let _ = std::fs::remove_dir_all(&tree);
run(std::process::Command::new("cp").arg("-R").arg(&source).arg(&tree));
let mut cflags = String::from("-DHAVE_XCHACHA");
if let Ok(hash) = env::var("WOLFSSL_FIPS_CORE_HASH") {
if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
panic!("\n\nWOLFSSL_FIPS_CORE_HASH must be 64 hex digits.\n");
}
cflags.push_str(&format!(" -DWOLFCRYPT_FIPS_CORE_HASH_VALUE={hash}"));
} else {
println!(
"cargo:warning=WOLFSSL_FIPS_CORE_HASH is not set: the FIPS self-test \
will fail and fips_mode() will be false until the final binary's \
hash is set (see the crate docs)"
);
}
let mut configure = std::process::Command::new(tree.join("configure"));
configure
.current_dir(&tree)
.arg(format!("--enable-fips={version}"))
.arg(format!("--prefix={}", prefix.display()))
// Static, wolfCrypt only, no test or example programs.
.args(["--enable-static", "--disable-shared", "--enable-cryptonly"])
.args(["--disable-examples", "--disable-crypttests"])
// Approved services the provider uses.
.args(["--enable-aesgcm", "--enable-sha384", "--enable-sha512", "--enable-sha3"])
.args(["--enable-hkdf", "--enable-pwdbased", "--enable-keygen"])
// Non-approved services, outside the FIPS boundary but in the module.
.args(["--enable-chacha", "--enable-poly1305", "--enable-xchacha"])
.args(["--enable-curve25519", "--enable-curve448", "--enable-blake2"])
.arg(format!("CFLAGS={cflags}"));
if let Ok(extra) = env::var("WOLFSSL_FIPS_CONFIGURE_ARGS") {
configure.args(extra.split_whitespace());
}
run(&mut configure);
let jobs = env::var("NUM_JOBS").unwrap_or_else(|_| "4".into());
run(std::process::Command::new("make")
.current_dir(&tree)
.arg(format!("-j{jobs}")));
run(std::process::Command::new("make").current_dir(&tree).arg("install"));
(prefix.join("include"), prefix.join("lib"))
}
fn run(cmd: &mut std::process::Command) {
let status = cmd
.status()
.unwrap_or_else(|e| panic!("\n\nfailed to run {cmd:?}: {e}\n"));
if !status.success() {
panic!("\n\n{cmd:?} failed with {status}\n");
}
}
/// Parse the CMake-generated `options.h` to extract all `#define` directives. /// Parse the CMake-generated `options.h` to extract all `#define` directives.
/// Returns a list of `-DNAME` clang args. /// Returns a list of `-DNAME` clang args.
fn parse_options_defines(include_dir: &Path) -> Vec<String> { fn parse_options_defines(include_dir: &Path) -> Vec<String> {