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/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/main.rs b/loader/src/main.rs index c297eb986..3a72890f6 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); } diff --git a/loader/src/secboot.rs b/loader/src/secboot.rs new file mode 100755 index 000000000..af2deec83 --- /dev/null +++ b/loader/src/secboot.rs @@ -0,0 +1,247 @@ +#![cfg_attr(target_os = "none", no_std)] +#![cfg_attr(target_os = "none", no_main)] + +#![allow(unreachable_code)] // allow debugging of failures to jump out of the bootloader + +pub const SIGBLOCK_SIZE: usize = 0x1000; + +const VERSION_STR: &'static str = "Xous OS Loader v0.9.0\n\r"; + +////// TODO: derive this from boot args +const KERNEL_DATA_OFFSET: u32 = 0x2098_1000; +const KERNEL_SIG_OFFSET: u32 = 0x2098_0000; + + +const STACK_LEN: u32 = 8192 - (7 * 4); // 7 words for backup kernel args +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); + } + 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 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.update_dirty(); + while self.busy() {} + } + 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 { + true +} diff --git a/precursors/soc.svd b/precursors/soc.svd index f1af1531e..0a1f5af65 100755 --- a/precursors/soc.svd +++ b/precursors/soc.svd @@ -3,7 +3,7 @@ litex SOC - + 8 32 @@ -1499,14 +1499,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 +3485,7 @@ inject too fast.]]> SEED1 0x0000 - 0x657b4b20 + 0x6a195bb8 32 @@ -3482,7 +3500,7 @@ inject too fast.]]> SEED0 0x0004 - 0x4ba4def0 + 0xde8898d 32 diff --git a/precursors/soc_csr.bin b/precursors/soc_csr.bin index 6fd3b420f..055ea814d 100755 Binary files a/precursors/soc_csr.bin and b/precursors/soc_csr.bin differ diff --git a/tools/sign_image.py b/tools/sign_image.py index 221b652ba..c0b68489b 100755 --- a/tools/sign_image.py +++ b/tools/sign_image.py @@ -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/xtask/src/main.rs b/xtask/src/main.rs index 153efea00..c5713887b 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,26 @@ 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(), + ]).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(()) }