From d9a27ea3d7ad40eaa70dfa986f26f1e200cdf99f Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 18:11:22 +0800 Subject: [PATCH 01/22] remove unnecessary print --- kernel/src/syscall.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/kernel/src/syscall.rs b/kernel/src/syscall.rs index e88ce936f..557023f68 100644 --- a/kernel/src/syscall.rs +++ b/kernel/src/syscall.rs @@ -732,7 +732,6 @@ pub fn handle_inner(pid: PID, tid: TID, in_irq: bool, call: SysCall) -> SysCallR }) } SysCall::UnmapMemory(range) => { - println!("UnmapMemory: {:x?}", range); #[cfg(feature = "swap")] // this call may diverge if it generates an advisory to the swapper let result = crate::swap::Swap::with_mut(|s| s.unmap(range)); From cc75520bc2e7aba62d46943d71cf702caeb0c4e2 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 18:11:35 +0800 Subject: [PATCH 02/22] fix missing commands in non-swap path --- kernel/src/arch/riscv/mem.rs | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/kernel/src/arch/riscv/mem.rs b/kernel/src/arch/riscv/mem.rs index aed182ed5..ddffe048b 100644 --- a/kernel/src/arch/riscv/mem.rs +++ b/kernel/src/arch/riscv/mem.rs @@ -823,8 +823,18 @@ pub fn return_page_inner( panic!("page wasn't shared in destination space"); } + #[cfg(feature = "swap")] // Clear the `SHARED` bit, and set the `VALID` bit. - unsafe { dest_entry.write_volatile(dest_entry_value & !(MMUFlags::S).bits() | MMUFlags::VALID.bits()) }; + unsafe { + dest_entry.write_volatile(dest_entry_value & !(MMUFlags::S).bits() | MMUFlags::VALID.bits()) + }; + #[cfg(not(feature = "swap"))] + // Clear the `SHARED` and `PREVIOUSLY-WRITABLE` bits, and set the `VALID` bit. + unsafe { + dest_entry + .write_volatile(dest_entry_value & !(MMUFlags::S | MMUFlags::P).bits() | MMUFlags::VALID.bits()) + }; + unsafe { flush_mmu() }; // Swap back to our previous address space @@ -928,9 +938,14 @@ pub fn ensure_page_exists_inner(address: usize) -> Result Date: Fri, 5 Apr 2024 16:12:11 +0800 Subject: [PATCH 03/22] remove debug-print from loader this shouldn't be here in main. --- loader/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/loader/Cargo.toml b/loader/Cargo.toml index e25d8eab7..6067bd218 100644 --- a/loader/Cargo.toml +++ b/loader/Cargo.toml @@ -78,4 +78,4 @@ simulation-only = [] board-bringup = [] #default = ["debug-print"] resume = [] # suspend/resume pathway code -default = ["debug-print", "board-bringup"] +default = [] From a732eed679b1a19eadc5b85f79fe12b3e8d54f23 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 15:27:24 +0800 Subject: [PATCH 04/22] make kernel aware of the IniS type this should now introduce a crash in the kernel when an IniS process is in the image set; previously we didn't try to schedule and run them. --- kernel/src/services.rs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/kernel/src/services.rs b/kernel/src/services.rs index 09f25d3fe..6d1e96ce0 100644 --- a/kernel/src/services.rs +++ b/kernel/src/services.rs @@ -354,7 +354,10 @@ impl SystemServices { let init_offsets = { let mut init_count = 1; for arg in args.iter() { - if arg.name == u32::from_le_bytes(*b"IniE") || arg.name == u32::from_le_bytes(*b"IniF") { + if arg.name == u32::from_le_bytes(*b"IniE") + || arg.name == u32::from_le_bytes(*b"IniF") + || arg.name == u32::from_le_bytes(*b"IniS") + { init_count += 1; } } @@ -367,7 +370,10 @@ impl SystemServices { let mut arg_iter = args.iter().peekable(); loop { if let Some(arg) = arg_iter.peek() { - if arg.name == u32::from_le_bytes(*b"IniE") || arg.name == u32::from_le_bytes(*b"IniF") { + if arg.name == u32::from_le_bytes(*b"IniE") + || arg.name == u32::from_le_bytes(*b"IniF") + || arg.name == u32::from_le_bytes(*b"IniS") + { break; } } else { @@ -400,7 +406,7 @@ impl SystemServices { } else { // This code makes the following assumption: // - Arguments are in the same order as processes - // - All processes take the form of IniE/IniF such that the flags are in the last word + // - All processes take the form of IniE/IniF/IniS such that the flags are in the last word // - Process #1 is the kernel // Any changes to this will break this code! let mut eh_frame = 0; From cdbd5dc0f41b2ad054870cbe6c5d4c5d43dcf90f Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 15:28:04 +0800 Subject: [PATCH 05/22] add structure to differentiate image type we now have three image types: inie, inif, inis; migrate away from a simple "xip" flag to something that can differentiate between all three options. --- loader/src/main.rs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/loader/src/main.rs b/loader/src/main.rs index 71f71035b..d0c60aa3f 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -59,6 +59,16 @@ pub struct PageTable { entries: [usize; PAGE_SIZE / WORD_SIZE], } +#[derive(Copy, Clone, Eq, PartialEq)] +pub enum IniType { + // RAM + IniE, + // XIP + IniF, + // Swap + IniS, +} + /// Entrypoint /// This makes the program self-sufficient by setting up memory page assignment /// and copying the arguments to RAM. @@ -344,7 +354,10 @@ pub fn read_initial_config(cfg: &mut BootConfig) { assert!(!kernel_seen, "kernel appears twice"); assert!(tag.size as usize == mem::size_of::(), "invalid XKrn size"); kernel_seen = true; - } else if tag.name == u32::from_le_bytes(*b"IniE") || tag.name == u32::from_le_bytes(*b"IniF") { + } else if tag.name == u32::from_le_bytes(*b"IniE") + || tag.name == u32::from_le_bytes(*b"IniF") + || tag.name == u32::from_le_bytes(*b"IniS") + { assert!(tag.size >= 4, "invalid Init size"); init_seen = true; cfg.init_process_count += 1; @@ -467,6 +480,11 @@ fn check_load(cfg: &mut BootConfig) { println!("\n\nChecking IniF region"); inif.check(cfg, inif.load_offset as usize, pid, true); pid += 1; + } else if tag.name == u32::from_le_bytes(*b"IniS") { + let inis = MiniElf::new(&tag); + println!("\n\nChecking IniS region"); + inis.check(cfg, inis.load_offset as usize, pid, true); + pid += 1; } } } From c37349778ed24d9d88b5aa2e823ab3813fcfb26d Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 15:28:53 +0800 Subject: [PATCH 06/22] put todo! placeholders for minielf handling of inis --- loader/src/minielf.rs | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/loader/src/minielf.rs b/loader/src/minielf.rs index 4defe972f..50f8847aa 100644 --- a/loader/src/minielf.rs +++ b/loader/src/minielf.rs @@ -93,7 +93,7 @@ impl MiniElf { load_offset: usize, pid: XousPid, params: &[u8], - xip: bool, + ini_type: IniType, ) -> usize { println!("Mapping PID {} starting at offset {:08x}", pid, load_offset); let mut allocated_bytes = 0; @@ -104,16 +104,20 @@ impl MiniElf { let image_phys_base = allocator.base_addr as usize + self.load_offset as usize; // It is a requirement that the image generator lay out the artifacts on disk such that // the page offsets line up for XIP sections. This assert confirms this necessary pre-condition. - if xip { - assert!( - (image_phys_base & (PAGE_SIZE - 1)) == self.sections[0].virt as usize & (PAGE_SIZE - 1), - "Image generator did not align load offsets to page offsets!" - ); + match ini_type { + IniType::IniF => { + assert!( + (image_phys_base & (PAGE_SIZE - 1)) == self.sections[0].virt as usize & (PAGE_SIZE - 1), + "Image generator did not align load offsets to page offsets!" + ); + } + _ => { + println!( + "flash_map_offset: {:x} / base_addr {:x} load_offset {:x}", + image_phys_base as usize, allocator.base_addr as usize, self.load_offset as usize + ); + } } - println!( - "flash_map_offset: {:x} / base_addr {:x} load_offset {:x}", - image_phys_base as usize, allocator.base_addr as usize, self.load_offset as usize - ); // The load offset is the end of this process. Shift it down by one page // so we get the start of the first page. @@ -231,7 +235,7 @@ impl MiniElf { panic!("init section addresses are not strictly increasing"); } - if copy_to_ram || !xip { + if copy_to_ram || ini_type == IniType::IniE { let mut this_page = section.virt as usize & !(PAGE_SIZE - 1); let mut bytes_to_copy = section.len(); @@ -350,6 +354,8 @@ impl MiniElf { } // --- map FLASH pages to virtual memory --- + // TODO: handle mapping of swap-located pages to virtual memory + todo!("Handle swap-located pages mapping into virtual memory"); while pages_to_map > 0 { let map_phys_addr = (image_phys_base + section_map_phys_offset) & !(PAGE_SIZE - 1); allocator.map_page(tt, map_phys_addr, virt_page, flag_defaults, pid as XousPid); From c354b75d97b37a74e5dc90f6ee8bdfc4a42ab76e Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 15:29:23 +0800 Subject: [PATCH 07/22] put placeholders to handle inis in phase1 --- loader/src/phase1.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/loader/src/phase1.rs b/loader/src/phase1.rs index 00b428af3..d19a60a27 100644 --- a/loader/src/phase1.rs +++ b/loader/src/phase1.rs @@ -147,6 +147,7 @@ pub fn copy_args(cfg: &mut BootConfig) { enum TagType { IniE, IniF, + IniS, XKrn, Other, } @@ -156,6 +157,8 @@ impl From for TagType { TagType::IniE } else if code == u32::from_le_bytes(*b"IniF") { TagType::IniF + } else if code == u32::from_le_bytes(*b"IniS") { + TagType::IniS } else if code == u32::from_le_bytes(*b"XKrn") { TagType::XKrn } else { @@ -169,6 +172,7 @@ impl TagType { match self { TagType::IniE => "IniE", TagType::IniF => "IniF", + TagType::IniS => "IniS", TagType::XKrn => "XKrn", TagType::Other => "Other", } @@ -314,6 +318,17 @@ fn copy_processes(cfg: &mut BootConfig) { } println!("Done with sections"); } + TagType::IniS => { + // IniS does not necessarily exist in linear memory space. + + // TODO: access IniS image and figure out what regions are "write" and allocate/copy + // those into RAM. We do this because there isn't a 1:1 mapping of these to the + // images on disk which creates a problem for the swapper. + + // Then, for regions that *are* aligned, allocate them into the swapper's + // memory space, and copy the data into swap. + todo!("implement inis handling"); + } TagType::XKrn => { let prog = unsafe { &*(tag.data.as_ptr() as *const ProgramDescription) }; From 8bae95ef727072890ee39a8139cdc8371c07a40e Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 1 Apr 2024 15:29:38 +0800 Subject: [PATCH 08/22] put placeholders for inis handling, phase 2 --- loader/src/phase2.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/loader/src/phase2.rs b/loader/src/phase2.rs index 83f7808bd..f5f655768 100644 --- a/loader/src/phase2.rs +++ b/loader/src/phase2.rs @@ -80,17 +80,24 @@ pub fn phase_2(cfg: &mut BootConfig, fs_prehash: &[u8; 64]) { if tag.name == u32::from_le_bytes(*b"IniE") { let inie = MiniElf::new(&tag); println!("\n\nCopying IniE program into memory"); - let allocated = inie.load(cfg, process_offset, pid, &env, false); + let allocated = inie.load(cfg, process_offset, pid, &env, IniType::IniE); println!("IniE Allocated {:x}", allocated); process_offset -= allocated; pid += 1; } else if tag.name == u32::from_le_bytes(*b"IniF") { let inif = MiniElf::new(&tag); println!("\n\nMapping IniF program into memory"); - let allocated = inif.load(cfg, process_offset, pid, &env, true); + let allocated = inif.load(cfg, process_offset, pid, &env, IniType::IniF); println!("IniF Allocated {:x}", allocated); process_offset -= allocated; pid += 1; + } else if tag.name == u32::from_le_bytes(*b"IniS") { + let inis = MiniElf::new(&tag); + println!("\n\nMapping IniS program into memory"); + let allocated = inis.load(cfg, process_offset, pid, &env, IniType::IniS); + println!("IniS Allocated {:x}", allocated); + process_offset -= allocated; + pid += 1; } else if tag.name == u32::from_le_bytes(*b"XKrn") { println!("\n\nCopying kernel into memory"); let xkrn = unsafe { &*(tag.data.as_ptr() as *const ProgramDescription) }; From d8f3fc96d6e1070c328b5c65f45bd7cf05ed5c04 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:32:19 +0800 Subject: [PATCH 09/22] specify swap file name --- xtask/src/builder.rs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/xtask/src/builder.rs b/xtask/src/builder.rs index 98ddfd5a9..52db53892 100644 --- a/xtask/src/builder.rs +++ b/xtask/src/builder.rs @@ -971,9 +971,16 @@ impl Builder { } else { String::new() }; + let mut swap_file = PathBuf::new(); if self.swap.is_some() { args.push("--swap"); args.push(&swap_spec); + swap_file.push("target"); + swap_file.push(self.target.as_ref().expect("target")); + swap_file.push(stream); + swap_file.push("swap.img"); + args.push("--swap-name"); + args.push(swap_file.to_str().unwrap()) } if memory_spec.len() == 1 { From 0aecb4c1d3a49a75a2f50aeb2215e41a4f092890 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:32:45 +0800 Subject: [PATCH 10/22] add the swap writer This will take the buffer that is generated from a xous argument and encrypts it to the prescribed "detached swap" format. --- tools/src/swap_writer.rs | 103 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 tools/src/swap_writer.rs diff --git a/tools/src/swap_writer.rs b/tools/src/swap_writer.rs new file mode 100644 index 000000000..91b448a6d --- /dev/null +++ b/tools/src/swap_writer.rs @@ -0,0 +1,103 @@ +use std::convert::TryInto; +use std::io::{Cursor, Result, Seek, SeekFrom, Write}; + +use aes_gcm_siv::{ + aead::{Aead, KeyInit, Payload}, + Aes256GcmSiv, Nonce, +}; +use rand::Rng; + +const SWAP_VERSION: u32 = 0x01_01_0000; + +pub struct SwapWriter { + pub buffer: Cursor>, +} + +struct SwapHeader { + aad: Vec, + partial_nonce: u64, + /// offset, starting from the top of payload data (so, +0x1000 to get absolute offset after the header) + mac_offset: usize, +} +impl SwapHeader { + pub fn new(swap_len: usize) -> Self { + let mut rng = rand::thread_rng(); + SwapHeader { + aad: "swap".as_bytes().to_vec(), + partial_nonce: rng.gen(), + mac_offset: ((swap_len + 0xFFF) / 0x1000) * 0x1000, + } + } + + /// Returns exactly a page of data with the header format serialized + 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 AAD + 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 + + // serialize the MAC data offset + data.write(&(self.mac_offset as u32).to_le_bytes())?; // LE because this is a size field + + output[..data.position() as usize].copy_from_slice(&data.into_inner()); + + Ok(output) + } +} + +impl SwapWriter { + pub fn new() -> Self { SwapWriter { buffer: Cursor::new(Vec::new()) } } + + pub fn encrypt_to(&mut self, mut f: T) -> Result + where + T: Write + Seek, + { + let header = SwapHeader::new(self.buffer.get_ref().len()); + let mut macs = Vec::::new(); + + f.write(&header.serialize()?)?; + + // 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 + // secret key generated in the device can provide security. + let zero_key = [0u8; 32]; + let cipher = Aes256GcmSiv::new(&zero_key.try_into().unwrap()); + let buf = self.buffer.get_ref(); + for (offset, block) in buf.chunks(0x1000).enumerate() { + let padded_block = if block.len() != 0x1000 { + [block, &vec![0u8; 0x1000 - block.len()]].concat() + } else { + block.to_owned() + }; + let mut nonce_vec = Vec::new(); + // use BE encoding because nonce is cryptographic matter + nonce_vec.extend_from_slice(&(offset as u32).to_be_bytes()); + nonce_vec.extend_from_slice(&header.partial_nonce.to_be_bytes()); + let nonce = Nonce::from_slice(&nonce_vec); + let enc = cipher + .encrypt(nonce, Payload { aad: &header.aad, msg: &padded_block }) + .expect("couldn't encrypt block"); + assert!(enc.len() == 0x1010); + f.write(&enc[..0x1000])?; + macs.extend_from_slice(&enc[0x1000..]); + } + + f.write(&macs) + } +} + +impl Write for SwapWriter { + fn write(&mut self, buf: &[u8]) -> std::io::Result { self.buffer.write(buf) } + + fn flush(&mut self) -> std::io::Result<()> { self.buffer.flush() } +} + +impl Seek for SwapWriter { + fn seek(&mut self, pos: SeekFrom) -> std::io::Result { self.buffer.seek(pos) } +} From eb1cb4a2530c26d2185ce5e0493687f22eea87fb Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:33:29 +0800 Subject: [PATCH 11/22] add the swap_writer module to the library --- tools/src/lib.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/src/lib.rs b/tools/src/lib.rs index 87f18cc2b..6a2efd11f 100644 --- a/tools/src/lib.rs +++ b/tools/src/lib.rs @@ -4,5 +4,6 @@ extern crate log; pub mod xous_arguments; pub mod elf; pub mod sign_image; +pub mod swap_writer; pub mod tags; pub mod utils; From a662f5edcb5b5b58d65f5b33a5054af7459a3873 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:34:00 +0800 Subject: [PATCH 12/22] rework create-image to put inis objects into the detached swap region --- tools/src/bin/create-image.rs | 52 ++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/tools/src/bin/create-image.rs b/tools/src/bin/create-image.rs index 631942e4b..52f5a3cf8 100644 --- a/tools/src/bin/create-image.rs +++ b/tools/src/bin/create-image.rs @@ -8,6 +8,7 @@ use std::fs::File; use clap::{App, Arg}; use tools::elf::{read_minielf, read_program}; +use tools::swap_writer::SwapWriter; use tools::tags::bflg::Bflg; use tools::tags::inie::IniE; use tools::tags::inif::IniF; @@ -166,6 +167,13 @@ fn main() { .value_name("OFFSET:SIZE") .help("Swap offset and size, in the form of [offset]:[size]; note: offset and size have platform-dependent interpretations") ) + .arg( + Arg::with_name("swap-name") + .long("swap-name") + .takes_value(true) + .value_name("OUTPUT") + .help("Output file to store swap image data") + ) .arg( Arg::with_name("debug") .short("d") @@ -342,6 +350,7 @@ fn main() { } let mut args = XousArguments::new(ram_config.offset, ram_config.size, ram_config.name); + let mut swap_args: Option = None; if !ram_config.regions.is_empty() { if let Some(s) = swap { @@ -360,6 +369,7 @@ fn main() { } // Note that other configurations don't split RAM, since the swap is provisioned directly // in hardware, and thus, no post-processing is required. + swap_args = Some(XousArguments::new(s.offset, s.size, s.name)); args.add(s); args.add(ram_config.regions); @@ -412,19 +422,23 @@ fn main() { } if let Some(init_paths) = matches.values_of("inis") { - for init_path in init_paths { - let program_name = std::path::Path::new(init_path); - process_names.set( - pid, - program_name - .file_stem() - .expect("program had no name") - .to_str() - .expect("program name is not valid utf-8"), - ); - pid += 1; - let init = read_minielf(init_path).expect("couldn't parse init file"); - args.add(IniS::new(init.entry_point, init.sections, init.program, init.alignment_offset)); + if let Some(ref mut sargs) = swap_args { + for init_path in init_paths { + let program_name = std::path::Path::new(init_path); + process_names.set( + pid, + program_name + .file_stem() + .expect("program had no name") + .to_str() + .expect("program name is not valid utf-8"), + ); + pid += 1; + let init = read_minielf(init_path).expect("couldn't parse init file"); + sargs.add(IniS::new(init.entry_point, init.sections, init.program, init.alignment_offset)); + } + } else { + println!("Warning: inis regions specified, but no swap region specified. Ignoring inis regions!"); } } @@ -452,6 +466,18 @@ fn main() { println!("Arguments: {}", args); + if let Some(mut sargs) = swap_args { + let mut swap_buffer = SwapWriter::new(); + sargs.write(&mut swap_buffer).expect("Couldn't write out swap args"); + + 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"); + + println!("Swap arguments: {}", sargs); + println!("Swap data created in file {}", swap_filename); + } println!("Runtime will require {} bytes to track memory allocations", ram_config.memory_required); if let Some(s) = swap { println!("Runtime will also require {} bytes to track swap", s.size / 4096); From 6dbea466fbc0f2982bc2aaa48400ab43d4fff1de Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:34:23 +0800 Subject: [PATCH 13/22] add cryptographic libraries to the image creator manifest --- tools/Cargo.toml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/Cargo.toml b/tools/Cargo.toml index 8600cf2b3..3c293dc22 100644 --- a/tools/Cargo.toml +++ b/tools/Cargo.toml @@ -24,6 +24,9 @@ ed25519-dalek = { version = "2.1.0", features = ["digest"] } sha2 = { version = "0.10.8" } pkcs8 = { version = "0.8.0", features = ["pem"] } base64 = "0.20.0" +rand = "0.8.5" +aead = { version = "0.5.2", features = ["alloc"] } +aes-gcm-siv = "0.11.1" [[bin]] name = "copy-object" From b72a949930460053e70e41821e0be3c61ac014df Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:34:45 +0800 Subject: [PATCH 14/22] absorb new dependencies --- Cargo.lock | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index ff5a885e6..bd18acde1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1063,6 +1063,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" dependencies = [ "generic-array", + "rand_core 0.6.4", "typenum", ] @@ -5132,6 +5133,8 @@ dependencies = [ name = "tools" version = "0.1.0" dependencies = [ + "aead", + "aes-gcm-siv", "base64 0.20.0", "bitflags 1.3.2", "clap 2.34.0", @@ -5142,6 +5145,7 @@ dependencies = [ "log", "pem", "pkcs8 0.8.0", + "rand 0.8.5", "ring", "sha2 0.10.8", "svd2utra 0.1.22", From bac8e4ff4d7cf67d603e76a3a2400e05558f57de Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:45:02 +0800 Subject: [PATCH 15/22] chore: add a comment --- tools/src/swap_writer.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/src/swap_writer.rs b/tools/src/swap_writer.rs index 91b448a6d..caa4cf45a 100644 --- a/tools/src/swap_writer.rs +++ b/tools/src/swap_writer.rs @@ -54,6 +54,8 @@ impl SwapHeader { impl SwapWriter { pub fn new() -> Self { SwapWriter { buffer: Cursor::new(Vec::new()) } } + /// 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 where T: Write + Seek, From 798566e6d287f6b752b9de599d47ba1cdbd7b3a6 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 18:45:16 +0800 Subject: [PATCH 16/22] add storage for the swap encryption key This is set to 0 in the image creator, but the keying ceremony should set this to something more secure after the device has been initialized (and likewise, re-encrypt the swap region to match the new, secure key). --- tools/src/tags/swap.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/tools/src/tags/swap.rs b/tools/src/tags/swap.rs index e734858e0..83a6b101b 100644 --- a/tools/src/tags/swap.rs +++ b/tools/src/tags/swap.rs @@ -14,6 +14,10 @@ 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], + /// Unused _padding: u32, } @@ -21,28 +25,36 @@ 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(()) } } impl Swap { pub fn new(offset: XousSize, size: XousSize) -> Self { - Swap { offset, size, name: u32::from_le_bytes(*b"Swap") as XousArgumentCode, _padding: 0 } + Swap { + offset, + size, + name: u32::from_le_bytes(*b"Swap") as XousArgumentCode, + key: [0u8; 32], + _padding: 0, + } } } impl XousArgument for Swap { fn code(&self) -> XousArgumentCode { self.name } - fn length(&self) -> XousSize { 16 as XousSize } + fn length(&self) -> XousSize { (16 + 32) 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(&0u32.to_le_bytes())?; - written += 4 * 4; + written += 4 * 4 + 32; Ok(written) } } From 98d31c52740cba4cec7b17db20e01bcbf195a225 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 19:23:07 +0800 Subject: [PATCH 17/22] fix ram offsets for precursor swap config --- xtask/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/xtask/src/main.rs b/xtask/src/main.rs index c1d93ce3c..d37a37fbd 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -244,7 +244,7 @@ fn main() -> Result<(), Box> { } Some("renode-swap") => { if !builder.is_swap_set() { - builder.set_swap(0x4040_0000, 8 * 1024 * 1024); + builder.set_swap(0x4080_0000, 8 * 1024 * 1024); } builder.target_renode(); // It is important that this is the first service added, because the swapper *must* be in PID 2 From 78cd15e590fbdbc79d4a660a21459f19090f83eb Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 19:23:26 +0800 Subject: [PATCH 18/22] the image creator is sensitive to the target for swap configs --- xtask/src/builder.rs | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/xtask/src/builder.rs b/xtask/src/builder.rs index 52db53892..848bcb541 100644 --- a/xtask/src/builder.rs +++ b/xtask/src/builder.rs @@ -933,7 +933,18 @@ impl Builder { memory_spec: Vec, ) -> Result { let stream = self.stream.as_str(); - let mut args = vec!["run", "--package", "tools", "--bin", "create-image", "--"]; + let mut args = vec!["run", "--package", "tools", "--bin", "create-image"]; + args.push("--features"); + if self.utra_target.contains("renode") { + args.push("renode"); + } else if self.utra_target.contains("precursor") { + args.push("precursor"); + } else if self.utra_target.contains("atsama5d2") { + args.push("atsama5d2"); + } else if self.utra_target.contains("cramium-soc") { + args.push("cramium-soc") + } + args.push("--"); let mut output_file = PathBuf::new(); output_file.push("target"); From b06dd72e7d0789d6b94170f8cfaaebbd2d3e6706 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 19:23:49 +0800 Subject: [PATCH 19/22] make argument start/offset visible so we can patch it up for the swap testing on precursor --- tools/src/xous_arguments.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/src/xous_arguments.rs b/tools/src/xous_arguments.rs index b2cac387c..a2ef8145c 100644 --- a/tools/src/xous_arguments.rs +++ b/tools/src/xous_arguments.rs @@ -40,8 +40,8 @@ pub trait XousArgument: fmt::Display { } pub struct XousArguments { - ram_start: XousSize, - ram_length: XousSize, + pub ram_start: XousSize, + pub ram_length: XousSize, ram_name: u32, pub arguments: Vec>, } From 8c219f8fb1c369d6d92fdb62c44b1ea0c2207793 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 19:24:17 +0800 Subject: [PATCH 20/22] patching routine for memory regions. ended up not being used because main memory is a special case :P --- tools/src/tags/memory.rs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tools/src/tags/memory.rs b/tools/src/tags/memory.rs index eedebc059..61754fd75 100644 --- a/tools/src/tags/memory.rs +++ b/tools/src/tags/memory.rs @@ -84,6 +84,15 @@ impl MemoryRegions { pub fn len(&self) -> usize { self.regions.len() } pub fn is_empty(&self) -> bool { self.regions.is_empty() } + + #[allow(dead_code)] + pub fn patch(&mut self, region_name: &str, new_spec: MemoryRegion) { + if let Some(index) = self.regions.iter().position(|&x| x.name == MemoryRegion::make_name(region_name)) + { + self.regions.remove(index); + self.regions.insert(index, new_spec); + } + } } impl XousArgument for MemoryRegions { From 50fa69a0621be55867305a8ac46421a892d4ac5c Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 19:24:38 +0800 Subject: [PATCH 21/22] fix main memory patching for swap config on precursor --- tools/src/bin/create-image.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/src/bin/create-image.rs b/tools/src/bin/create-image.rs index 52f5a3cf8..5cb254611 100644 --- a/tools/src/bin/create-image.rs +++ b/tools/src/bin/create-image.rs @@ -366,6 +366,8 @@ fn main() { if s.offset < ram_config.offset + ram_config.size { ram_config.size = s.offset - ram_config.offset; } + args.ram_start = ram_config.offset; + args.ram_length = ram_config.size; } // Note that other configurations don't split RAM, since the swap is provisioned directly // in hardware, and thus, no post-processing is required. From 8a7010a6c5f155af7f25eca82e4fe7a6861cbc43 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 4 Apr 2024 22:16:23 +0800 Subject: [PATCH 22/22] add renode configs for swap --- emulation/betrusted-swap.resc | 149 ++++++++++++++++++++++++++++++++++ emulation/xous-swap.resc | 10 +++ 2 files changed, 159 insertions(+) create mode 100644 emulation/betrusted-swap.resc create mode 100644 emulation/xous-swap.resc diff --git a/emulation/betrusted-swap.resc b/emulation/betrusted-swap.resc new file mode 100644 index 000000000..455fd8e26 --- /dev/null +++ b/emulation/betrusted-swap.resc @@ -0,0 +1,149 @@ +# Boot Renode Script (boot.resc) + + +# Add this script's path to the global path, so +# we can include files relative to ourselves. +path add $ORIGIN + +using sysbus + +# Add peripherals that are defined in C#. You must restart Renode +# if you modify these files. +i @peripherals/ABRTCMC.cs +i @peripherals/BetrustedEcI2C.cs +i @peripherals/BetrustedSocI2C.cs +i @peripherals/BetrustedSpinor.cs +i @peripherals/BetrustedWatchdog.cs +i @peripherals/BQ24157.cs +i @peripherals/BQ27421.cs +i @peripherals/BtEvents.cs +i @peripherals/ComConnector.cs +EnsureTypeIsLoaded "Antmicro.Renode.Peripherals.SPI.Betrusted.IComPeripheral" +EnsureTypeIsLoaded "Antmicro.Renode.Peripherals.SPI.Betrusted.IComController" +i @peripherals/ComEc.cs +i @peripherals/ComSoC.cs +i @peripherals/EcPower.cs +i @peripherals/EcWifi.cs +i @peripherals/engine.cs +i @peripherals/Jtag.cs +i @peripherals/keyboard.cs +i @peripherals/keyrom.cs +i @peripherals/LiteX_Timer_32.cs +i @peripherals/LM3509.cs +i @peripherals/LSM6DS3.cs +i @peripherals/memlcd.cs +i @peripherals/MXIC_MX66UM1G45G.cs +i @peripherals/sha512.cs +i @peripherals/spinor_soft_int.cs +i @peripherals/ticktimer.cs +i @peripherals/trng_kernel.cs +i @peripherals/trng_server.cs +i @peripherals/TLV320AIC3100.cs +i @peripherals/TUSB320LAI.cs +i @peripherals/WF200.cs +i @peripherals/wfi.cs + +EnsureTypeIsLoaded "Antmicro.Renode.Peripherals.CPU.VexRiscv" +i @peripherals/vexriscv-aes.cs + +EnsureTypeIsLoaded "Antmicro.Renode.Peripherals.Timers.Betrusted.TickTimer" +i @peripherals/susres.cs + +# Create the COM SPI bus +emulation CreateComConnector "com" + +############### Define the Betrusted SoC ############### +mach create "SoC" +machine LoadPlatformDescription @soc/betrusted-soc.repl + +machine StartGdbServer 3333 true +showAnalyzer uart +showAnalyzer console +showAnalyzer app_uart +showAnalyzer memlcd + +# sysbus LogPeripheralAccess engine true +# sysbus LogPeripheralAccess sha512 true +# sysbus LogPeripheralAccess i2c true +# sysbus LogPeripheralAccess trng_kernel true + +sysbus Tag <0xB0000000, 0xB0006000> "Framebuffer" + +# logLevel -1 keyboard +# logLevel -1 ticktimer +# logLevel -1 engine +# logLevel -1 i2c +# logLevel -1 i2c.abracom_rtc +# logLevel -1 sha512 +# logLevel -1 sysbus.spinor.flash +# sysbus LogPeripheralAccess spinor true + +# Silence GPIO +sysbus SilenceRange <0xf0003000, 0xF0003FFF> +# Silence POWER +sysbus SilenceRange <0xF0014000 100> + +# Attach the flash backing to the filesystem +sysbus.spinor.flash BackingFile $ORIGIN/../tools/pddb-images/renode.bin + +# Load the SPI flash into RAM +sysbus LoadBinary @../utralib/renode/soc_csr.bin 0x20000000 + +# Connect the SoC to the SPI bus +connector Connect sysbus.com com + +# The macro `reset` gets called implicitly when running `machine Reset` +macro reset +""" + #sysbus LoadBinary @flash-formatted.bin 0x20000000 + sysbus LoadBinary @../target/riscv32imac-unknown-xous-elf/release/loader.bin 0x20500000 + sysbus LoadBinary @../target/riscv32imac-unknown-xous-elf/release/xous.img 0x20980000 + sysbus LoadBinary @../target/riscv32imac-unknown-xous-elf/release/swap.img 0x21200000 + # Set $a0 to point at the args binary + cpu SetRegisterUnsafe 10 0x20980000 + cpu PC 0x20501000 +""" + +# Connect the serial port to an Ethernet port +emulation CreateServerSocketTerminal 8888 "kernel" False +connector Connect sysbus.uart kernel + +# Connect the `app_uart` port -- which is the port on which +# the Xous gdbserver runs -- to TCP port 3456, to allow for +# application-aware debugging +emulation CreateServerSocketTerminal 3456 "gdb" False +connector Connect sysbus.app_uart gdb + +runMacro $reset + +mach clear + +############### Define the Betrusted EC ############### +mach create "EC" +machine LoadPlatformDescription @ec/betrusted-ec.repl + +# logLevel -1 i2c +# logLevel -1 i2c.bq27421 +# logLevel -1 wifi +# logLevel 0 wifi.wf200 +# sysbus LogPeripheralAccess wifi true + +machine StartGdbServer 3334 true +showAnalyzer uart + +# Connect the EC to the SPI bus +connector Connect sysbus.com com + +macro reset +""" + sysbus LoadBinary @ec/bt-ec.bin 0x20000000 + sysbus LoadBinary @ec/wf200_fw.bin 0x2009C000 + sysbus LoadBinary @ec/loader.bin 0x00000000 + cpu PC 0 + cpu SP 0x1001FFFC +""" +runMacro $reset + +mach clear + +start diff --git a/emulation/xous-swap.resc b/emulation/xous-swap.resc new file mode 100644 index 000000000..56a8bd7d2 --- /dev/null +++ b/emulation/xous-swap.resc @@ -0,0 +1,10 @@ +i @emulation/betrusted-swap.resc +i @emulation/linux-server.resc + + +# Connect EC to the switch +mach set "EC" +connector Connect sysbus.wifi.wf200 switch +mach clear + +start \ No newline at end of file