diff --git a/Cargo.lock b/Cargo.lock index 0cc7c79b8..ecd86939f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -505,7 +505,7 @@ dependencies = [ [[package]] name = "curve25519-dalek" version = "3.1.0" -source = "git+https://github.com/betrusted-io/curve25519-dalek.git?branch=main#b8f968b6e45816d3f5148eb3fb9e10803fedd3f9" +source = "git+https://github.com/betrusted-io/curve25519-dalek.git?branch=main#c0ee5bf18c606b51bbffb02fde5801ac129b4e7d" dependencies = [ "byteorder", "digest", diff --git a/Cargo.toml b/Cargo.toml index 550cc607d..585617c9c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,8 +78,8 @@ resolver = "2" # Keep them out of the main workspace. exclude = [ "kernel", - "loader", # Exclude UTRA, since it is machine-generated. - "utralib", + "loader", + "utralib", # Exclude UTRA, since it is machine-generated. ] [profile.release] diff --git a/loader/Cargo.lock b/loader/Cargo.lock index bdb8bbe9f..f0c5a673c 100644 --- a/loader/Cargo.lock +++ b/loader/Cargo.lock @@ -47,12 +47,6 @@ version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" -[[package]] -name = "cfg-if" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" - [[package]] name = "clap" version = "2.33.3" @@ -68,21 +62,17 @@ dependencies = [ "vec_map", ] +[[package]] +name = "com_rs" +version = "0.1.0" +source = "git+https://github.com/betrusted-io/com_rs?branch=main#4b45a42ad2d932550566d6c32ec1e1dd60e93c67" + [[package]] name = "convert_case" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" -[[package]] -name = "cpufeatures" -version = "0.1.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "66c99696f6c9dd7f35d486b9d04d7e6e202aa3e8c40d553f2fdf5e7e0c6a71ef" -dependencies = [ - "libc", -] - [[package]] name = "curve25519-dalek" version = "3.1.0" @@ -96,6 +86,20 @@ dependencies = [ "zeroize", ] +[[package]] +name = "curve25519-dalek" +version = "3.1.0" +source = "git+https://github.com/betrusted-io/curve25519-dalek.git?branch=main#c0ee5bf18c606b51bbffb02fde5801ac129b4e7d" +dependencies = [ + "byteorder", + "digest", + "engine25519-as", + "rand_core", + "subtle", + "utralib", + "zeroize", +] + [[package]] name = "digest" version = "0.9.0" @@ -120,12 +124,17 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" dependencies = [ - "curve25519-dalek", + "curve25519-dalek 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)", "ed25519", "sha2", "zeroize", ] +[[package]] +name = "engine25519-as" +version = "0.1.0" +source = "git+https://github.com/betrusted-io/engine25519-as.git?rev=6681e73c1fdc4a460b5ef9f9c7c91aef546d00f3#6681e73c1fdc4a460b5ef9f9c7c91aef546d00f3" + [[package]] name = "generic-array" version = "0.14.4" @@ -161,7 +170,8 @@ checksum = "12b8adadd720df158f4d70dfe7ccc6adb0472d7c55ca83445f6a5ab3e36f8fb6" name = "loader" version = "0.1.0" dependencies = [ - "curve25519-dalek", + "com_rs", + "curve25519-dalek 3.1.0 (git+https://github.com/betrusted-io/curve25519-dalek.git?branch=main)", "ed25519-dalek", "lazy_static", "utralib", @@ -215,14 +225,11 @@ checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" [[package]] name = "sha2" version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b362ae5752fd2137731f9fa25fd4d9058af34666ca1966fb969119cc35719f12" dependencies = [ "block-buffer", - "cfg-if", - "cpufeatures", "digest", "opaque-debug", + "utralib", ] [[package]] diff --git a/loader/Cargo.toml b/loader/Cargo.toml index 2e8d2ff6a..732aa7677 100644 --- a/loader/Cargo.toml +++ b/loader/Cargo.toml @@ -8,10 +8,18 @@ description = "Initial kernel loader for Xous" [dependencies] utralib = {path = "../utralib"} +[dependencies.com_rs] +git="https://github.com/betrusted-io/com_rs" +branch="main" + [dependencies.curve25519-dalek] +git="https://github.com/betrusted-io/curve25519-dalek.git" +branch="main" +#path = "../../curve25519-dalek" +package = "curve25519-dalek" version = "3.1.0" default-features = false -features = ["u32_backend"] +features = ["u32e_backend"] [dependencies.ed25519-dalek] version="1.0.1" @@ -25,8 +33,8 @@ lazy_static = "1.4.0" [features] debug-print = [] earlyprintk = [] -default = ["debug-print"] -#default = [] +#default = ["debug-print"] +default = [] [profile.release] codegen-units = 1 # 1 better optimizations @@ -35,3 +43,12 @@ lto = "fat" [target.'cfg(not(any(windows, unix)))'.dependencies] utralib = { path = "../utralib"} + +# patch key references into our local name space +[patch.crates-io.sha2] +path = "./sha2" +package = "sha2" +default-features = false + +[patch.crates-io.utralib] +path = "../utralib" diff --git a/loader/bin/riscv32i-unknown-none-elf.a b/loader/bin/riscv32i-unknown-none-elf.a index ec3693020..00b0e5c35 100755 Binary files a/loader/bin/riscv32i-unknown-none-elf.a and b/loader/bin/riscv32i-unknown-none-elf.a differ diff --git a/loader/bin/riscv32imac-unknown-none-elf.a b/loader/bin/riscv32imac-unknown-none-elf.a index 4e25c296a..fe2b07cc1 100755 Binary files a/loader/bin/riscv32imac-unknown-none-elf.a and b/loader/bin/riscv32imac-unknown-none-elf.a differ diff --git a/loader/bin/riscv32imc-unknown-none-elf.a b/loader/bin/riscv32imc-unknown-none-elf.a index 4e25c296a..fe2b07cc1 100755 Binary files a/loader/bin/riscv32imc-unknown-none-elf.a and b/loader/bin/riscv32imc-unknown-none-elf.a differ diff --git a/loader/bin/riscv64gc-unknown-none-elf.a b/loader/bin/riscv64gc-unknown-none-elf.a index b7e586264..8eeeea44c 100755 Binary files a/loader/bin/riscv64gc-unknown-none-elf.a and b/loader/bin/riscv64gc-unknown-none-elf.a differ diff --git a/loader/bin/riscv64imac-unknown-none-elf.a b/loader/bin/riscv64imac-unknown-none-elf.a index b7e586264..8eeeea44c 100755 Binary files a/loader/bin/riscv64imac-unknown-none-elf.a and b/loader/bin/riscv64imac-unknown-none-elf.a differ diff --git a/loader/link.x b/loader/link.x index ac1f4fd36..035c30181 100644 --- a/loader/link.x +++ b/loader/link.x @@ -5,7 +5,7 @@ MEMORY MEMLCD: ORIGIN = 0xB0000000, LENGTH = 32k } /* -Fonts go from 0x2051_0000 to 0x2098_0000 +Fonts go from 0x2052_0000 to 0x2098_0000 */ REGION_ALIAS("REGION_TEXT", FLASH); @@ -90,7 +90,7 @@ SECTIONS _edata = .; } > REGION_DATA AT > REGION_RODATA - .fonts ALIGN(65536) : SUBALIGN(65536) + .fonts ALIGN(131072) : SUBALIGN(131072) { KEEP(*(.fontdata)); } > REGION_RODATA diff --git a/loader/sha2/Cargo.toml b/loader/sha2/Cargo.toml new file mode 100644 index 000000000..fa32b50d4 --- /dev/null +++ b/loader/sha2/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "sha2" +version = "0.9.5" +authors = ["bunnie "] +edition = "2018" +description = "sha2 hardware accelerator engine" + +[dependencies] +utralib = {path = "../../utralib"} + +# Rust-standard digest API dependencies +digest = "0.9" +block-buffer = "0.9" +opaque-debug = "0.3" # prevents internal hash state leakage from debug structures + +[target.'cfg(not(any(windows,unix)))'.dependencies] +utralib = { path = "../../utralib"} + +[features] +default = [] diff --git a/loader/sha2/src/lib.rs b/loader/sha2/src/lib.rs new file mode 100644 index 000000000..87ad49c7d --- /dev/null +++ b/loader/sha2/src/lib.rs @@ -0,0 +1,148 @@ +#![cfg_attr(target_os = "none", no_std)] + +use digest::{BlockInput, FixedOutputDirty, Reset, Update}; +use digest::consts::{U64, U128}; +type BlockSize = U128; + +use utralib::generated::*; + +/// The SHA-512 hash algorithm with the SHA-512 initial hash value. +#[derive(Clone)] +pub struct Sha512 { + csr: utralib::CSR, + fifo: *mut u32, +} +impl Sha512 { + // use this function instead of default for more control over configuration of the hardware engine + pub fn new() -> Self { + let mut csr = CSR::new(utra::sha512::HW_SHA512_BASE as *mut u32); + csr.wfo(utra::sha512::POWER_ON, 1); + // setup for sha512 operation + csr.wo(utra::sha512::CONFIG, + csr.ms(utra::sha512::CONFIG_DIGEST_SWAP, 1) | + csr.ms(utra::sha512::CONFIG_ENDIAN_SWAP, 1) | + csr.ms(utra::sha512::CONFIG_SHA_EN, 1) + ); + csr.wfo(utra::sha512::COMMAND_HASH_START, 1); + // csr.wfo(utra::sha512::EV_ENABLE_SHA512_DONE, 1); + + Sha512 { + csr, + fifo: utralib::HW_SHA512_MEM as *mut u32, + } + } + // call before exit, to cleanup from bootloader -- otherwise the unit might be stuck on as it's assumed to be off going into Xous + pub fn power_off(&mut self) { + self.csr.wfo(utra::sha512::POWER_ON, 0); + } +} + +impl Default for Sha512 { + fn default() -> Self { + Sha512::new() + } +} + +impl Drop for Sha512 { + fn drop(&mut self) { + self.csr.wo(utra::sha512::CONFIG, 0); // clear all config bits, including EN, which resets the unit + } +} + +impl BlockInput for Sha512 { + type BlockSize = BlockSize; +} + +impl Update for Sha512 { + fn update(&mut self, input: impl AsRef<[u8]>) { + let buf: &[u8] = input.as_ref(); + + self.csr.wfo(utra::sha512::POWER_ON, 1); + let sha = self.fifo; + let sha_byte = self.fifo as *mut u8; + + for (_reg, chunk) in buf.chunks(4).enumerate() { + let mut temp: [u8; 4] = Default::default(); + if chunk.len() == 4 { + temp.copy_from_slice(chunk); + let dword: u32 = u32::from_le_bytes(temp); + + while self.csr.rf(utra::sha512::FIFO_ALMOST_FULL) != 0 { + } + unsafe { sha.write_volatile(dword); } + } else { + for index in 0..chunk.len() { + while self.csr.rf(utra::sha512::FIFO_ALMOST_FULL) != 0 { + } + unsafe{ sha_byte.write_volatile(chunk[index]); } + } + } + } + } +} + +impl FixedOutputDirty for Sha512 { + type OutputSize = U64; + + fn finalize_into_dirty(&mut self, out: &mut digest::Output) { + self.csr.wfo(utra::sha512::EV_PENDING_SHA512_DONE, 1); // clear the done if it's pending + self.csr.wfo(utra::sha512::COMMAND_HASH_PROCESS, 1); + while self.csr.rf(utra::sha512::EV_PENDING_SHA512_DONE) == 0 { + } + self.csr.wfo(utra::sha512::EV_PENDING_SHA512_DONE, 1); + + let _length_in_bits: u64 = (self.csr.r(utra::sha512::MSG_LENGTH0) as u64) | ((self.csr.r(utra::sha512::MSG_LENGTH1) as u64) << 32); + let mut hash: [u8; 64] = [0; 64]; + let digest_regs: [utralib::Register; 16] = [ + utra::sha512::DIGEST00, + utra::sha512::DIGEST01, + utra::sha512::DIGEST10, + utra::sha512::DIGEST11, + utra::sha512::DIGEST20, + utra::sha512::DIGEST21, + utra::sha512::DIGEST30, + utra::sha512::DIGEST31, + utra::sha512::DIGEST40, + utra::sha512::DIGEST41, + utra::sha512::DIGEST50, + utra::sha512::DIGEST51, + utra::sha512::DIGEST60, + utra::sha512::DIGEST61, + utra::sha512::DIGEST70, + utra::sha512::DIGEST71, + ]; + let mut i = 0; + for ® in digest_regs.iter() { + hash[i..i+4].clone_from_slice(&self.csr.r(reg).to_le_bytes()); + i += 4; + } + self.csr.wo(utra::sha512::CONFIG, 0); // clear all config bits, including EN, which resets the unit + + // two-stage copy because we're porting code over. maybe this could be merged into the copy above, but let's optimize that once things are working. + for (dest, &src) in out.chunks_exact_mut(1).zip(hash.iter()) { + dest.copy_from_slice(&[src]) + } + } +} + +impl Reset for Sha512 { + fn reset(&mut self) { + if self.csr.rf(utra::sha512::FIFO_RUNNING) != 0 { + // if it's running, call digest, then reset + let sha = self.fifo; + unsafe { sha.write_volatile(0x0); } // stuff a dummy byte, in case the hash was empty + self.csr.wfo(utra::sha512::COMMAND_HASH_PROCESS, 1); + self.csr.wfo(utra::sha512::EV_PENDING_SHA512_DONE, 1); + while self.csr.rf(utra::sha512::EV_PENDING_SHA512_DONE) == 0 { + } + } else { + // engine is already stopped, just clear the pending bits and reset the config + } + self.csr.wfo(utra::sha512::EV_PENDING_SHA512_DONE, 1); + self.csr.wo(utra::sha512::CONFIG, 0); // clear all config bits, including EN, which resets the unit + } +} + +opaque_debug::implement!(Sha512); + +digest::impl_write!(Sha512); diff --git a/loader/src/asm.S b/loader/src/asm.S index 748503f44..53ac6f6f9 100644 --- a/loader/src/asm.S +++ b/loader/src/asm.S @@ -6,6 +6,15 @@ _start: csrw mideleg, t0 csrw medeleg, t0 + // decorate our stack area with a canary pattern + li t1, 0xACE0BACE + li t0, 0x40FFE01C // currently allowed stack extent - 8k - (7 words) - 7 words for kernel backup args - see bootloader in betrusted-soc + li t2, 0x41000000 +fillstack: + sw t1, 0(t0) + addi t0, t0, 4 + bltu t0, t2, fillstack + // Place the stack pointer at the end of RAM li t0, 0x40000000 // SRAM start hard-coded into loader -- don't trust kernel boot args to tell us where RAM is, we haven't validated them yet! li t1, 0x01000000 // SRAM length diff --git a/loader/src/font6x12.png b/loader/src/font6x12.png new file mode 100644 index 000000000..3922f650e Binary files /dev/null and b/loader/src/font6x12.png differ diff --git a/loader/src/font6x12_1bpp.raw b/loader/src/font6x12_1bpp.raw new file mode 100644 index 000000000..3a25b9beb Binary files /dev/null and b/loader/src/font6x12_1bpp.raw differ diff --git a/loader/src/fonts.rs b/loader/src/fonts.rs old mode 100644 new mode 100755 index 4abd8bbe1..1136823c0 --- a/loader/src/fonts.rs +++ b/loader/src/fonts.rs @@ -1,7 +1,7 @@ // This file is autogenerated by xous-core/loader/src/generate_fonts.py. Do not edit. // The order of these modules impacts the link order, which changes the position in the binary image. -pub mod hanzi; +pub mod bold; pub mod emoji; +pub mod hanzi; pub mod regular; pub mod small; -pub mod bold; diff --git a/loader/src/fonts/bold.rs b/loader/src/fonts/bold.rs old mode 100644 new mode 100755 diff --git a/loader/src/fonts/emoji.rs b/loader/src/fonts/emoji.rs old mode 100644 new mode 100755 diff --git a/loader/src/fonts/hanzi.rs b/loader/src/fonts/hanzi.rs old mode 100644 new mode 100755 diff --git a/loader/src/fonts/regular.rs b/loader/src/fonts/regular.rs old mode 100644 new mode 100755 diff --git a/loader/src/fonts/small.rs b/loader/src/fonts/small.rs old mode 100644 new mode 100755 diff --git a/loader/src/generate_fonts.py b/loader/src/generate_fonts.py index 1662e2b38..72ef305e1 100755 --- a/loader/src/generate_fonts.py +++ b/loader/src/generate_fonts.py @@ -73,7 +73,7 @@ def main(): mapfile.write("#![allow(dead_code)]\n") # Python iterators are deterministic, right......? so if I used the same iterator to make the link order it'll be the same here....right? offset = 0 - mapfile.write("pub const FONT_BASE: usize = 0x{:08x};\n".format(0x20510000)) + mapfile.write("pub const FONT_BASE: usize = 0x{:08x};\n".format(0x20520000)) for k,v in fontdict.items(): length = int(v) * 4 mapfile.write("pub const {}_OFFSET: usize = 0x{:08x};\n".format(k.upper(), offset)) diff --git a/loader/src/main.rs b/loader/src/main.rs index c297eb986..0cd7fd2c9 100644 --- a/loader/src/main.rs +++ b/loader/src/main.rs @@ -43,7 +43,8 @@ mod debug; mod fonts; -use ed25519_dalek::*; +mod secboot; +use secboot::SIGBLOCK_SIZE; // Install a panic handler when not running tests. #[cfg(not(test))] @@ -1065,7 +1066,21 @@ pub fn copy_args(cfg: &mut BootConfig) { /// /// This function is safe to call exactly once. #[export_name = "rust_entry"] -pub unsafe extern "C" fn rust_entry(arg_buffer: *const usize, signature: u32) -> ! { +pub unsafe extern "C" fn rust_entry(signed_buffer: *const usize, signature: u32) -> ! { + // initially validate the whole image on disk (including kernel args) + // kernel args must be validated because tampering with them can change critical assumptions about + // how data is loaded into memory + if !secboot::validate_xous_img(signed_buffer as *const u32) { + loop {} + }; + // the kernel arg buffer is SIG_BLOCK_SIZE into the signed region + let arg_buffer = (signed_buffer as u32 + SIGBLOCK_SIZE as u32) as *const usize; + + // perhaps later on in these sequences, individual sub-images may be validated + // against sub-signatures; or the images may need to be re-validated after loading + // into RAM, if we have concerns about RAM glitching as an attack surface (I don't think we do...). + // But for now, the basic "validate everything as a blob" is perhaps good enough to + // armor code-at-rest against front-line patching attacks. let kab = KernelArguments::new(arg_buffer); boot_sequence(kab, signature); } @@ -1165,6 +1180,8 @@ fn boot_sequence(args: KernelArguments, _signature: u32) -> ! { // where in heap this memory will go. #[allow(clippy::cast_ptr_alignment)] // This test only works on 32-bit systems if false { + // note: memtest is "destructive" -- can't do a resume after suspend with memtest enabled + // use this mainly to trace down e.g. hardware issues with timing to the RAM. memtest(); } let mut cfg = BootConfig { diff --git a/loader/src/secboot.rs b/loader/src/secboot.rs new file mode 100755 index 000000000..f910e5ae1 --- /dev/null +++ b/loader/src/secboot.rs @@ -0,0 +1,379 @@ +use crate::println; + +pub const SIGBLOCK_SIZE: usize = 0x1000; + +const VERSION_STR: &'static str = "Xous OS Loader v0.9.1\n\r"; +// v0.9.0 -- initial version +// v0.9.1 -- booting with hw acceleration, and "simplest signature" check on the entire xous.img blob + +pub const STACK_LEN: u32 = 8192 - (7 * 4); // 7 words for backup kernel args +pub const STACK_TOP: u32 = 0x4100_0000 - STACK_LEN; + +use utralib::generated::*; + +#[repr(C)] +struct SignatureInFlash { + pub version: u32, + pub signed_len: u32, + pub signature: [u8; 64], +} + +struct Point { + x: i16, + y: i16, +} +#[derive(PartialEq, Eq)] +enum Color { + Light, + Dark +} +const FB_WIDTH_WORDS: usize = 11; +const FB_WIDTH_PIXELS: usize = 336; +const FB_LINES: usize = 536; +const FB_SIZE: usize = FB_WIDTH_WORDS * FB_LINES; // 44 bytes by 536 lines +// this font is from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ +const FONT_IMAGE: &'static [u8] = include_bytes!("font6x12_1bpp.raw"); +const CHAR_HEIGHT: u32 = 12; +const CHAR_WIDTH: u32 = 6; +const FONT_IMAGE_WIDTH: u32 = 96; +const LEFT_MARGIN: i16 = 10; + +struct Gfx { + csr: utralib::CSR, + fb: &'static mut [u32], +} +impl<'a> Gfx { + pub fn init(&mut self, clk_mhz: u32) { + self.csr.wfo(utra::memlcd::PRESCALER_PRESCALER, (clk_mhz / 2_000_000) - 1); + } + #[allow(dead_code)] + pub fn update_all(&mut self) { + self.csr.wfo(utra::memlcd::COMMAND_UPDATEALL, 1); + } + pub fn update_dirty(&mut self) { + self.csr.wfo(utra::memlcd::COMMAND_UPDATEDIRTY, 1); + } + pub fn busy(&self) -> bool { + if self.csr.rf(utra::memlcd::BUSY_BUSY) == 1 { + true + } else { + false + } + } + pub fn flush(&mut self) { + self.update_dirty(); + while self.busy() {} + // clear the dirty bits + for lines in 0..FB_LINES { + self.fb[lines * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] &= 0x0000_FFFF; + } + } + pub fn set_devboot(&mut self) { + self.csr.wfo(utra::memlcd::DEVBOOT_DEVBOOT, 1); + } + + fn char_offset(&self, c: char) -> u32 { + let fallback = ' ' as u32 - ' ' as u32; + if c < ' ' { + return fallback; + } + if c <= '~' { + return c as u32 - ' ' as u32; + } + fallback + } + fn put_digit(&mut self, d: u8, pos: &mut Point) { + let mut buf: [u8; 4] = [0; 4]; // stack buffer for the character encoding + let nyb = d & 0xF; + if nyb < 10 { + self.msg(((nyb + 0x30) as char).encode_utf8(&mut buf), pos); + } else { + self.msg(((nyb + 0x61 - 10) as char).encode_utf8(&mut buf), pos); + } + } + fn put_hex(&mut self, c: u8, pos: &mut Point) { + self.put_digit(c >> 4, pos); + self.put_digit(c & 0xF, pos); + } + pub fn hex_word(&mut self, word: u32, pos: &mut Point) { + for &byte in word.to_be_bytes().iter() { + self.put_hex(byte, pos); + } + } + pub fn msg(&mut self, text: &'a str, pos: &mut Point) { + // this routine is adapted from the embedded graphics crate https://docs.rs/embedded-graphics/0.7.1/embedded_graphics/ + let char_per_row = FONT_IMAGE_WIDTH / CHAR_WIDTH; + let mut idx = 0; + let mut x_update: i16 = 0; + for current_char in text.chars() { + let mut char_walk_x = 0; + let mut char_walk_y = 0; + + loop { + // Char _code_ offset from first char, most often a space + // E.g. first char = ' ' (32), target char = '!' (33), offset = 33 - 32 = 1 + let char_offset = self.char_offset(current_char); + let row = char_offset / char_per_row; + + // Top left corner of character, in pixels + let char_x = (char_offset - (row * char_per_row)) * CHAR_WIDTH; + let char_y = row * CHAR_HEIGHT; + + // Bit index + // = X pixel offset for char + // + Character row offset (row 0 = 0, row 1 = (192 * 8) = 1536) + // + X offset for the pixel block that comprises this char + // + Y offset for pixel block + let bitmap_bit_index = char_x + + (FONT_IMAGE_WIDTH * char_y) + + char_walk_x + + (char_walk_y * FONT_IMAGE_WIDTH); + + let bitmap_byte = bitmap_bit_index / 8; + let bitmap_bit = 7 - (bitmap_bit_index % 8); + + let color = if FONT_IMAGE[bitmap_byte as usize] & (1 << bitmap_bit) != 0 { + Color::Light + } else { + Color::Dark + }; + + let x = pos.x + + (CHAR_WIDTH * idx as u32) as i16 + + char_walk_x as i16; + let y = pos.y + char_walk_y as i16; + + // draw color at x, y + if (current_char as u8 != 0xd) && (current_char as u8 != 0xa) { // don't draw CRLF specials + self.draw_pixel(Point{x, y}, color); + } + + char_walk_x += 1; + + if char_walk_x >= CHAR_WIDTH { + char_walk_x = 0; + char_walk_y += 1; + + // Done with this char, move on to the next one + if char_walk_y >= CHAR_HEIGHT { + if current_char as u8 == 0xd { // '\n' + pos.y += CHAR_HEIGHT as i16; + } else if current_char as u8 == 0xa { // '\r' + pos.x = LEFT_MARGIN as i16; + x_update = 0; + } else { + idx += 1; + x_update += CHAR_WIDTH as i16; + } + + break; + } + } + } + } + pos.x += x_update; + self.flush(); + } + pub fn draw_pixel(&mut self, pix: Point, color: Color) { + let mut clip_y: usize = pix.y as usize; + if clip_y >= FB_LINES { + clip_y = FB_LINES - 1; + } + let clip_x: usize = pix.x as usize; + if clip_x >= FB_WIDTH_PIXELS { + clip_y = FB_WIDTH_PIXELS - 1; + } + if color == Color::Light { + self.fb[(clip_x + clip_y * FB_WIDTH_WORDS * 32) / 32] |= 1 << (clip_x % 32) + } else { + self.fb[(clip_x + clip_y * FB_WIDTH_WORDS * 32) / 32] &= !(1 << (clip_x % 32)) + } + // set the dirty bit on the line that contains the pixel + self.fb[clip_y * FB_WIDTH_WORDS + (FB_WIDTH_WORDS - 1)] |= 0x1_0000; + } +} + +struct Keyrom { + csr: utralib::CSR, +} +#[derive(Copy, Clone)] +enum KeyLoc { + SelfSignPub = 0x10, + DevPub = 0x18, + ThirdPartyPub = 0x20, +} +impl Keyrom { + pub fn new() -> Self { + Keyrom { + csr: CSR::new(utra::keyrom::HW_KEYROM_BASE as *mut u32), + } + } + fn key_is_zero(&mut self, key_base: KeyLoc) -> bool { + for offset in key_base as u32..key_base as u32 + 8 { + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32); + if self.csr.rf(utra::keyrom::DATA_DATA) != 0 { + return false; + } + } + true + } + fn key_is_dev(&mut self, key_base: KeyLoc) -> bool { + for offset in 0..8 { + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32 + key_base as u32); + let kval = self.csr.rf(utra::keyrom::DATA_DATA); + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, offset as u32 + KeyLoc::DevPub as u32); + let dkval = self.csr.rf(utra::keyrom::DATA_DATA); + if kval != dkval { + return false; + } + } + true + } + fn read_ed25519(&mut self, key_base: KeyLoc) -> ed25519_dalek::PublicKey { + let mut pk_bytes: [u8; 32] = [0; 32]; + for (offset, pk_word) in pk_bytes.chunks_exact_mut(4).enumerate() { + self.csr.wfo(utra::keyrom::ADDRESS_ADDRESS, key_base as u32 + offset as u32); + let word = self.csr.rf(utra::keyrom::DATA_DATA); + for (&src_byte, dst_byte) in word.to_be_bytes().iter().zip(pk_word.iter_mut()) { + *dst_byte = src_byte; + } + } + ed25519_dalek::PublicKey::from_bytes(&pk_bytes).unwrap() + } +} + +// returns true if the kernel is valid +// side-effects the "devboot" register in the gfx engine if devkeys were detected +pub fn validate_xous_img(xous_img_offset: *const u32) -> bool { + // reset the SHA block, in case we're coming out of a warm reset + let mut sha = CSR::new(utra::sha512::HW_SHA512_BASE as *mut u32); + sha.wfo(utra::sha512::POWER_ON, 1); + sha.wfo(utra::sha512::CONFIG_RESET, 1); // this reset takes ~32 CPU cycles before we can use the SHA block. not a problem. + + // conjure the signature struct directly out of memory. super unsafe. + let sig_ptr = xous_img_offset as *const SignatureInFlash; + let sig: &SignatureInFlash = unsafe{sig_ptr.as_ref().unwrap()}; + let mut cursor = Point {x: LEFT_MARGIN, y: (FB_LINES as i16 / 2) + 10}; // draw on bottom half + + // clear screen to all black + let mut gfx = Gfx { + csr: CSR::new(utra::memlcd::HW_MEMLCD_BASE as *mut u32), + fb: unsafe{core::slice::from_raw_parts_mut(utralib::HW_MEMLCD_MEM as *mut u32, FB_SIZE)}, + }; + gfx.init(100_000_000); + + // insert a pattern of alternating 0101/1010 to create a "gray effect" on the bottom half of the fb + // note that the gray has "stripes" every 32 bits but it's visually easier to look at than stripes every other bit + let (_top, bottom) = gfx.fb.split_at_mut(gfx.fb.len() / 2); + for (i, word) in bottom.iter_mut().enumerate() { + if i % 2 == 0 { + *word = 0xAAAA_AAAA; + } else { + *word = 0x5555_5555; + } + } + gfx.flush(); + + // now characters should actually be able to print + gfx.msg(VERSION_STR, &mut cursor); + println!("{}", VERSION_STR); + + // init the curve25519 engine + let mut engine = utralib::CSR::new(utra::engine::HW_ENGINE_BASE as *mut u32); + engine.wfo(utra::engine::POWER_ON, 1); + engine.wfo(utra::engine::WINDOW_WINDOW, 0); + engine.wfo(utra::engine::MPSTART_MPSTART, 0); + + // select the public key + let mut keyrom = Keyrom::new(); + let keyloc = + if !keyrom.key_is_zero(KeyLoc::SelfSignPub) { // self-signing key takes priority + if keyrom.key_is_dev(KeyLoc::SelfSignPub) { + println!("Self-signed key slot, but with developer public key."); + gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + gfx.set_devboot(); + } + println!("Using self-signed public key"); + KeyLoc::SelfSignPub + } else if !keyrom.key_is_zero(KeyLoc::ThirdPartyPub) { // third party key is second in line + if keyrom.key_is_dev(KeyLoc::ThirdPartyPub) { + println!("Third party public key slot, but with developer public key."); + gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + gfx.set_devboot(); + } + println!("Using third-party public key"); + KeyLoc::ThirdPartyPub + } else { + if keyrom.key_is_zero(KeyLoc::DevPub) { + gfx.msg("Can't boot: No valid keys!", &mut cursor); + loop {} + } + gfx.msg("DEVELOPER KEY DETECTED\n\r", &mut cursor); + println!("Using developer public key"); + gfx.set_devboot(); + KeyLoc::DevPub + }; + let pubkey = keyrom.read_ed25519(keyloc); + + println!("Public key bytes: {:x?}", pubkey.as_bytes()); + + if sig.version != 1 { + println!("Warning: mismatch on signature record version numbering. Ignoring and moving on...") + } + let signed_len = sig.signed_len; + let image: &[u8] = unsafe{core::slice::from_raw_parts((xous_img_offset as usize + SIGBLOCK_SIZE) as *const u8, signed_len as usize)}; + let ed25519_signature = ed25519_dalek::Signature::from(sig.signature); + + use ed25519_dalek::Verifier; + if pubkey.verify(image, &ed25519_signature).is_ok() { + gfx.msg("Signature check passed\n\r", &mut cursor); + println!("Signature check passed"); + } else { + gfx.msg("Signature check failed, powering down\n\r", &mut cursor); + println!("Signature check failed"); + let ticktimer = CSR::new(utra::ticktimer::HW_TICKTIMER_BASE as *mut u32); + let mut power = CSR::new(utra::power::HW_POWER_BASE as *mut u32); + let mut com = CSR::new(utra::com::HW_COM_BASE as *mut u32); + let mut start = ticktimer.rf(utra::ticktimer::TIME0_TIME); + loop { + // every 15 seconds, attempt to send a power down command + // any attempt to re-flash the system must halt the CPU before we time-out to this point! + if ticktimer.rf(utra::ticktimer::TIME0_TIME) - start > 15_000 { + println!("Powering down..."); + power.rmwf(utra::power::POWER_STATE, 0); + power.rmwf(utra::power::POWER_SELF, 0); + + // ship mode is the safest mode -- suitable for long-term storage (~years) + com.wfo(utra::com::TX_TX, com_rs::ComState::POWER_SHIPMODE.verb as u32); + while com.rf(utra::com::STATUS_TIP) == 1 {} + let _ = com.rf(utra::com::RX_RX); // discard the RX result + start = ticktimer.rf(utra::ticktimer::TIME0_TIME); + } + } + } + + // check the stack usage + let stack: &[u32] = unsafe{core::slice::from_raw_parts(STACK_TOP as *const u32, (STACK_LEN as usize / core::mem::size_of::()) as usize)}; + let mut unused_stack_words = 0; + for &word in stack.iter() { + if word != 0xACE0BACE { + break; + } + unused_stack_words += 1; + } + println!("Free stack after signature check: {} bytes", unused_stack_words * 4); + gfx.msg("Free stack after sigcheck: 0x", &mut cursor); + gfx.hex_word(unused_stack_words * 4, &mut cursor); + + gfx.msg("\n\r\n\rLoading kernel...\n\r", &mut cursor); + println!("Everything checks out, loading to kernel..."); + + let mut sha_csr = CSR::new(utra::sha512::HW_SHA512_BASE as *mut u32); + sha_csr.wfo(utra::sha512::POWER_ON, 0); // cut power to the SHA block; this is the expected default state after the bootloader is done. + let mut engine_csr = CSR::new(utra::engine::HW_ENGINE_BASE as *mut u32); + engine_csr.wfo(utra::engine::POWER_ON, 0); // cut power to the engine block; this is the expected default state after the bootloader is done. + // note that removing power does *not* clear the RF or microcode state -- data can leak from the bootloader + // into other areas because of this! (but I think it's OK because we just mess around with public keys here) + + true +} diff --git a/precursors/soc.svd b/precursors/soc.svd index f1af1531e..11bd3f218 100755 --- a/precursors/soc.svd +++ b/precursors/soc.svd @@ -3,7 +3,7 @@ litex SOC - + 8 32 @@ -433,11 +433,27 @@ configure as output for the value to appear on the pin]]> + + USBDISABLE + + 0x001c + 0x00 + 32 + + + usbdisable + 0 + [0:0] + 0 + + + EV_STATUS - 0x001c + 0x0020 0x00 32 @@ -503,7 +519,7 @@ Writes to this register have no effect.]]> EV_PENDING - 0x0020 + 0x0024 0x00 32 @@ -577,7 +593,7 @@ edge.]]> EV_ENABLE - 0x0024 + 0x0028 0x00 32 @@ -642,7 +658,7 @@ register to disable individual events.]]> 0 - 0x28 + 0x2c registers @@ -1222,10 +1238,10 @@ register to disable individual events.]]> GIT_GITREV 0x0014 - 0xa27f1fe4 + 0xab8658b6 32 @@ -1242,7 +1258,7 @@ the exact git version used to build this firmware.]]> is ``1``, then the repository this was built from has one additional commit beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]> 0x0018 - 0x39 + 0x3e 32 @@ -1499,14 +1515,32 @@ register to disable individual events.]]> [0:0] 0 +Cannot be cleared, except by a full reset. Do not rely on this register to +determine if a devboot has happened; the *register* may be cleared, but the +internal hardware bit cannot be.]]> + + + + + DEVSTATUS + + 0x001c + 0x00 + 32 + + + devstatus + 0 + [0:0] + 0 0 - 0x1c + 0x20 registers @@ -3467,7 +3501,7 @@ inject too fast.]]> SEED1 0x0000 - 0x657b4b20 + 0x2b72d267 32 @@ -3482,7 +3516,7 @@ inject too fast.]]> SEED0 0x0004 - 0x4ba4def0 + 0x2d8ab78 32 @@ -5847,6 +5881,13 @@ savings)]]> 3 + + reset + 4 + [4:4] + 4 + + @@ -6241,52 +6282,59 @@ in bits]]> 32 - read_count - 8 - [8:0] + reset_status + 0 + [0:0] 0 + + + + read_count + 9 + [9:1] + 1 write_count - 17 - [17:9] - 9 + 18 + [18:10] + 10 read_error - 18 - [18:18] - 18 + 19 + [19:19] + 19 write_error - 19 - [19:19] - 19 + 20 + [20:20] + 20 almost_full - 20 - [20:20] - 20 + 21 + [21:21] + 21 almost_empty - 21 - [21:21] - 21 + 22 + [22:22] + 22 running - 22 - [22:22] - 22 + 23 + [23:23] + 23 @@ -6946,7 +6994,7 @@ of the PLL]]> SHA512 0xE0002000 - 0x00000008 + 0x00000004 ENGINE diff --git a/precursors/soc_csr.bin b/precursors/soc_csr.bin index 6fd3b420f..4e0850056 100755 Binary files a/precursors/soc_csr.bin and b/precursors/soc_csr.bin differ diff --git a/services/engine-sha512/src/main.rs b/services/engine-sha512/src/main.rs index dfc4c32d1..3eea2b0ae 100644 --- a/services/engine-sha512/src/main.rs +++ b/services/engine-sha512/src/main.rs @@ -65,7 +65,7 @@ mod implementation { .expect("couldn't map Engine512 CSR range"); #[cfg(not(feature = "event_wait"))] - let engine512 = Engine512 { + let mut engine512 = Engine512 { csr: CSR::new(csr.as_mut_ptr() as *mut u32), fifo, }; @@ -87,6 +87,13 @@ mod implementation { // instead, we rely on every usage of this mechanism to explicitly set this enable bit before relying upon it engine512.csr.wfo(utra::sha512::EV_ENABLE_SHA512_DONE, 1); } + // reset the block on boot + // we don't save this as part of the susres set because + // on a "proper" resume, the block was already reset by the secure boot process + // the code path where this really becomes necessary is if we have a WDT reset or + // some sort of server-restart. + engine512.csr.wfo(utra::sha512::CONFIG_RESET, 1); // takes ~32 cycles to complete + engine512 } @@ -206,33 +213,10 @@ mod implementation { pub(crate) fn reset(&mut self) { self.csr.wfo(utra::sha512::POWER_ON, 1); - if self.csr.rf(utra::sha512::FIFO_RUNNING) != 0 { - // if it's running, call digest, then reset - let sha = self.fifo.as_mut_ptr() as *mut u32; - unsafe { sha.write_volatile(0x0); } // stuff a dummy byte, in case the hash was empty - #[cfg(feature = "event_wait")] - { - engine512.csr.wfo(utra::sha512::EV_ENABLE_SHA512_DONE, 1); - self.done = false; - self.csr.wfo(utra::sha512::COMMAND_HASH_PROCESS, 1); - while !self.done { - log::trace!("waiting for sha512_done (reset)"); - xous::wait_event(); - } - log::trace!("moving on (reset)"); - } - #[cfg(not(feature = "event_wait"))] - { - self.csr.wfo(utra::sha512::COMMAND_HASH_PROCESS, 1); - while self.csr.rf(utra::sha512::EV_PENDING_SHA512_DONE) == 0 { - xous::yield_slice(); - } - } - } else { - // engine is already stopped, just clear the pending bits and reset the config - } + self.csr.wfo(utra::sha512::CONFIG_RESET, 1); self.csr.wfo(utra::sha512::EV_PENDING_SHA512_DONE, 1); self.csr.wo(utra::sha512::CONFIG, 0); // clear all config bits, including EN, which resets the unit + while self.csr.rf(utra::sha512::FIFO_RESET_STATUS) == 1 { } // wait for the reset block to finish, if it's not already done by now self.csr.wfo(utra::sha512::POWER_ON, 0); } diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index ca6ec2432..bcb85f8c1 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -131,7 +131,8 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi let llio = llio::Llio::new(&xns).unwrap(); log::debug!("usb unlock notice..."); - let mut debug_unlocked = llio.debug_usb_unlocked().unwrap(); + let (dl, _) = llio.debug_usb(None).unwrap(); + let mut debug_locked = dl; // build security status textview let mut security_tv = TextView::new(status_gid, TextBounds::BoundingBox(Rectangle::new(Point::new(0,screensize.y / 2), @@ -182,13 +183,14 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi needs_redraw = true; }), Some(StatusOpcode::Pump) => { - if debug_unlocked != llio.debug_usb_unlocked().unwrap() { - debug_unlocked = llio.debug_usb_unlocked().unwrap(); + let (is_locked, force_update) = llio.debug_usb(None).unwrap(); + if (debug_locked != is_locked) || force_update { + debug_locked = is_locked; security_tv.clear_str(); - if debug_unlocked { - write!(&mut security_tv, " USB unlocked").unwrap(); - } else { + if debug_locked { write!(&mut security_tv, " USB secured").unwrap(); + } else { + write!(&mut security_tv, " USB unlocked").unwrap(); } // only post the view if something has actually changed gam.post_textview(&mut security_tv).unwrap(); @@ -240,7 +242,8 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi }); } } - if (stats_phase % stats_interval == 0) && ((stats_phase % (stats_interval * 2)) == stats_interval) && datetime.is_some() { + // date/time only redraws once every stats_interval period; but if needs_redraw is triggered (e.g. due to resume), force a redraw + if (needs_redraw || ((stats_phase % stats_interval == 0) && ((stats_phase % (stats_interval * 2)) == stats_interval))) && datetime.is_some() { let dt = datetime.unwrap(); let day = match dt.weekday { rtc::Weekday::Monday => "Mon", diff --git a/services/graphics-server/src/fontmap.rs b/services/graphics-server/src/fontmap.rs old mode 100644 new mode 100755 index d181fdfff..f1fc694ab --- a/services/graphics-server/src/fontmap.rs +++ b/services/graphics-server/src/fontmap.rs @@ -1,15 +1,15 @@ // This file is autogenerated by xous-core/loader/src/generate_fonts.py. Do not edit. // This makes probably bad assumptions about how link order is computed. Be suspicious of these offsets. #![allow(dead_code)] -pub const FONT_BASE: usize = 0x20510000; -pub const HANZI_OFFSET: usize = 0x00000000; -pub const HANZI_LEN: usize = 0x0010df64; -pub const EMOJI_OFFSET: usize = 0x0010df64; -pub const EMOJI_LEN: usize = 0x00059170; -pub const REGULAR_OFFSET: usize = 0x001670d4; -pub const REGULAR_LEN: usize = 0x00001610; -pub const SMALL_OFFSET: usize = 0x001686e4; -pub const SMALL_LEN: usize = 0x000010bc; -pub const BOLD_OFFSET: usize = 0x001697a0; +pub const FONT_BASE: usize = 0x20520000; +pub const BOLD_OFFSET: usize = 0x00000000; pub const BOLD_LEN: usize = 0x00001774; +pub const EMOJI_OFFSET: usize = 0x00001774; +pub const EMOJI_LEN: usize = 0x00059170; +pub const HANZI_OFFSET: usize = 0x0005a8e4; +pub const HANZI_LEN: usize = 0x0010df64; +pub const REGULAR_OFFSET: usize = 0x00168848; +pub const REGULAR_LEN: usize = 0x00001610; +pub const SMALL_OFFSET: usize = 0x00169e58; +pub const SMALL_LEN: usize = 0x000010bc; pub const FONT_TOTAL_LEN: usize = 0x0016af14; diff --git a/services/llio/src/api.rs b/services/llio/src/api.rs index 40b3b799f..9e613ff9f 100644 --- a/services/llio/src/api.rs +++ b/services/llio/src/api.rs @@ -171,13 +171,13 @@ pub(crate) enum Opcode { GpioIntAsFalling, //(u32), GpioIntPending, GpioIntEna, //(u32), - GpioIntSubscribe, //(String<64>), // TODO + GpioIntSubscribe, //(String<64>), // GpioIntHappened, /// set UART mux UartMux, //(UartType), - //TODO InfoLitexId, //(String<64>), // TODO: returns the ASCII string baked into the FPGA that describes the FPGA build, inside Registration + // InfoLitexId, //(String<64>), // TODO: returns the ASCII string baked into the FPGA that describes the FPGA build, inside Registration InfoDna, InfoGit, InfoPlatform, @@ -226,6 +226,9 @@ pub(crate) enum Opcode { EventRtcHappened, EventUsbHappened, + /// debug USB status + DebugUsbOp, + /// SuspendResume callback SuspendResume, diff --git a/services/llio/src/lib.rs b/services/llio/src/lib.rs index caf128a0f..b005dc758 100644 --- a/services/llio/src/lib.rs +++ b/services/llio/src/lib.rs @@ -523,8 +523,33 @@ impl Llio { Err(xous::Error::InternalError) } } - pub fn debug_usb_unlocked(&self) -> Result { - Ok(true) // for now, always return true, because we don't have the hardware yet to lock out debug USB + // if do_lock is Some(), set the debug USB lock status to locked if true, unlocked if false + // returns a tuple of (bool, bool) -> (is_locked, force_update) + // needs_update is so that the polling function knows to redraw the UX after a resume-from-suspend + pub fn debug_usb(&self, do_lock: Option) -> Result<(bool, bool), xous::Error> { + // arg1 indicates if an update to the state is requested + // arg2 is the new state update + let (arg1, arg2) = if let Some(lock) = do_lock { + if lock { + (1, 1) + } else { + (1, 0) + } + } else { + (0, 0) + }; + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::DebugUsbOp.to_usize().unwrap(), arg1, arg2, 0, 0))?; + if let xous::Result::Scalar2(is_locked, force_update) = response { + let il = if is_locked != 0 {true} else {false}; + let fu = if force_update != 0 {true} else {false}; + Ok( + (il, fu) + ) + } else { + log::error!("LLIO: unexpected return value: {:#?}", response); + Err(xous::Error::InternalError) + } } pub fn set_uart_mux(&self, setting: UartType) -> Result<(), xous::Error> { if setting == UartType::Application { diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index a2f0f249b..86923992b 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -206,6 +206,7 @@ mod implementation { xl.gpio_susres.push_fixed_value(RegOrField::Reg(utra::gpio::EV_PENDING), 0xFFFF_FFFF); xl.gpio_susres.push(RegOrField::Reg(utra::gpio::EV_ENABLE), None); xl.gpio_susres.push(RegOrField::Field(utra::gpio::UARTSEL_UARTSEL), None); + xl.gpio_susres.push(RegOrField::Reg(utra::gpio::USBDISABLE), None); xl.event_susres.push_fixed_value(RegOrField::Reg(utra::btevents::EV_PENDING), 0xFFFF_FFFF); xl.event_susres.push(RegOrField::Reg(utra::btevents::EV_ENABLE), None); @@ -446,6 +447,20 @@ mod implementation { let value = if ena {1} else {0}; self.power_csr.rmwf(utra::power::EV_PENDING_USB_ATTACH, value); } + pub fn get_usb_disable(&self) -> bool { + if self.gpio_csr.rf(utra::gpio::USBDISABLE_USBDISABLE) != 0 { + true + } else { + false + } + } + pub fn set_usb_disable(&mut self, state: bool) { + if state { + self.gpio_csr.wfo(utra::gpio::USBDISABLE_USBDISABLE, 1); + } else { + self.gpio_csr.wfo(utra::gpio::USBDISABLE_USBDISABLE, 0); + } + } } } @@ -538,6 +553,13 @@ mod implementation { } pub fn wfi_override(&mut self, _override_: bool) { } + + pub fn get_usb_disable(&self) -> bool { + false + } + pub fn set_usb_disable(&mut self, _state: bool) { + } + } } @@ -643,6 +665,8 @@ fn xmain() -> ! { let mut rtc_cb_conns: [Option; 32] = [None; 32]; let mut gpio_cb_conns: [Option; 32] = [None; 32]; + let mut lockstatus_force_update = true; // some state to track if we've been through a susupend/resume, to help out the status thread with its UX update after a restart-from-cold + log::trace!("starting main loop"); loop { let msg = xous::receive_message(llio_sid).unwrap(); @@ -652,6 +676,7 @@ fn xmain() -> ! { llio.suspend(); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); llio.resume(); + lockstatus_force_update = true; // notify the status bar that yes, it does need to redraw the lock status, even if the value hasn't changed since the last read }), Some(Opcode::CrgMode) => msg_scalar_unpack!(msg, _mode, _, _, _, { todo!("CrgMode opcode not yet implemented."); @@ -858,6 +883,36 @@ fn xmain() -> ! { log::debug!("activity/period: {}/{}, {:.2}%", latest_activity, period, (latest_activity as f32 / period as f32) * 100.0); xous::return_scalar2(msg.sender, latest_activity as usize, period as usize).expect("couldn't return activity"); }), + Some(Opcode::DebugUsbOp) => msg_blocking_scalar_unpack!(msg, update_req, new_state, _, _, { + if update_req != 0 { + // if new_state is true (not 0), then try to lock the USB port + // if false, try to unlock the USB port + if new_state != 0 { + llio.set_usb_disable(true); + } else { + llio.set_usb_disable(false); + } + } + // at this point, *read back* the new state -- don't assume it "took". The readback is always based on + // a real hardware value and not the requested value. for now, always false. + let is_locked = if llio.get_usb_disable() { + 1 + } else { + 0 + }; + + // this is a performance optimization. we could always redraw the status, but, instead we only redraw when + // the status has changed. However, there is an edge case: on a resume from suspend, the status needs a redraw, + // even if nothing has changed. Thus, we have this separate boolean we send back to force an update in the + // case that we have just come out of a suspend. + let force_update = if lockstatus_force_update { + 1 + } else { + 0 + }; + xous::return_scalar2(msg.sender, is_locked, force_update).expect("couldn't return status"); + lockstatus_force_update = false; + }), Some(Opcode::Quit) => { log::info!("Received quit opcode, exiting."); let dropconn = xous::connect(i2c_sid).unwrap(); diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index dbed16db6..cb3cf261d 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -96,6 +96,7 @@ mod trng_cmd; use trng_cmd::*; mod engine; use engine::*; mod console; use console::*; mod memtest; use memtest::*; +mod keys; use keys::*; //mod fcc; use fcc::*; //mod pds; // dependency of the FCC file @@ -119,6 +120,7 @@ pub struct CmdEnv { trng_cmd: TrngCmd, engine_cmd: Engine, memtest_cmd: Memtest, + keys_cmd: Keys, //fcc_cmd: Fcc, } @@ -169,6 +171,7 @@ impl CmdEnv { trng_cmd: TrngCmd::new(), engine_cmd: engine, memtest_cmd: memtest, + keys_cmd: Keys::new(), //fcc_cmd: fcc, } @@ -203,6 +206,7 @@ impl CmdEnv { &mut self.engine_cmd, &mut console_cmd, &mut self.memtest_cmd, + &mut self.keys_cmd, //&mut self.fcc_cmd, ]; diff --git a/services/shellchat/src/cmds/keys.rs b/services/shellchat/src/cmds/keys.rs new file mode 100644 index 000000000..15dfd0f1f --- /dev/null +++ b/services/shellchat/src/cmds/keys.rs @@ -0,0 +1,43 @@ +use crate::{ShellCmdApi, CommonEnv}; +use xous_ipc::String; + +#[derive(Debug)] +pub struct Keys { +} +impl Keys { + pub fn new() -> Keys { + Keys {} + } +} + +impl<'a> ShellCmdApi<'a> for Keys { + cmd_api!(keys); // inserts boilerplate for command API + + fn process(&mut self, args: String::<1024>, env: &mut CommonEnv) -> Result>, xous::Error> { + use core::fmt::Write; + let mut ret = String::<1024>::new(); + let helpstring = "keys options: usblock usbunlock"; + + let mut tokens = args.as_str().unwrap().split(' '); + + if let Some(sub_cmd) = tokens.next() { + match sub_cmd { + "usblock" => { + env.llio.debug_usb(Some(true)).unwrap(); + write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap(); + } + "usbunlock" => { + env.llio.debug_usb(Some(false)).unwrap(); + write!(ret, "USB debug port unlocked: all secrets are readable via USB!").unwrap(); + } + _ => { + write!(ret, "{}", helpstring).unwrap(); + } + } + + } else { + write!(ret, "{}", helpstring).unwrap(); + } + Ok(Some(ret)) + } +} diff --git a/services/shellchat/src/cmds/test.rs b/services/shellchat/src/cmds/test.rs index 8bbf4d6a5..f6b7de7fb 100644 --- a/services/shellchat/src/cmds/test.rs +++ b/services/shellchat/src/cmds/test.rs @@ -32,6 +32,7 @@ impl<'a> ShellCmdApi<'a> for Test { write!(ret, "devboot on").unwrap(); } "devbootoff" => { + // this should do nothing if devboot was already set env.gam.set_devboot(false).unwrap(); write!(ret, "devboot off").unwrap(); } diff --git a/tools/README_UPDATE.md b/tools/README_UPDATE.md index f8adee15f..f5e91ba29 100644 --- a/tools/README_UPDATE.md +++ b/tools/README_UPDATE.md @@ -58,8 +58,8 @@ The updater encodes the offsets of every binary location in the script. When the then the updater script should no longer be used for a given Precursor revision. ``` -usage: usb_update.py [-h] [-s [SoC gateware file]] [-l [loader file]] [-k [kernel file]] [-e [EC gateware package]] - [-w [WF200 firmware package]] [--peek ADDR] [--poke ADDR DATA] [--check-poke] [--config] +usage: usb_update.py [-h] [-s [SoC gateware file]] [-l [loader file]] [-k [kernel file]] [-e [EC gateware package]] [-w [WF200 firmware package]] [--audiotest [Test audio clip]] [--peek ADDR] [--poke ADDR DATA] [--check-poke] + [--config] [-i IMAGEFILE ADDR] [-n] [-f] [--bounce] Update/upload to a Precursor device running Xous 0.8/0.9 @@ -75,10 +75,17 @@ optional arguments: EC gateware -w [WF200 firmware package], --wf200 [WF200 firmware package] WF200 firmware + --audiotest [Test audio clip] + Test audio clip (must be 8kHz WAV) --peek ADDR Inspect an address --poke ADDR DATA Write to an address --check-poke Read data before and after the poke --config Print the descriptor + -i IMAGEFILE ADDR, --image IMAGEFILE ADDR + Manually specify an image and address. Offset is relative to bottom of flash. + -n, --no-verify Skip readback verification (may be necessary for large files to avoid WDT timeout). Only honored with -i. + -f, --force Ignore gitrev version on SoC and try to burn an image anyways + --bounce cycle the device through a reset ``` You can try reading the first word out of the ROM to see if `usb_update.py` is working correctly. diff --git a/tools/sign_image.py b/tools/sign_image.py index 221b652ba..c4298f436 100755 --- a/tools/sign_image.py +++ b/tools/sign_image.py @@ -3,7 +3,7 @@ import argparse import sys from Crypto.IO import PEM # counter-intuitively, this is from pycryptodome: `pip3 install pycryptodome` (ubuntu) `pip install pycryptodome` (maybe others?) # note: if you did the sensible thing and tried to install the crypto or pycrypto libraries first when you hit this error -# you have to uninstall those before putting in pycryptodome. +# you have to uninstall those before putting in pycryptodome: `pip remove crypto`, and then `pip install pycryptodome` (or pip3 on ubuntu) from nacl.signing import SigningKey # from pynacl package: `pip3 install pynacl` from nacl.encoding import RawEncoder import os.path @@ -11,13 +11,13 @@ import os.path import binascii DEVKEY_PATH='../devkey/dev.key' -LOADER_VERSION=1 +SIGNER_VERSION=1 -def loader_sign(source, output, key, defile=False): - global LOADER_VERSION +def blob_sign(source, output, key, defile=False): + global SIGNER_VERSION with open(source, "rb") as source_f: source = list(source_f.read()) - source += int(LOADER_VERSION).to_bytes(4, 'little') # protect the version number + source += int(SIGNER_VERSION).to_bytes(4, 'little') # protect the version number source += len(source).to_bytes(4, 'little') # append the length to the image, and sign that # NOTE NOTE NOTE @@ -28,13 +28,13 @@ def loader_sign(source, output, key, defile=False): with open(output, "wb") as output_f: written = 0 - written += output_f.write(int(LOADER_VERSION).to_bytes(4, 'little')) # version number record - mirrored inside the signed data, too + written += output_f.write(int(SIGNER_VERSION).to_bytes(4, 'little')) # version number record - mirrored inside the signed data, too written += output_f.write(len(source).to_bytes(4, 'little')) # record the length of the final signed record (which /also/ includes a length) written += output_f.write(signature.signature) output_f.write(bytearray([0] * (4096 - written))) # pad out to one page beyond message = bytearray(signature.message) if defile is True: - print("WARNING: defiling the loader image. This corrupts the binary and should cause it to fail the signature check.") + print("WARNING: defiling the image. This corrupts the binary and should cause it to fail the signature check.") message[16778] ^= 0x1 # flip one bit at some random offset output_f.write(message) # the actual signed message @@ -57,6 +57,9 @@ def main(): parser.add_argument( "--loader-output", required=False, help="loader output image", type=str, nargs='?', metavar=('loader output image'), const='../target/riscv32imac-unknown-none-elf/release/loader.bin' ) + parser.add_argument( + "--kernel-output", required=False, help="kernel output image", type=str, nargs='?', metavar=('kernel output image'), const='../target/riscv32imac-unknown-none-elf/release/xous.img' + ) parser.add_argument( "--defile", help="patch the resulting image, to create a test file to catch signature failure", default=False, action="store_true" ) @@ -91,22 +94,26 @@ def main(): loader_pkey = None if loader_pkey != None: - loader_sign(args.loader_image, loader_output, loader_pkey, defile=args.defile) - - - + blob_sign(args.loader_image, loader_output, loader_pkey, defile=args.defile) + # for now, the kernel signing path is just signing a blob that is the overall binary + # however, there is some aspiration to sign individual binaries, and to incorporate + # signatures into the kernel tags. leave this path separate so there's an on-ramp + # to add these features if args.kernel_image and (args.kernel_key is None): kernel_key = DEVKEY_PATH else: kernel_key = args.kernel_key + if args.kernel_image and (args.kernel_output is None): + kernel_output = '../target/riscv32imac-unknown-none-elf/release/xous.img' + else: + kernel_output = args.kernel_output if kernel_key is not None and kernel_key is not DEVKEY_PATH: - kernel_pass = input("Enter loader key passphrase, enter if none: ") with open(kernel_key) as kernel_f: kernel_pem = kernel_f.read() try: - pem = PEM.decode(kernel_pem, kernel_pass) + pem = PEM.decode(kernel_pem, None) except: passphrase = input("Enter kernel key passphrase: ") pem = PEM.decode(kernel_pem, passphrase) @@ -118,6 +125,9 @@ def main(): else: kernel_pkey = None + if kernel_pkey != None: + blob_sign(args.kernel_image, kernel_output, kernel_pkey, defile=args.defile) + if __name__ == "__main__": main() exit(0) diff --git a/tools/usb_update.py b/tools/usb_update.py index 5de361609..3e528adc9 100755 --- a/tools/usb_update.py +++ b/tools/usb_update.py @@ -382,6 +382,9 @@ def main(): parser.add_argument( "-f", "--force", help="Ignore gitrev version on SoC and try to burn an image anyways", action="store_true" ) + parser.add_argument( + "--bounce", help="cycle the device through a reset", action="store_true" + ) args = parser.parse_args() if not len(sys.argv) > 1: diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 153efea00..98a21c7e3 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -5,11 +5,6 @@ use std::{ path::{Path, PathBuf, MAIN_SEPARATOR}, process::Command, }; -/* -extern crate ed25519_dalek; -extern crate pem; -use ed25519_dalek::{Keypair, Signature, PublicKey, PrivateKey}; -*/ type DynError = Box; @@ -268,20 +263,11 @@ fn build_hw_image( } else { String::from("../devkey/dev.key") }; - // placeholder for future signing of the kernel - let _kernelkey_file = if let Some(kkf) = kkey { + let kernelkey_file = if let Some(kkf) = kkey { kkf } else { String::from("../devkey/dev.key") }; - /* aborted effort to do signing in Rust -- config in xtask conflicts with config in kernel :-/ - // use a python helper script instead - let mut lkf = File::open(loaderkey_file)?; - let mut lk_str = Vec::::new(); - lkf.read_to_end(&mut lk_str); - let lk_pems = pem::parse(lk_str); - println!("lk_pems: {:?}", lk_pems); - */ let kernel = build_kernel(debug)?; let mut init = vec![]; @@ -327,7 +313,7 @@ fn build_hw_image( if !status.success() { return Err("cargo build failed".into()); } - // sign_loader(loader_presign, loader_bin, loader_signing_key)?; + let status = Command::new("python3") .current_dir(project_root().join("tools")) .args(&[ @@ -342,11 +328,12 @@ fn build_hw_image( if !status.success() { return Err("loader image sign failed".into()) } - println!("Signed loader at {}", loader_bin.to_str().unwrap()); let mut xous_img_path = output_bundle.parent().unwrap().to_owned(); + let mut xous_img_presign_path = xous_img_path.clone(); xous_img_path.push("xous.img"); - let mut xous_img = std::fs::File::create(&xous_img_path).expect("couldn't create xous.img"); + xous_img_presign_path.push("xous_presign.img"); + let mut xous_img = std::fs::File::create(&xous_img_presign_path).expect("couldn't create xous.img"); let mut bundle_file = std::fs::File::open(output_bundle).expect("couldn't open output bundle"); let mut buf = vec![]; bundle_file @@ -355,9 +342,27 @@ fn build_hw_image( xous_img .write_all(&buf) .expect("couldn't write bundle file to xous.img"); + println!("Bundled image file created at {}", xous_img_path.display()); + + let status = Command::new("python3") + .current_dir(project_root().join("tools")) + .args(&[ + "sign_image.py", + "--kernel-image", + xous_img_presign_path.to_str().unwrap(), + "--kernel-key", + kernelkey_file.as_str(), + "--kernel-output", + xous_img_path.to_str().unwrap(), + // "--defile", + ]).status()?; + if !status.success() { + return Err("kernel image sign failed".into()) + } println!(); - println!("Bundled image file created at {}", xous_img_path.display()); + println!("Signed loader at {}", loader_bin.to_str().unwrap()); + println!("Signed kernel at {}", xous_img_path.to_str().unwrap()); Ok(()) }