diff --git a/tools/Cargo.toml b/tools/Cargo.toml index a9e7681d0..547431a32 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -27,6 +27,9 @@ name = "copy-object" [[bin]] name = "create-image" +[[bin]] +name = "make-renode-boot" + [[bin]] name = "make-tags" diff --git a/tools/src/bin/make-renode-boot.rs b/tools/src/bin/make-renode-boot.rs new file mode 100644 index 000000000..f312ef2c2 --- /dev/null +++ b/tools/src/bin/make-renode-boot.rs @@ -0,0 +1,238 @@ +extern crate crc; + +use std::collections::VecDeque; +use std::convert::TryInto; +use std::fs::File; +use std::io::Write; + +use tools::elf::{process_minielf, process_program, read_minielf}; +use tools::sign_image::sign_image; +use tools::tags::inie::IniE; +use tools::tags::memory::{MemoryRegion, MemoryRegions}; +use tools::tags::pnam::ProcessNames; +use tools::tags::xkrn::XousKernel; +use tools::xous_arguments::XousArguments; + +struct RamConfig { + offset: u32, + size: u32, + name: u32, + regions: MemoryRegions, + memory_required: u32, +} + +fn csr_to_config(hv: tools::utils::CsrConfig, ram_config: &mut RamConfig) { + let mut found_ram_name = None; + fn round_mem(src: u32) -> u32 { + (src + 4095) & !4095 + } + // Look for the largest "ram" block, which we'll treat as main memory + for (k, v) in &hv.regions { + if k.find("ram").is_some() && v.length > ram_config.size { + ram_config.size = round_mem(v.length); + ram_config.offset = v.start; + found_ram_name = Some(k.clone()); + } + } + + if found_ram_name.is_none() { + eprintln!("Error: Couldn't find a memory region named \"ram\" in config file"); + return; + } + + // Now that we know which block is ram, add the other regions. + let found_ram_name = MemoryRegion::make_name(&found_ram_name.unwrap()); + for (k, v) in &hv.regions { + ram_config.memory_required += round_mem(v.length) / 4096; + let region_name = MemoryRegion::make_name(k); + // Don't add the RAM section to the extra regions block. + if region_name == found_ram_name { + ram_config.name = region_name; + continue; + } + // Don't add empty sections. + if round_mem(v.length) == 0 { + continue; + } + ram_config + .regions + .add(MemoryRegion::new(v.start, round_mem(v.length), region_name)); + } +} +fn create_image(init_programs: &[String]) -> std::io::Result> { + env_logger::init(); + + let mut ram_config = RamConfig { + offset: Default::default(), + size: Default::default(), + name: MemoryRegion::make_name("sram"), + regions: MemoryRegions::new(), + memory_required: 0, + }; + + let mut process_names = ProcessNames::new(); + + let soc_svd_file = include_bytes!("../../../utralib/renode/renode.svd"); + let desc = svd2utra::parse_svd(soc_svd_file.as_slice()).unwrap(); + let mut map = std::collections::BTreeMap::new(); + + let mut csr_top = 0; + for peripheral in desc.peripherals { + if peripheral.base > csr_top { + csr_top = peripheral.base; + } + } + for region in desc.memory_regions { + // Ignore the "CSR" region and manually reconstruct it, because this + // region is largely empty and we want to avoid allocating too much space. + if region.name == "CSR" { + const PAGE_SIZE: usize = 4096; + // round to the nearest page, then add one page as the last entry in the csr_top + // is an alloatable page, and not an end-stop. + let length = if csr_top - region.base & (PAGE_SIZE - 1) == 0 { + csr_top - region.base + } else { + ((csr_top - region.base) & !(PAGE_SIZE - 1)) + PAGE_SIZE + } + PAGE_SIZE; + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: length.try_into().unwrap(), + }, + ); + } else { + map.insert( + region.name.to_lowercase(), + tools::utils::CsrMemoryRegion { + start: region.base.try_into().unwrap(), + length: region.size.try_into().unwrap(), + }, + ); + } + } + csr_to_config(tools::utils::CsrConfig { regions: map }, &mut ram_config); + + let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); + + if !ram_config.regions.is_empty() { + args.add(ram_config.regions); + } + + let kernel = process_program(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-kernel" + )) + .expect("unable to read kernel"); + process_names.set(1, "kernel"); + + let pid = 2; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-ticktimer" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-ticktimer"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-log" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-log"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-names" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-names"); + + let pid = pid + 1; + let init = process_minielf(include_bytes!( + "../../../target/riscv32imac-unknown-xous-elf/release/xous-susres" + )) + .expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + process_names.set(pid, "xous-susres"); + + let mut pid = pid + 1; + for init_path in init_programs { + let program_name = std::path::Path::new(&init_path); + println!("Adding {} to output", program_name.display()); + process_names.set( + pid, + program_name + .file_stem() + .expect("program had no name") + .to_str() + .expect("program name is not valid utf-8"), + ); + let init = read_minielf(init_path).expect("couldn't parse init file"); + args.add(IniE::new(init.entry_point, init.sections, init.program)); + pid += 1; + } + + let xkrn = XousKernel::new( + kernel.text_offset, + kernel.text_size, + kernel.data_offset, + kernel.data_size, + kernel.bss_size, + kernel.entry_point, + kernel.program, + ); + args.add(xkrn); + + args.add(process_names); + + // Add tags for init and kernel. These point to the actual data, which should + // immediately follow the tags. Therefore, we must know the length of the tags + // before we create them. + let mut f = vec![]; + args.write(&mut f).expect("Couldn't write to args"); + + println!("Arguments: {}", args); + + println!( + "Runtime will require {} bytes to track memory allocations", + ram_config.memory_required + ); + Ok(f) +} + +fn main() -> Result<(), Box> { + let mut args: VecDeque = std::env::args().collect(); + println!("Args: {:?}", args); + let program = args.pop_front().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::Other, "program name not present") + })?; + let output_filename = args.pop_front().ok_or_else(|| { + std::io::Error::new(std::io::ErrorKind::Other, "output filename not present") + })?; + args.make_contiguous(); + + if args.len() == 0 { + return Err("no init programs specified".into()); + } + println!("Program: {}", program); + println!("Output file: {}", output_filename); + println!("Init args: {:?}", args); + let xous_presign_img = create_image(args.as_slices().0)?; + + let xous_pkey = pem::parse(include_bytes!("../../../devkey/dev.key"))?; + if xous_pkey.tag != "PRIVATE KEY" { + println!("Xous image key was a {}, not a PRIVATE KEY", xous_pkey.tag); + return Err("invalid xous image private key type".into()); + } + println!("Signing output image"); + let xous_img = sign_image(&xous_presign_img, &xous_pkey, false, &None, Some([0u8; 16]))?; + + let mut output_file = File::create(&output_filename)?; + output_file.write_all(&xous_img)?; + + println!("Successfully wrote {}", output_filename); + + Ok(()) +} diff --git a/tools/src/bin/sign-image.rs b/tools/src/bin/sign-image.rs index f625e0a9a..3d5fe2574 100644 --- a/tools/src/bin/sign-image.rs +++ b/tools/src/bin/sign-image.rs @@ -1,6 +1,7 @@ use clap::{crate_version, App, Arg}; -use std::io::{Read, Write, ErrorKind, Error}; +use std::io::{Error, ErrorKind, Read, Write}; use std::path::Path; +use tools::sign_image::{load_pem, sign_file}; use ring::signature::Ed25519KeyPair; @@ -9,86 +10,6 @@ const LOADER_VERSION: u32 = 1; use xous_semver::SemVer; -fn image_sign( - input: &S, - output: &T, - private_key: &pem::Pem, - defile: bool, - minver: &Option, -) -> Result<(), Box> -where - S: AsRef, - T: AsRef, -{ - let mut source = vec![]; - let mut source_file = std::fs::File::open(input)?; - let mut dest_file = std::fs::File::create(output)?; - source_file.read_to_end(&mut source)?; - - // Append version information to the binary. Appending it here means it is part - // of the signed bundle. - let minver_bytes = if let Some(mv) = minver {mv.into()} else {[0u8; 16]}; - let semver: [u8; 16] = SemVer::from_git() - .map_err(|_| Error::new(ErrorKind::Other, "error parsing current Git rev"))? - .into(); - // extra data appended here needs to be reflected in two places in Xous: - // 1. root-keys/src/implementation.rs @ sign-loader() - // 2. graphics-server/src/main.rs @ Some(Opcode::BulkReadfonts) - // This is because memory ownership is split between two crates for performance reasons: - // the direct memory page of fonts belongs to the graphics server, to avoid having to send - // a message on every font lookup. However, the keys reside in root-keys, so therefore, - // a bulk read operation has to shuttle font data back to the root-keys crate. Of course, - // the appended metadata is in the font region, so, this data has to be shuttled back. - // The graphics server is also entirely naive to how much cryptographic data is in the font - // region, and I think it's probably better for it to stay that way. - source.append(&mut minver_bytes.to_vec()); - source.append(&mut semver.to_vec()); - for &b in LOADER_VERSION.to_le_bytes().iter() { - source.push(b); - } - for &b in (source.len() as u32).to_le_bytes().iter() { - source.push(b); - } - - // NOTE NOTE NOTE - // can't find a good ASN.1 ED25519 key decoder, just relying on the fact that the last - // 32 bytes are "always" the private key. always? the private key? - let signing_key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents) - .map_err(|e| format!("{}", e))?; - let signature = signing_key.sign(&source); - - dest_file.write_all(&LOADER_VERSION.to_le_bytes())?; - dest_file.write_all(&(source.len() as u32).to_le_bytes())?; - - // Write the signature data - let signature_u8 = &signature.as_ref(); - dest_file.write_all(signature_u8)?; - - // Pad the first sector to 4096 bytes. - let mut v = vec![]; - v.resize(4096 - 4 - 4 - signature_u8.len(), 0); - dest_file.write_all(&v)?; - - // Fill the remainder of the source data - - if defile { - println!("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check."); - source[16778] ^= 0x1 // flip one bit at some random offset - } - - dest_file.write_all(&source)?; - - Ok(()) -} - -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> { let matches = App::new("sign-image") .version(crate_version!()) @@ -160,10 +81,12 @@ fn main() -> Result<(), Box> { .get_matches(); let minver = if let Some(minver_str) = matches.value_of("min-xous-ver") { - Some( - SemVer::from_str(minver_str) - .map_err(|_| Error::new(ErrorKind::InvalidInput, "Minimum version semver format incorrect"))? - ) + Some(SemVer::from_str(minver_str).map_err(|_| { + Error::new( + ErrorKind::InvalidInput, + "Minimum version semver format incorrect", + ) + })?) } else { None }; @@ -183,7 +106,7 @@ fn main() -> Result<(), Box> { Err("invalid loader private key type")?; } println!("Signing loader"); - image_sign( + sign_file( &loader_image, &loader_output, &loader_pkey, @@ -206,7 +129,7 @@ fn main() -> Result<(), Box> { Err("invalid kernel private key type")?; } println!("Signing kernel"); - image_sign( + sign_file( &kernel_image, &kernel_output, &kernel_pkey, diff --git a/tools/src/elf.rs b/tools/src/elf.rs index 8c4a88b53..b9dd01320 100644 --- a/tools/src/elf.rs +++ b/tools/src/elf.rs @@ -56,7 +56,11 @@ impl fmt::Display for MiniElfSection { write!( f, "Section {:13} {:6} bytes loading into {:08x}..{:08x} flags: {:?}", - self.name, self.size, self.virt, self.virt + self.size, self.flags + self.name, + self.size, + self.virt, + self.virt + self.size, + self.flags ) } } @@ -133,6 +137,10 @@ pub fn read_program>(filename: P) -> Result Result { let elf = ElfFile::new(&b).map_err(|x| ElfReadError::ParseElfError(x))?; let entry_point = elf.header.pt2.entry_point() as u32; let mut program_data = Cursor::new(Vec::new()); @@ -276,6 +284,10 @@ pub fn read_minielf>(filename: P) -> Result Result { let elf = ElfFile::new(&b).map_err(|x| ElfReadError::ParseElfError(x))?; let entry_point = elf.header.pt2.entry_point() as u32; let mut program_data = Cursor::new(Vec::new()); diff --git a/tools/src/lib.rs b/tools/src/lib.rs index 8196bd896..87f18cc2b 100644 --- a/tools/src/lib.rs +++ b/tools/src/lib.rs @@ -3,5 +3,6 @@ extern crate log; #[macro_use] pub mod xous_arguments; pub mod elf; +pub mod sign_image; pub mod tags; pub mod utils; diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs new file mode 100644 index 000000000..25107ef42 --- /dev/null +++ b/tools/src/sign_image.rs @@ -0,0 +1,110 @@ +use std::io::{Error, ErrorKind, Read, Write}; +use std::path::Path; + +use ring::signature::Ed25519KeyPair; + +const LOADER_VERSION: u32 = 1; + +use xous_semver::SemVer; + +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 semver_to_u8() -> Result<[u8; 16], &'static str> { + let a = SemVer::from_git()?; + Ok(a.into()) +} + +pub fn sign_image( + source: &[u8], + private_key: &pem::Pem, + defile: bool, + minver: &Option, + semver: Option<[u8; 16]>, +) -> Result, Box> { + let mut source = source.to_owned(); + let mut dest_file = vec![]; + + // Append version information to the binary. Appending it here means it is part + // of the signed bundle. + let minver_bytes = if let Some(mv) = minver { + mv.into() + } else { + [0u8; 16] + }; + let semver: [u8; 16] = semver + .ok_or_else(|| semver_to_u8()) + .map_err(|_| Error::new(ErrorKind::Other, "error parsing current Git rev"))?; + // extra data appended here needs to be reflected in two places in Xous: + // 1. root-keys/src/implementation.rs @ sign-loader() + // 2. graphics-server/src/main.rs @ Some(Opcode::BulkReadfonts) + // This is because memory ownership is split between two crates for performance reasons: + // the direct memory page of fonts belongs to the graphics server, to avoid having to send + // a message on every font lookup. However, the keys reside in root-keys, so therefore, + // a bulk read operation has to shuttle font data back to the root-keys crate. Of course, + // the appended metadata is in the font region, so, this data has to be shuttled back. + // The graphics server is also entirely naive to how much cryptographic data is in the font + // region, and I think it's probably better for it to stay that way. + source.append(&mut minver_bytes.to_vec()); + source.append(&mut semver.to_vec()); + for &b in LOADER_VERSION.to_le_bytes().iter() { + source.push(b); + } + for &b in (source.len() as u32).to_le_bytes().iter() { + source.push(b); + } + + // NOTE NOTE NOTE + // can't find a good ASN.1 ED25519 key decoder, just relying on the fact that the last + // 32 bytes are "always" the private key. always? the private key? + let signing_key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&private_key.contents) + .map_err(|e| format!("{}", e))?; + let signature = signing_key.sign(&source); + + dest_file.write_all(&LOADER_VERSION.to_le_bytes())?; + dest_file.write_all(&(source.len() as u32).to_le_bytes())?; + + // Write the signature data + let signature_u8 = &signature.as_ref(); + dest_file.write_all(signature_u8)?; + + // Pad the first sector to 4096 bytes. + let mut v = vec![]; + v.resize(4096 - 4 - 4 - signature_u8.len(), 0); + dest_file.write_all(&v)?; + + // Fill the remainder of the source data + + if defile { + println!("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check."); + source[16778] ^= 0x1 // flip one bit at some random offset + } + + Ok(dest_file) +} + +pub fn sign_file( + input: &S, + output: &T, + private_key: &pem::Pem, + defile: bool, + minver: &Option, +) -> Result<(), Box> +where + S: AsRef, + T: AsRef, +{ + let mut source = vec![]; + let mut source_file = std::fs::File::open(input)?; + let mut dest_file = std::fs::File::create(output)?; + source_file.read_to_end(&mut source)?; + + let result = sign_image(&source, private_key, defile, minver, None)?; + dest_file.write_all(&result)?; + Ok(()) +}