Merge pull request #822 from betrusted-io/baobit-audit

Baobit audit
This commit is contained in:
bunnie 2026-02-16 20:14:47 +08:00 committed by GitHub
commit 5397e1b488
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 76 additions and 23 deletions

View file

@ -1,7 +1,7 @@
use core::convert::TryInto;
use bao1x_api::pubkeys::{BOOT0_SELF_CHECK, BOOT0_TO_BOOT1, BOOT1_TO_LOADER_OR_BAREMETAL};
use bao1x_api::signatures::{SignatureInFlash, UNSIGNED_LEN};
use bao1x_api::signatures::{SIGBLOCK_LEN, SignatureInFlash, UNSIGNED_LEN};
use bao1x_api::*;
use bao1x_hal::acram::OneWayCounter;
use bao1x_hal::sigcheck::ERASE_VALUE;
@ -29,6 +29,18 @@ fn hash_region(region: &[u8], description: &str) {
crate::println!("{}: {}", description, hex_str);
}
fn report_toolchain(sig: &SignatureInFlash, description: &str) {
let hash = sig.sealed_data.toolchain;
if hash == [0u8; 20] {
crate::println!("{}: unspecified", description);
} else {
let mut buffer = [0u8; 40];
hex::encode_to_slice(&hash, &mut buffer).unwrap();
let hex_str = core::str::from_utf8(&buffer).unwrap();
crate::println!("{}: {}", description, hex_str);
}
}
/// Stepping detection: attempt to modify the RRCR configuration. If bit 12 (code area protection)
/// can be flipped, then we are A0 stepping.
fn detect_stepping() -> &'static str {
@ -57,7 +69,6 @@ pub fn audit() {
crate::println!("Board type reads as: {:?}", boardtype);
crate::println!("Boot partition is: {:?}", owc.get_decoded::<AltBootCoding>());
crate::println!("Semver is: {}", crate::version::SEMVER);
crate::println!("Baobit commit is: {}", crate::version::BAOBIT_COMMIT);
crate::println!("Description is: {}", crate::RELEASE_DESCRIPTION);
crate::println!("Stepping is: {}", detect_stepping());
let slot_mgr = bao1x_hal::acram::SlotManager::new();
@ -169,12 +180,13 @@ pub fn audit() {
let b0_pk: &SignatureInFlash = unsafe { b0_pk_ptr.as_ref().unwrap() };
let boot0_used = unsafe {
core::slice::from_raw_parts(
(bao1x_api::BOOT0_START + UNSIGNED_LEN) as *const u8,
b0_pk.sealed_data.signed_len as usize,
(bao1x_api::BOOT0_START + SIGBLOCK_LEN) as *const u8,
b0_pk.sealed_data.signed_len as usize - (SIGBLOCK_LEN - UNSIGNED_LEN),
)
};
// only the portion that's protected by signature
// only the portion that's strictly reproducible
hash_region(boot0_used, "boot0 code only");
report_toolchain(b0_pk, "boot0 baobit toolchain");
let boot1_region = unsafe {
core::slice::from_raw_parts(
@ -185,6 +197,18 @@ pub fn audit() {
// includes free space
hash_region(boot1_region, "boot1 partition");
let b1_pk_ptr = bao1x_api::BOOT1_START as *const SignatureInFlash;
let b1_pk: &SignatureInFlash = unsafe { b1_pk_ptr.as_ref().unwrap() };
let boot1_used = unsafe {
core::slice::from_raw_parts(
(bao1x_api::BOOT1_START + SIGBLOCK_LEN) as *const u8,
b1_pk.sealed_data.signed_len as usize - (SIGBLOCK_LEN - UNSIGNED_LEN),
)
};
// only the portion that's strictly reproducible
hash_region(boot1_used, "boot1 code only");
report_toolchain(b1_pk, "boot1 baobit toolchain");
// detailed state checks
let mut secure = true;
// check that boot1 pubkeys match the indelible entries

View file

@ -162,6 +162,16 @@ pub struct SealedFields {
///
/// If no valid keys are found, the device is effectively bricked and goes into a "die" state.
pub pubkeys: [Pubkey; 4],
/// Placeholder for baobit commit: this is the hash of the toolchain used to generate the image.
/// In many images, this is just 0's; but for signed release images, this is injected into the file
/// prior to applying the final signature. This injection has to happen after everything is done
/// because the rules of the reproducible build system disallow it from knowing its final commit
/// state: you have to commit its final state, which changes its reported commit state, and so
/// forth, so at build time you can't know what toolchain was used to build you - only after
/// the build is complete is the information revealed to the user.
///
/// This field is long enough to hold a SHA-1 git hash.
pub toolchain: [u8; 20],
}
impl AsRef<[u8]> for SealedFields {
@ -178,6 +188,7 @@ impl Default for SealedFields {
min_semver: [0u8; 16],
semver: [0u8; 16],
pubkeys: [Pubkey::default(); 4],
toolchain: [0u8; 20],
}
}
}

View file

@ -43,6 +43,10 @@ struct Args {
/// Function code e.g. partition - if provided, creates a uf2 file
#[arg(short = 'p', long = "function-code", value_name = "CODE")]
function_code: Option<String>,
/// Hash to embed in the signature (hex string)
#[arg(short = 'b', long = "baobit-hash", value_name = "HASH")]
baobit_hash: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
@ -58,6 +62,11 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Parse command line arguments
let args = Args::parse();
let baobit_hash: Option<[u8; 20]> = args.baobit_hash.as_deref().map(|hex_str| {
let vec = hex::decode(hex_str).expect("invalid hex string");
vec.try_into().expect("Baobit hash must be exactly 20 bytes")
});
// Load and parse the credential file
let credential_data = fs::read_to_string(&args.credential_file)
.map_err(|e| format!("Failed to read credential file: {}", e))?;
@ -100,6 +109,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
sig.as_mut().copy_from_slice(&file[offset..offset + size_of::<SignatureInFlash>()]);
if sig.sealed_data.magic == bao1x_api::signatures::MAGIC_NUMBER {
is_bao1x = true;
// inject the baobit hash here, if it is specified
if let Some(toolchain) = baobit_hash {
patch_hash_in_file(&file_path, &toolchain, offset)?;
}
// Re-read the file so we hash the patched contents
let file = fs::read(&file_path)
.map_err(|e| format!("Failed to re-read file '{}': {}", file_path.display(), e))?;
let mut h: Sha512 = Sha512::new();
// hash the sealed region
h.update(&file[offset + SignatureInFlash::sealed_data_offset()..]);
@ -212,6 +228,22 @@ fn patch_signature_in_file(
Ok(())
}
fn patch_hash_in_file(
file_path: &PathBuf,
hash: &[u8],
offset: usize,
) -> Result<(), Box<dyn std::error::Error>> {
// Open file with read and write permissions
let mut file = OpenOptions::new().read(true).write(true).open(file_path)?;
let mut signature_struct = read_header_from_file(&mut file, offset)?;
signature_struct.sealed_data.toolchain.copy_from_slice(&hash);
write_header_to_file(&mut file, &signature_struct, offset)?;
Ok(())
}
fn read_header_from_file(
file: &mut std::fs::File,
offset: usize,

View file

@ -657,6 +657,7 @@ def main():
# now try to download all the artifacts and check their versions
# this list should visit kernels in order from newest to oldest.
URL_LIST = [
'https://ci.betrusted.io/releases/v0.10.0/',
'https://ci.betrusted.io/releases/v0.9.16/',
'https://ci.betrusted.io/releases/v0.9.15/',
'https://ci.betrusted.io/releases/v0.9.14/',

View file

@ -60,8 +60,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
let do_version = env::args().filter(|x| x == "--no-timestamp").count() == 0;
let git_describe_opt = get_flag("--git-describe")?.first().cloned();
let git_rev_opt = get_flag("--git-rev")?.first().cloned();
let baobit_commit_opt = get_flag("--baobit-commit")?.first().cloned();
generate_version(do_version, git_describe_opt.clone(), baobit_commit_opt.clone());
generate_version(do_version, git_describe_opt.clone());
if let Some(desc) = git_describe_opt {
builder.set_git_describe(desc);
}

View file

@ -27,11 +27,7 @@ fn write_if_changed(path: &str, new_data: &[u8]) {
vfile.write_all(new_data).expect(&format!("couldn't write to {}", path));
}
pub(crate) fn generate_version(
add_timestamp: bool,
forced_version: Option<String>,
baobit_commit: Option<String>,
) {
pub(crate) fn generate_version(add_timestamp: bool, forced_version: Option<String>) {
let gitver = {
if let Some(ver) = forced_version {
ver.as_bytes().to_vec()
@ -77,17 +73,7 @@ pub(crate) fn generate_version(
.expect("couldn't add our semver");
new_data.extend_from_slice(&semver_code);
// Baochip versioning is just SEMVER + BAOBIT_COMMIT. Now that
// the semver_code has been added to new_data, we can extend it with the Baobit commit.
if let Some(ref commit) = baobit_commit {
writeln!(semver_code, "pub const BAOBIT_COMMIT: &'static str = \"{}\";", commit)
.expect("couldn't add baobit commit");
} else {
// For builds that aren't built in the reproducible environment, the baobit commit is unspecified
writeln!(semver_code, "pub const BAOBIT_COMMIT: &'static str = \"unspecified\";")
.expect("couldn't add baobit commit placeholder");
}
// Baochip versioning is just SEMVER
write_if_changed(version_file, &new_data);
write_if_changed(boot0_version_file, &semver_code);
write_if_changed(boot1_version_file, &semver_code);