Merge branch 'bunnie-dev' into main

This commit is contained in:
bunnie 2021-07-13 00:48:12 +08:00
commit 135cffcb16
39 changed files with 937 additions and 149 deletions

2
Cargo.lock generated
View file

@ -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",

View file

@ -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]

49
loader/Cargo.lock generated
View file

@ -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]]

View file

@ -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"

View file

@ -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

20
loader/sha2/Cargo.toml Normal file
View file

@ -0,0 +1,20 @@
[package]
name = "sha2"
version = "0.9.5"
authors = ["bunnie <bunnie@kosagi.com>"]
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 = []

148
loader/sha2/src/lib.rs Normal file
View file

@ -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<u32>,
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>) {
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 &reg 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);

View file

@ -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

BIN
loader/src/font6x12.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

4
loader/src/fonts.rs Normal file → Executable file
View file

@ -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;

0
loader/src/fonts/bold.rs Normal file → Executable file
View file

0
loader/src/fonts/emoji.rs Normal file → Executable file
View file

0
loader/src/fonts/hanzi.rs Normal file → Executable file
View file

0
loader/src/fonts/regular.rs Normal file → Executable file
View file

0
loader/src/fonts/small.rs Normal file → Executable file
View file

View file

@ -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))

View file

@ -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 {

379
loader/src/secboot.rs Executable file
View file

@ -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<u32>,
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<u32>,
}
#[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::<u32>()) 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
}

View file

@ -3,7 +3,7 @@
<device schemaVersion="1.1" xmlns:xs="http://www.w3.org/2001/XMLSchema-instance" xs:noNamespaceSchemaLocation="CMSIS-SVD.xsd" >
<vendor>litex</vendor>
<name>SOC</name>
<description><![CDATA[Litex SoC 2021-07-11 04:33:17]]></description>
<description><![CDATA[Litex SoC 2021-07-12 23:54:59]]></description>
<addressUnitBits>8</addressUnitBits>
<width>32</width>
@ -433,11 +433,27 @@ configure as output for the value to appear on the pin]]></description>
</field>
</fields>
</register>
<register>
<name>USBDISABLE</name>
<description><![CDATA[When set to ``1``, USB debug is limited by remapping all wishbone request
addresses to 0x8000_0000]]></description>
<addressOffset>0x001c</addressOffset>
<resetValue>0x00</resetValue>
<size>32</size>
<fields>
<field>
<name>usbdisable</name>
<msb>0</msb>
<bitRange>[0:0]</bitRange>
<lsb>0</lsb>
</field>
</fields>
</register>
<register>
<name>EV_STATUS</name>
<description><![CDATA[This register contains the current raw level of the event7 event trigger.
Writes to this register have no effect.]]></description>
<addressOffset>0x001c</addressOffset>
<addressOffset>0x0020</addressOffset>
<resetValue>0x00</resetValue>
<size>32</size>
<fields>
@ -503,7 +519,7 @@ Writes to this register have no effect.]]></description>
<name>EV_PENDING</name>
<description><![CDATA[When a event7 event occurs, the corresponding bit will be set in this register.
To clear the Event, set the corresponding bit in this register.]]></description>
<addressOffset>0x0020</addressOffset>
<addressOffset>0x0024</addressOffset>
<resetValue>0x00</resetValue>
<size>32</size>
<fields>
@ -577,7 +593,7 @@ edge.]]></description>
<name>EV_ENABLE</name>
<description><![CDATA[This register enables the corresponding event7 events. Write a ``0`` to this
register to disable individual events.]]></description>
<addressOffset>0x0024</addressOffset>
<addressOffset>0x0028</addressOffset>
<resetValue>0x00</resetValue>
<size>32</size>
<fields>
@ -642,7 +658,7 @@ register to disable individual events.]]></description>
</registers>
<addressBlock>
<offset>0</offset>
<size>0x28</size>
<size>0x2c</size>
<usage>registers</usage>
</addressBlock>
<interrupt>
@ -1222,10 +1238,10 @@ register to disable individual events.]]></description>
<register>
<name>GIT_GITREV</name>
<description><![CDATA[First 32-bits of the git revision. This documentation was built from git rev
``a27f1fe4``, so this value is 2726240228, which should be enough to check out
``ab8658b6``, so this value is 2877708470, which should be enough to check out
the exact git version used to build this firmware.]]></description>
<addressOffset>0x0014</addressOffset>
<resetValue>0xa27f1fe4</resetValue>
<resetValue>0xab8658b6</resetValue>
<size>32</size>
<fields>
<field>
@ -1242,7 +1258,7 @@ the exact git version used to build this firmware.]]></description>
is ``1``, then the repository this was built from has one additional commit
beyond the tag indicated in `MAJOR`, `MINOR`, and `REVISION`.]]></description>
<addressOffset>0x0018</addressOffset>
<resetValue>0x39</resetValue>
<resetValue>0x3e</resetValue>
<size>32</size>
<fields>
<field>
@ -1499,14 +1515,32 @@ register to disable individual events.]]></description>
<bitRange>[0:0]</bitRange>
<lsb>0</lsb>
<description><![CDATA[When set to ``1``, permanently add a strike-through on the top of the screen.
Cannot be cleared, except by a full reset.]]></description>
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.]]></description>
</field>
</fields>
</register>
<register>
<name>DEVSTATUS</name>
<description><![CDATA[Reads back as ``1`` if a devboot was set anywhere along the boot chain. This is
a read-only register and reflects ground truth.]]></description>
<addressOffset>0x001c</addressOffset>
<resetValue>0x00</resetValue>
<size>32</size>
<fields>
<field>
<name>devstatus</name>
<msb>0</msb>
<bitRange>[0:0]</bitRange>
<lsb>0</lsb>
</field>
</fields>
</register>
</registers>
<addressBlock>
<offset>0</offset>
<size>0x1c</size>
<size>0x20</size>
<usage>registers</usage>
</addressBlock>
</peripheral>
@ -3467,7 +3501,7 @@ inject too fast.]]></description>
<name>SEED1</name>
<description><![CDATA[Bits 32-63 of `SEED_SEED`. Seed used for the build]]></description>
<addressOffset>0x0000</addressOffset>
<resetValue>0x657b4b20</resetValue>
<resetValue>0x2b72d267</resetValue>
<size>32</size>
<fields>
<field>
@ -3482,7 +3516,7 @@ inject too fast.]]></description>
<name>SEED0</name>
<description><![CDATA[Bits 0-31 of `SEED_SEED`.]]></description>
<addressOffset>0x0004</addressOffset>
<resetValue>0x4ba4def0</resetValue>
<resetValue>0x2d8ab78</resetValue>
<size>32</size>
<fields>
<field>
@ -5847,6 +5881,13 @@ savings)]]></description>
<lsb>3</lsb>
<description><![CDATA[Select SHA512/256 IV constants when set to `1`]]></description>
</field>
<field>
<name>reset</name>
<msb>4</msb>
<bitRange>[4:4]</bitRange>
<lsb>4</lsb>
<description><![CDATA[Resets the hardware. Power must be on for this to take effect.]]></description>
</field>
</fields>
</register>
<register>
@ -6241,52 +6282,59 @@ in bits]]></description>
<size>32</size>
<fields>
<field>
<name>read_count</name>
<msb>8</msb>
<bitRange>[8:0]</bitRange>
<name>reset_status</name>
<msb>0</msb>
<bitRange>[0:0]</bitRange>
<lsb>0</lsb>
<description><![CDATA[when set, the block is undergoing a soft reset]]></description>
</field>
<field>
<name>read_count</name>
<msb>9</msb>
<bitRange>[9:1]</bitRange>
<lsb>1</lsb>
<description><![CDATA[read pointer]]></description>
</field>
<field>
<name>write_count</name>
<msb>17</msb>
<bitRange>[17:9]</bitRange>
<lsb>9</lsb>
<msb>18</msb>
<bitRange>[18:10]</bitRange>
<lsb>10</lsb>
<description><![CDATA[write pointer]]></description>
</field>
<field>
<name>read_error</name>
<msb>18</msb>
<bitRange>[18:18]</bitRange>
<lsb>18</lsb>
<msb>19</msb>
<bitRange>[19:19]</bitRange>
<lsb>19</lsb>
<description><![CDATA[read error occurred]]></description>
</field>
<field>
<name>write_error</name>
<msb>19</msb>
<bitRange>[19:19]</bitRange>
<lsb>19</lsb>
<msb>20</msb>
<bitRange>[20:20]</bitRange>
<lsb>20</lsb>
<description><![CDATA[write error occurred]]></description>
</field>
<field>
<name>almost_full</name>
<msb>20</msb>
<bitRange>[20:20]</bitRange>
<lsb>20</lsb>
<msb>21</msb>
<bitRange>[21:21]</bitRange>
<lsb>21</lsb>
<description><![CDATA[almost full]]></description>
</field>
<field>
<name>almost_empty</name>
<msb>21</msb>
<bitRange>[21:21]</bitRange>
<lsb>21</lsb>
<msb>22</msb>
<bitRange>[22:22]</bitRange>
<lsb>22</lsb>
<description><![CDATA[almost empty]]></description>
</field>
<field>
<name>running</name>
<msb>22</msb>
<bitRange>[22:22]</bitRange>
<lsb>22</lsb>
<msb>23</msb>
<bitRange>[23:23]</bitRange>
<lsb>23</lsb>
<description><![CDATA[hash engine is running and controls are locked out]]></description>
</field>
</fields>
@ -6946,7 +6994,7 @@ of the PLL]]></description>
<memoryRegion>
<name>SHA512</name>
<baseAddress>0xE0002000</baseAddress>
<size>0x00000008</size>
<size>0x00000004</size>
</memoryRegion>
<memoryRegion>
<name>ENGINE</name>

Binary file not shown.

View file

@ -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);
}

View file

@ -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",

20
services/graphics-server/src/fontmap.rs Normal file → Executable file
View file

@ -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;

View file

@ -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,

View file

@ -523,8 +523,33 @@ impl Llio {
Err(xous::Error::InternalError)
}
}
pub fn debug_usb_unlocked(&self) -> Result<bool, xous::Error> {
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<bool>) -> 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 {

View file

@ -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<ScalarCallback>; 32] = [None; 32];
let mut gpio_cb_conns: [Option<ScalarCallback>; 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();

View file

@ -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,
];

View file

@ -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<Option<String::<1024>>, 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))
}
}

View file

@ -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();
}

View file

@ -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.

View file

@ -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)

View file

@ -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:

View file

@ -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<dyn std::error::Error>;
@ -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::<u8>::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(())
}