From 2175ea60f17e87cc24477414d14e21b781278d1f Mon Sep 17 00:00:00 2001 From: bunnie Date: Sat, 4 Oct 2025 00:49:56 +0800 Subject: [PATCH] improve the tools for creating images - use more structural templating to place data, instead of just hand-coded writes to a buffer - add private key signature generation to the swap image --- tools/src/bin/create-image.rs | 43 ++++++++++++++++++++++++++--- tools/src/sign_image.rs | 15 ++++++---- tools/src/swap_writer.rs | 52 +++++++++++++++++++++++++---------- tools/src/tags/swap.rs | 25 +++++++---------- 4 files changed, 96 insertions(+), 39 deletions(-) diff --git a/tools/src/bin/create-image.rs b/tools/src/bin/create-image.rs index 19246e109..a37965bf7 100644 --- a/tools/src/bin/create-image.rs +++ b/tools/src/bin/create-image.rs @@ -5,9 +5,11 @@ extern crate crc; use std::convert::TryInto; use std::fs::File; +use std::io::Read; use clap::{App, Arg}; use tools::elf::{read_minielf, read_program}; +use tools::sign_image::convert_to_uf2; use tools::swap_writer::SwapWriter; use tools::tags::bflg::Bflg; use tools::tags::inie::IniE; @@ -20,6 +22,8 @@ use tools::tags::xkrn::XousKernel; use tools::utils::{parse_csr_csv, parse_u32}; use tools::xous_arguments::XousArguments; +const DEVKEY_PATH: &str = "devkey/dev.key"; + struct RamConfig { offset: u32, size: u32, @@ -81,6 +85,14 @@ fn csr_to_config(hv: tools::utils::CsrConfig, ram_config: &mut RamConfig) { ram_config.regions.add(candidate_region); } +pub fn load_pem(src: &str) -> Result> { + let mut input = vec![]; + let mut pemfile = std::fs::File::open(src)?; + pemfile.read_to_end(&mut input)?; + + Ok(pem::parse(input)?) +} + fn main() -> Result<(), Box> { env_logger::init(); let matches = App::new("Xous Image Creator") @@ -165,7 +177,7 @@ fn main() -> Result<(), Box> { .long("swap") .takes_value(true) .value_name("OFFSET:SIZE") - .help("Swap offset and size, in the form of [offset]:[size]; note: offset and size have platform-dependent interpretations") + .help("Swap memory regions, in the form of [ram offset]:[ram size]; note: offset and size have platform-dependent interpretations") ) .arg( Arg::with_name("swap-name") @@ -194,6 +206,15 @@ fn main() -> Result<(), Box> { .required(true) .help("Output file to store tag and init information"), ) + .arg( + Arg::with_name("swap-key") + .long("swap-key") + .takes_value(true) + .required(true) + .help("swap signing key") + .value_name("swap signing key") + .default_value(DEVKEY_PATH), + ) .get_matches(); let mut ram_config = RamConfig { @@ -469,6 +490,13 @@ fn main() -> Result<(), Box> { println!("Arguments: {}", args); + let swap_key = matches.value_of("swap-key").expect("no swap key specified"); + let swap_pkey = load_pem(swap_key)?; + if swap_pkey.tag != "PRIVATE KEY" { + println!("Kernel key was a {}, not a PRIVATE KEY", swap_pkey.tag); + Err("invalid kernel private key type")?; + } + if let Some(mut sargs) = swap_args { let mut swap_buffer = SwapWriter::new(); // Transfer our unencrypted data inside sargs to swap_buffer @@ -477,13 +505,20 @@ fn main() -> Result<(), Box> { // Create the swap target image and encrypt swap_buffer to it let swap_filename = matches.value_of("swap-name").expect("swap filename not present"); - let sf = File::create(swap_filename) - .unwrap_or_else(|_| panic!("Couldn't create output file {}", swap_filename)); - swap_buffer.encrypt_to(sf).expect("Couldn't flush swap buffer to disk"); + { + let sf = File::create(swap_filename) + .unwrap_or_else(|_| panic!("Couldn't create output file {}", swap_filename)); + swap_buffer.encrypt_to(sf, &swap_pkey).expect("Couldn't flush swap buffer to disk"); + } // drop sf, so it closes println!("Swap arguments: {}", sargs); println!("Swap data created in file {}", swap_filename); + let swap_uf2 = format!("{}uf2", &swap_filename[..swap_filename.len() - 3]); + // generate a uf2 file + convert_to_uf2(&swap_filename, &swap_uf2, Some("swap"), None)?; + println!("Created UF2 at {}", swap_uf2); + match matches.value_of("swap-debug-name") { Some(sf_dbg) => { use std::io::Write; diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index 8bf183059..3c01c0839 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -205,6 +205,8 @@ pub fn sign_image( Some("boot1") => FunctionCode::Boot1, Some("loader") => FunctionCode::Loader, Some("kernel") => FunctionCode::Kernel, + Some("app") => FunctionCode::App, + Some("swap") => FunctionCode::Swap, _ => FunctionCode::Developer, }; let mut sealed_fields = SealedFields { @@ -292,7 +294,7 @@ pub fn convert_to_uf2( input: &S, output: &T, function_code: Option<&str>, - app_id: Option, + offset: Option, ) -> Result<(), Box> where S: AsRef, @@ -309,14 +311,15 @@ where Some("loader") => bao1x_api::LOADER_START, Some("baremetal") => bao1x_api::BAREMETAL_START, Some("kernel") => bao1x_api::KERNEL_START, - Some("app") => { - bao1x_api::APP_START_UF2 - | ((app_id.expect("app region specified without ID") as usize) & 0xF) << 24 - } + Some("swap") => bao1x_api::SWAP_START_UF2, _ => return Err(String::from("UF2 Image Requires a function code").into()), }; - match bin_to_uf2(&source, bao1x_api::BAOCHIP_1X_UF2_FAMILY, app_start_addr as u32) { + match bin_to_uf2( + &source, + bao1x_api::BAOCHIP_1X_UF2_FAMILY, + app_start_addr as u32 + offset.unwrap_or(0) as u32, + ) { Ok(u2f_blob) => { dest_file.write_all(&u2f_blob)?; Ok(()) diff --git a/tools/src/swap_writer.rs b/tools/src/swap_writer.rs index 8f8fe9a1a..4a9451e33 100644 --- a/tools/src/swap_writer.rs +++ b/tools/src/swap_writer.rs @@ -6,6 +6,9 @@ use aes_gcm_siv::{ Aes256GcmSiv, Nonce, aead::{Aead, KeyInit, Payload}, }; +use bao1x_api::signatures::SwapSourceHeader; + +use crate::sign_image::{Version, sign_image}; const SWAP_VERSION: u32 = 0x01_01_0000; @@ -53,21 +56,22 @@ impl SwapHeader { } /// Returns exactly a page of data with the header format serialized + /// Header format is in loader/src/swap.rs/SwapSourceHeader pub fn serialize(&self) -> Result<[u8; 4096]> { let mut data = Cursor::new(Vec::::new()); let mut output = [0u8; 4096]; - data.write(&SWAP_VERSION.to_le_bytes())?; - // note that the nonce is in big-endian format, as is expected for cryptographic matter - data.write(&self.partial_nonce.to_be_bytes())?; - - // serialize the MAC data offset - data.write(&(self.mac_offset as u32).to_le_bytes())?; // LE because this is a size field - - // serialize the AAD + let mut ssh = SwapSourceHeader::default(); + ssh.version = SWAP_VERSION; + ssh.partial_nonce.copy_from_slice(&self.partial_nonce.to_be_bytes()); + ssh.mac_offset = self.mac_offset as u32; assert!(self.aad.len() < 64, "AAD is limited to 64 bytes"); - data.write(&(self.aad.len() as u32).to_le_bytes())?; // LE because this is a size field - data.write(&self.aad)?; // BE because this is cryptographic matter + ssh.aad_len = self.aad.len() as u32; + for (dst, &src) in ssh.aad.iter_mut().zip(self.aad.iter()) { + *dst = src; + } + + data.write(ssh.as_ref())?; output[..data.position() as usize].copy_from_slice(&data.into_inner()); @@ -80,14 +84,16 @@ impl SwapWriter { /// Take the swap file and wrap it data structures that facilitate per-device encryption /// after deployment to a user device. - pub fn encrypt_to(&mut self, mut f: T) -> Result + pub fn encrypt_to(&mut self, mut f: T, private_key: &pem::Pem) -> Result where T: Write + Seek, { let header = SwapHeader::new(self.buffer.get_ref().len()); let mut macs = Vec::::new(); - f.write(&header.serialize()?)?; + let unsigned_header = header.serialize()?; + + let mut image = Vec::new(); // encrypt using the "zero key" for the default distribution. The intention is not to // provide security, but to lay out the data structure so that a future re-encryption to a @@ -114,11 +120,29 @@ impl SwapWriter { assert!(enc.len() == 0x1010); // println!("data: {:x?}", &enc[..32]); // println!("tag: {:x?}", &enc[0x1000..]); - f.write(&enc[..0x1000])?; + image.write(&enc[..0x1000])?; macs.extend_from_slice(&enc[0x1000..]); } - f.write(&macs) + image.write(&macs)?; + + let function = Some("swap"); + let signed = sign_image( + &image, + private_key, + false, + &None, + None, + true, + bao1x_api::signatures::SIGBLOCK_LEN, + Version::Bao1xV1, + function, + ) + .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Can't sign swap image"))?; + // write the header, less space for the signature + f.write(&unsigned_header[..4096 - bao1x_api::signatures::SIGBLOCK_LEN])?; + + f.write(&signed) } } diff --git a/tools/src/tags/swap.rs b/tools/src/tags/swap.rs index ff313697b..aaeaef494 100644 --- a/tools/src/tags/swap.rs +++ b/tools/src/tags/swap.rs @@ -14,10 +14,6 @@ pub struct Swap { /// Region name (as a type) pub name: XousArgumentCode, - /// Encryption key. Set to 0 by the image creator, but set to something more interesting - /// by the device upon completion of the keying ceremony. - pub key: [u8; 32], - /// Starting offset of swap in FLASH pub offset_flash: u32, } @@ -25,7 +21,6 @@ pub struct Swap { impl fmt::Display for Swap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, " Swap: {:08x} - {:08x}", self.offset, self.offset + self.size)?; - writeln!(f, " key: {:x?}", self.key)?; Ok(()) } } @@ -36,7 +31,6 @@ impl Swap { offset, size, name: u32::from_le_bytes(*b"Swap") as XousArgumentCode, - key: [0u8; 32], // location for swap offset in FLASH (for precursor) offset_flash: 0x21200000, } @@ -46,16 +40,17 @@ impl Swap { impl XousArgument for Swap { fn code(&self) -> XousArgumentCode { self.name } - fn length(&self) -> XousSize { (16 + 32) as XousSize } + fn length(&self) -> XousSize { size_of::() as XousSize } fn serialize(&self, output: &mut dyn io::Write) -> io::Result { - let mut written = 0; - output.write_all(&self.offset.to_le_bytes())?; - output.write_all(&self.size.to_le_bytes())?; - output.write_all(&self.name.to_le_bytes())?; - output.write_all(&self.key)?; - output.write_all(&self.offset_flash.to_le_bytes())?; - written += 4 * 4 + 32; - Ok(written) + let mut descriptor = bao1x_api::signatures::SwapDescriptor::default(); + descriptor.ram_offset = self.offset; + descriptor.ram_size = self.size; + descriptor.name = self.name; + descriptor.key.fill(0); // slot in the "dummy" key for new images - we could use anything, but it needs to be provided + descriptor.flash_offset = self.offset_flash; + + output.write(descriptor.as_ref())?; + Ok(descriptor.as_ref().len()) } }