blob: d4ed42e31877d6341b9dce3c686bf33e4424dc2e [file]
// Licensed under the Apache-2.0 license
// SPDX-License-Identifier: Apache-2.0
//! Loads Caliptra and MCU boot binaries listed in the JSON `.boot_env` runfile
//! generated by `caliptra_mcu_image` (located via `CALIPTRA_BOOT_ENV`) and
//! constructs [`caliptra_mcu_hw_model::InitParams`].
use std::collections::HashMap;
use std::path::PathBuf;
use caliptra_mcu_hw_model::{Fuses, InitParams};
use runfiles::{rlocation, Runfiles};
/// Boot binaries and vendor public key hash for one `caliptra_mcu_image`.
pub struct BootFiles {
pub caliptra_rom: Vec<u8>,
pub caliptra_fw: Vec<u8>,
pub mcu_rom: Vec<u8>,
pub mcu_fw: Vec<u8>,
pub soc_manifest: Vec<u8>,
pub vendor_pk_hash: [u8; 48],
}
impl BootFiles {
/// Loads all boot inputs from the `.boot_env` runfile named by
/// `CALIPTRA_BOOT_ENV`.
///
/// Panics if the runfile or any file it references cannot be read, or if
/// its contents are malformed.
pub fn from_env() -> Self {
Self::try_from_env().expect("failed to load boot files")
}
/// Fallible variant of [`Self::from_env`].
pub fn try_from_env() -> Result<Self, String> {
let runfiles = Runfiles::create().map_err(|e| format!("locating runfiles: {e:?}"))?;
let boot_env = std::env::var("CALIPTRA_BOOT_ENV")
.map_err(|_| "CALIPTRA_BOOT_ENV is not set".to_string())?;
Self::load(&boot_env, |path| rlocation!(runfiles, path))
}
/// Loads boot inputs from the `.boot_env` at rlocation path `boot_env`,
/// using `resolve` to map rlocation paths to filesystem paths.
fn load(boot_env: &str, resolve: impl Fn(&str) -> Option<PathBuf>) -> Result<Self, String> {
let read = |rlocation_path: &str| -> Result<Vec<u8>, String> {
let path = resolve(rlocation_path)
.ok_or_else(|| format!("runfile not found: {rlocation_path}"))?;
std::fs::read(&path).map_err(|e| format!("reading {}: {e}", path.display()))
};
let contents = String::from_utf8(read(boot_env)?)
.map_err(|e| format!("{boot_env} is not UTF-8: {e}"))?;
let entries: HashMap<String, String> =
serde_json::from_str(&contents).map_err(|e| format!("parsing {boot_env}: {e}"))?;
let get = |key: &str| {
entries
.get(key)
.map(String::as_str)
.ok_or_else(|| format!("{boot_env} is missing {key}"))
};
let hash_bytes = hex::decode(get("VENDOR_PK_HASH")?)
.map_err(|e| format!("invalid hex in VENDOR_PK_HASH: {e}"))?;
let vendor_pk_hash: [u8; 48] = hash_bytes.try_into().map_err(|v: Vec<u8>| {
format!("VENDOR_PK_HASH must be 48 bytes, got {} bytes", v.len())
})?;
Ok(Self {
caliptra_rom: read(get("CALIPTRA_ROM")?)?,
caliptra_fw: read(get("CALIPTRA_FW")?)?,
mcu_rom: read(get("MCU_ROM")?)?,
mcu_fw: read(get("MCU_FW")?)?,
soc_manifest: read(get("SOC_MANIFEST")?)?,
vendor_pk_hash,
})
}
/// Returns default [`InitParams`] configured to boot this image through the
/// Caliptra + MCU ROM recovery flow (`active_mode: true`,
/// `enable_mcu_uart_log: true`, `check_booted_to_runtime: true`).
pub fn init_params(&self) -> InitParams<'_> {
// Fuses take the vendor PK hash as big-endian words (matching upstream
// caliptra-mcu-sw's test harness).
let mut fuse_hash = [0u32; 12];
for (word, chunk) in fuse_hash
.iter_mut()
.zip(self.vendor_pk_hash.chunks_exact(4))
{
if let &[a, b, c, d] = chunk {
*word = u32::from_be_bytes([a, b, c, d]);
}
}
InitParams {
fuses: Fuses {
vendor_pk_hash: fuse_hash,
..Default::default()
},
caliptra_rom: &self.caliptra_rom,
caliptra_firmware: &self.caliptra_fw,
mcu_rom: &self.mcu_rom,
mcu_firmware: &self.mcu_fw,
soc_manifest: &self.soc_manifest,
vendor_pk_hash: Some(self.vendor_pk_hash),
active_mode: true,
enable_mcu_uart_log: true,
check_booted_to_runtime: true,
..Default::default()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
const SAMPLE_HASH_HEX: &str = "000102030405060708090a0b0c0d0e0f\
101112131415161718191a1b1c1d1e1f\
202122232425262728292a2b2c2d2e2f";
fn temp_dir(label: &str) -> PathBuf {
let base = std::env::var_os("TEST_TMPDIR")
.map(PathBuf::from)
.unwrap_or_else(std::env::temp_dir);
let dir = base.join(format!("test_boot_files_{}_{label}", std::process::id()));
std::fs::create_dir_all(&dir).expect("create temp dir");
dir
}
/// Writes boot binaries and a `.boot_env` under `root`, returning the
/// `.boot_env` rlocation path. `boot_env_json` overrides its contents.
fn write_fixture(root: &Path, boot_env_json: Option<&str>) -> &'static str {
let pkg = root.join("_main/pkg");
std::fs::create_dir_all(&pkg).expect("create fixture tree");
for (name, contents) in [
("cptra_rom.bin", "cptra_rom"),
("cptra_fw.bin", "cptra_fw"),
("mcu_rom.bin", "mcu_rom"),
("mcu_fw.bin", "mcu_fw"),
("soc.manifest", "manifest"),
] {
std::fs::write(pkg.join(name), contents).unwrap();
}
let default_json = format!(
r#"{{
"CALIPTRA_ROM": "_main/pkg/cptra_rom.bin",
"CALIPTRA_FW": "_main/pkg/cptra_fw.bin",
"MCU_ROM": "_main/pkg/mcu_rom.bin",
"MCU_FW": "_main/pkg/mcu_fw.bin",
"SOC_MANIFEST": "_main/pkg/soc.manifest",
"VENDOR_PK_HASH": "{SAMPLE_HASH_HEX}"
}}"#
);
std::fs::write(
pkg.join("image.boot_env"),
boot_env_json.unwrap_or(&default_json),
)
.unwrap();
"_main/pkg/image.boot_env"
}
fn load_from(root: &Path, boot_env: &str) -> Result<BootFiles, String> {
BootFiles::load(boot_env, |p| Some(root.join(p)))
}
#[test]
fn loads_boot_files_and_packs_big_endian_fuses() {
let root = temp_dir("ok");
let boot_env = write_fixture(&root, None);
let files = load_from(&root, boot_env).expect("load boot files");
assert_eq!(files.caliptra_rom, b"cptra_rom");
assert_eq!(files.caliptra_fw, b"cptra_fw");
assert_eq!(files.mcu_rom, b"mcu_rom");
assert_eq!(files.mcu_fw, b"mcu_fw");
assert_eq!(files.soc_manifest, b"manifest");
let params = files.init_params();
assert_eq!(params.fuses.vendor_pk_hash[0], 0x0001_0203);
assert_eq!(params.fuses.vendor_pk_hash[1], 0x0405_0607);
assert_eq!(params.fuses.vendor_pk_hash[11], 0x2c2d_2e2f);
assert_eq!(params.vendor_pk_hash, Some(files.vendor_pk_hash));
assert!(params.active_mode);
assert!(params.enable_mcu_uart_log);
assert!(params.check_booted_to_runtime);
}
#[test]
fn rejects_malformed_boot_env() {
let root = temp_dir("errors");
let cases = [
("not json", "parsing"),
(r#"{"CALIPTRA_ROM": "_main/pkg/cptra_rom.bin"}"#, "missing"),
(
r#"{"VENDOR_PK_HASH": "not-valid-hex"}"#,
"invalid hex in VENDOR_PK_HASH",
),
(
r#"{"VENDOR_PK_HASH": "00112233"}"#,
"VENDOR_PK_HASH must be 48 bytes, got 4 bytes",
),
];
for (json, expected) in cases {
let boot_env = write_fixture(&root, Some(json));
let err = load_from(&root, boot_env).err().expect("expected error");
assert!(err.contains(expected), "{json:?}: unexpected error {err}");
}
}
#[test]
fn reports_missing_runfile() {
let err = BootFiles::load("_main/pkg/image.boot_env", |_| None)
.err()
.expect("expected error");
assert!(err.contains("runfile not found"), "unexpected error {err}");
}
}