mirror of
https://github.com/saymrwulf/xous-core.git
synced 2026-11-19 09:00:54 +00:00
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
This commit is contained in:
parent
1b36c34341
commit
2175ea60f1
4 changed files with 96 additions and 39 deletions
|
|
@ -5,9 +5,11 @@ extern crate crc;
|
||||||
|
|
||||||
use std::convert::TryInto;
|
use std::convert::TryInto;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
|
use std::io::Read;
|
||||||
|
|
||||||
use clap::{App, Arg};
|
use clap::{App, Arg};
|
||||||
use tools::elf::{read_minielf, read_program};
|
use tools::elf::{read_minielf, read_program};
|
||||||
|
use tools::sign_image::convert_to_uf2;
|
||||||
use tools::swap_writer::SwapWriter;
|
use tools::swap_writer::SwapWriter;
|
||||||
use tools::tags::bflg::Bflg;
|
use tools::tags::bflg::Bflg;
|
||||||
use tools::tags::inie::IniE;
|
use tools::tags::inie::IniE;
|
||||||
|
|
@ -20,6 +22,8 @@ use tools::tags::xkrn::XousKernel;
|
||||||
use tools::utils::{parse_csr_csv, parse_u32};
|
use tools::utils::{parse_csr_csv, parse_u32};
|
||||||
use tools::xous_arguments::XousArguments;
|
use tools::xous_arguments::XousArguments;
|
||||||
|
|
||||||
|
const DEVKEY_PATH: &str = "devkey/dev.key";
|
||||||
|
|
||||||
struct RamConfig {
|
struct RamConfig {
|
||||||
offset: u32,
|
offset: u32,
|
||||||
size: 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);
|
ram_config.regions.add(candidate_region);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn load_pem(src: &str) -> Result<pem::Pem, Box<dyn std::error::Error>> {
|
||||||
|
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<dyn std::error::Error>> {
|
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
let matches = App::new("Xous Image Creator")
|
let matches = App::new("Xous Image Creator")
|
||||||
|
|
@ -165,7 +177,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
.long("swap")
|
.long("swap")
|
||||||
.takes_value(true)
|
.takes_value(true)
|
||||||
.value_name("OFFSET:SIZE")
|
.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(
|
||||||
Arg::with_name("swap-name")
|
Arg::with_name("swap-name")
|
||||||
|
|
@ -194,6 +206,15 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
.required(true)
|
.required(true)
|
||||||
.help("Output file to store tag and init information"),
|
.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();
|
.get_matches();
|
||||||
|
|
||||||
let mut ram_config = RamConfig {
|
let mut ram_config = RamConfig {
|
||||||
|
|
@ -469,6 +490,13 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
|
||||||
println!("Arguments: {}", args);
|
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 {
|
if let Some(mut sargs) = swap_args {
|
||||||
let mut swap_buffer = SwapWriter::new();
|
let mut swap_buffer = SwapWriter::new();
|
||||||
// Transfer our unencrypted data inside sargs to swap_buffer
|
// Transfer our unencrypted data inside sargs to swap_buffer
|
||||||
|
|
@ -477,13 +505,20 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
|
|
||||||
// Create the swap target image and encrypt swap_buffer to it
|
// 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 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));
|
let sf = File::create(swap_filename)
|
||||||
swap_buffer.encrypt_to(sf).expect("Couldn't flush swap buffer to disk");
|
.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 arguments: {}", sargs);
|
||||||
println!("Swap data created in file {}", swap_filename);
|
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") {
|
match matches.value_of("swap-debug-name") {
|
||||||
Some(sf_dbg) => {
|
Some(sf_dbg) => {
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
|
||||||
|
|
@ -205,6 +205,8 @@ pub fn sign_image(
|
||||||
Some("boot1") => FunctionCode::Boot1,
|
Some("boot1") => FunctionCode::Boot1,
|
||||||
Some("loader") => FunctionCode::Loader,
|
Some("loader") => FunctionCode::Loader,
|
||||||
Some("kernel") => FunctionCode::Kernel,
|
Some("kernel") => FunctionCode::Kernel,
|
||||||
|
Some("app") => FunctionCode::App,
|
||||||
|
Some("swap") => FunctionCode::Swap,
|
||||||
_ => FunctionCode::Developer,
|
_ => FunctionCode::Developer,
|
||||||
};
|
};
|
||||||
let mut sealed_fields = SealedFields {
|
let mut sealed_fields = SealedFields {
|
||||||
|
|
@ -292,7 +294,7 @@ pub fn convert_to_uf2<S, T>(
|
||||||
input: &S,
|
input: &S,
|
||||||
output: &T,
|
output: &T,
|
||||||
function_code: Option<&str>,
|
function_code: Option<&str>,
|
||||||
app_id: Option<u8>,
|
offset: Option<usize>,
|
||||||
) -> Result<(), Box<dyn std::error::Error>>
|
) -> Result<(), Box<dyn std::error::Error>>
|
||||||
where
|
where
|
||||||
S: AsRef<Path>,
|
S: AsRef<Path>,
|
||||||
|
|
@ -309,14 +311,15 @@ where
|
||||||
Some("loader") => bao1x_api::LOADER_START,
|
Some("loader") => bao1x_api::LOADER_START,
|
||||||
Some("baremetal") => bao1x_api::BAREMETAL_START,
|
Some("baremetal") => bao1x_api::BAREMETAL_START,
|
||||||
Some("kernel") => bao1x_api::KERNEL_START,
|
Some("kernel") => bao1x_api::KERNEL_START,
|
||||||
Some("app") => {
|
Some("swap") => bao1x_api::SWAP_START_UF2,
|
||||||
bao1x_api::APP_START_UF2
|
|
||||||
| ((app_id.expect("app region specified without ID") as usize) & 0xF) << 24
|
|
||||||
}
|
|
||||||
_ => return Err(String::from("UF2 Image Requires a function code").into()),
|
_ => 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) => {
|
Ok(u2f_blob) => {
|
||||||
dest_file.write_all(&u2f_blob)?;
|
dest_file.write_all(&u2f_blob)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,9 @@ use aes_gcm_siv::{
|
||||||
Aes256GcmSiv, Nonce,
|
Aes256GcmSiv, Nonce,
|
||||||
aead::{Aead, KeyInit, Payload},
|
aead::{Aead, KeyInit, Payload},
|
||||||
};
|
};
|
||||||
|
use bao1x_api::signatures::SwapSourceHeader;
|
||||||
|
|
||||||
|
use crate::sign_image::{Version, sign_image};
|
||||||
|
|
||||||
const SWAP_VERSION: u32 = 0x01_01_0000;
|
const SWAP_VERSION: u32 = 0x01_01_0000;
|
||||||
|
|
||||||
|
|
@ -53,21 +56,22 @@ impl SwapHeader {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns exactly a page of data with the header format serialized
|
/// 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]> {
|
pub fn serialize(&self) -> Result<[u8; 4096]> {
|
||||||
let mut data = Cursor::new(Vec::<u8>::new());
|
let mut data = Cursor::new(Vec::<u8>::new());
|
||||||
let mut output = [0u8; 4096];
|
let mut output = [0u8; 4096];
|
||||||
|
|
||||||
data.write(&SWAP_VERSION.to_le_bytes())?;
|
let mut ssh = SwapSourceHeader::default();
|
||||||
// note that the nonce is in big-endian format, as is expected for cryptographic matter
|
ssh.version = SWAP_VERSION;
|
||||||
data.write(&self.partial_nonce.to_be_bytes())?;
|
ssh.partial_nonce.copy_from_slice(&self.partial_nonce.to_be_bytes());
|
||||||
|
ssh.mac_offset = self.mac_offset as u32;
|
||||||
// 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
|
|
||||||
assert!(self.aad.len() < 64, "AAD is limited to 64 bytes");
|
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
|
ssh.aad_len = self.aad.len() as u32;
|
||||||
data.write(&self.aad)?; // BE because this is cryptographic matter
|
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());
|
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
|
/// Take the swap file and wrap it data structures that facilitate per-device encryption
|
||||||
/// after deployment to a user device.
|
/// after deployment to a user device.
|
||||||
pub fn encrypt_to<T>(&mut self, mut f: T) -> Result<usize>
|
pub fn encrypt_to<T>(&mut self, mut f: T, private_key: &pem::Pem) -> Result<usize>
|
||||||
where
|
where
|
||||||
T: Write + Seek,
|
T: Write + Seek,
|
||||||
{
|
{
|
||||||
let header = SwapHeader::new(self.buffer.get_ref().len());
|
let header = SwapHeader::new(self.buffer.get_ref().len());
|
||||||
let mut macs = Vec::<u8>::new();
|
let mut macs = Vec::<u8>::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
|
// 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
|
// 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);
|
assert!(enc.len() == 0x1010);
|
||||||
// println!("data: {:x?}", &enc[..32]);
|
// println!("data: {:x?}", &enc[..32]);
|
||||||
// println!("tag: {:x?}", &enc[0x1000..]);
|
// println!("tag: {:x?}", &enc[0x1000..]);
|
||||||
f.write(&enc[..0x1000])?;
|
image.write(&enc[..0x1000])?;
|
||||||
macs.extend_from_slice(&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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,10 +14,6 @@ pub struct Swap {
|
||||||
/// Region name (as a type)
|
/// Region name (as a type)
|
||||||
pub name: XousArgumentCode,
|
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
|
/// Starting offset of swap in FLASH
|
||||||
pub offset_flash: u32,
|
pub offset_flash: u32,
|
||||||
}
|
}
|
||||||
|
|
@ -25,7 +21,6 @@ pub struct Swap {
|
||||||
impl fmt::Display for Swap {
|
impl fmt::Display for Swap {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
writeln!(f, " Swap: {:08x} - {:08x}", self.offset, self.offset + self.size)?;
|
writeln!(f, " Swap: {:08x} - {:08x}", self.offset, self.offset + self.size)?;
|
||||||
writeln!(f, " key: {:x?}", self.key)?;
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -36,7 +31,6 @@ impl Swap {
|
||||||
offset,
|
offset,
|
||||||
size,
|
size,
|
||||||
name: u32::from_le_bytes(*b"Swap") as XousArgumentCode,
|
name: u32::from_le_bytes(*b"Swap") as XousArgumentCode,
|
||||||
key: [0u8; 32],
|
|
||||||
// location for swap offset in FLASH (for precursor)
|
// location for swap offset in FLASH (for precursor)
|
||||||
offset_flash: 0x21200000,
|
offset_flash: 0x21200000,
|
||||||
}
|
}
|
||||||
|
|
@ -46,16 +40,17 @@ impl Swap {
|
||||||
impl XousArgument for Swap {
|
impl XousArgument for Swap {
|
||||||
fn code(&self) -> XousArgumentCode { self.name }
|
fn code(&self) -> XousArgumentCode { self.name }
|
||||||
|
|
||||||
fn length(&self) -> XousSize { (16 + 32) as XousSize }
|
fn length(&self) -> XousSize { size_of::<bao1x_api::signatures::SwapDescriptor>() as XousSize }
|
||||||
|
|
||||||
fn serialize(&self, output: &mut dyn io::Write) -> io::Result<usize> {
|
fn serialize(&self, output: &mut dyn io::Write) -> io::Result<usize> {
|
||||||
let mut written = 0;
|
let mut descriptor = bao1x_api::signatures::SwapDescriptor::default();
|
||||||
output.write_all(&self.offset.to_le_bytes())?;
|
descriptor.ram_offset = self.offset;
|
||||||
output.write_all(&self.size.to_le_bytes())?;
|
descriptor.ram_size = self.size;
|
||||||
output.write_all(&self.name.to_le_bytes())?;
|
descriptor.name = self.name;
|
||||||
output.write_all(&self.key)?;
|
descriptor.key.fill(0); // slot in the "dummy" key for new images - we could use anything, but it needs to be provided
|
||||||
output.write_all(&self.offset_flash.to_le_bytes())?;
|
descriptor.flash_offset = self.offset_flash;
|
||||||
written += 4 * 4 + 32;
|
|
||||||
Ok(written)
|
output.write(descriptor.as_ref())?;
|
||||||
|
Ok(descriptor.as_ref().len())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue