diff --git a/Cargo.lock b/Cargo.lock index c26864b5d..7a9e3cd31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1621,15 +1621,25 @@ dependencies = [ name = "root-keys" version = "0.1.0" dependencies = [ + "aes-xous", "blowfish", "cipher", + "curve25519-dalek", + "digest", + "ed25519-dalek", + "engine-25519", + "engine-sha512", "gam", + "graphics-server", + "hex", "locales", "log", "log-server", "num-derive", "num-traits", + "rand_core 0.5.1", "rkyv 0.4.3", + "sha2", "susres", "ticktimer-server", "trng", diff --git a/services/engine-sha512/src/lib.rs b/services/engine-sha512/src/lib.rs index fb2edc2e1..847ec2ebf 100644 --- a/services/engine-sha512/src/lib.rs +++ b/services/engine-sha512/src/lib.rs @@ -285,6 +285,7 @@ impl FixedOutputDirty for Sha512 { let returned: Sha2Finalize = buf.to_original().expect("couldn't decode return buffer"); match returned.result { Sha2Result::Sha512Result(s) => { + log::info!("bits hashed: {}", self.length); if self.length != returned.length_in_bits.expect("hardware did not return a length field!") { panic!("Sha512 hardware did not hash as many bits as we had expected!") } diff --git a/services/gam/src/modal.rs b/services/gam/src/modal.rs index b04c03df8..18eabfd73 100644 --- a/services/gam/src/modal.rs +++ b/services/gam/src/modal.rs @@ -370,14 +370,16 @@ impl ActionApi for TextEntry { } '\u{8}' => { // backspace // coded in a conservative manner to avoid temporary allocations that can leave the plaintext on the stack - let mut temp_str = String::<256>::from_str(self.action_payload.0.as_str().unwrap()); - let cur_len = temp_str.as_str().unwrap().chars().count(); - let mut c_iter = temp_str.as_str().unwrap().chars(); - self.action_payload.0.clear(); - for _ in 0..cur_len-1 { - self.action_payload.0.push(c_iter.next().unwrap()).unwrap(); + if self.action_payload.0.len() > 0 { // don't backspace if we have no string. + let mut temp_str = String::<256>::from_str(self.action_payload.0.as_str().unwrap()); + let cur_len = temp_str.as_str().unwrap().chars().count(); + let mut c_iter = temp_str.as_str().unwrap().chars(); + self.action_payload.0.clear(); + for _ in 0..cur_len-1 { + self.action_payload.0.push(c_iter.next().unwrap()).unwrap(); + } + temp_str.volatile_clear(); } - temp_str.volatile_clear(); } _ => { // text entry self.action_payload.0.push(k).expect("ran out of space storing password"); diff --git a/services/graphics-server/src/api.rs b/services/graphics-server/src/api.rs index 09dce96d0..7e7423cac 100644 --- a/services/graphics-server/src/api.rs +++ b/services/graphics-server/src/api.rs @@ -23,6 +23,7 @@ pub use shapes::*; pub mod text; pub use text::*; + use hash32::{Hash, Hasher}; //////////////// IPC APIs @@ -87,6 +88,10 @@ pub(crate) enum Opcode { /// permanently turns on the Devboot mark Devboot, + /// bulk read for signature verifications + BulkReadFonts, + RestartBulkRead, + /// SuspendResume callback SuspendResume, @@ -112,4 +117,25 @@ pub struct ClipObject { pub struct TokenClaim { pub token: Option<[u32; 4]>, pub name: xous_ipc::String::<128>, +} + +/// the buffer length of this equal to the internal length passed by the +/// engine-sha512 implementation times 2 (a small amount of overhead is required +/// out of an even 4096 page for bookkeeping). We could make this a neat power of 2, +/// but then you'd end up doing an extra memory message for the overhead bits that +/// are left over. +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] +pub struct BulkRead { + pub buf: [u8; 7936], + pub from_offset: u32, + pub len: u32, // used to return the length read out of the font map +} +impl BulkRead { + pub fn default() -> BulkRead { + BulkRead { + buf: [0; 7936], + from_offset: 0, + len: 7936, + } + } } \ No newline at end of file diff --git a/services/graphics-server/src/lib.rs b/services/graphics-server/src/lib.rs index 55928d02f..469b729cf 100644 --- a/services/graphics-server/src/lib.rs +++ b/services/graphics-server/src/lib.rs @@ -7,11 +7,16 @@ use blitstr_ref as blitstr; pub use blitstr::{ClipRect, Cursor, GlyphStyle}; pub mod op; +pub mod fontmap; +pub use fontmap::*; + use api::Opcode; // if you prefer to map the api into your local namespace use xous::{send_message, Message}; use xous_ipc::Buffer; use num_traits::ToPrimitive; +pub use api::BulkRead; +pub use api::ArchivedBulkRead; #[derive(Debug)] pub struct Gfx { conn: xous::CID, @@ -24,6 +29,7 @@ impl Gfx { conn, }) } + pub fn conn(&self) -> xous::CID {self.conn} pub fn draw_line(&self, line: Line) -> Result<(), xous::Error> { send_message(self.conn, @@ -159,6 +165,18 @@ impl Gfx { ena, 0, 0, 0,) ).map(|_| ()) } + + /// instead of implementing the read in the library, we had the raw opcode to the caller + /// this allows the caller to re-use the bulk read data structure across multiple reads + /// instead of it being re-allocated and re-init'd every single call + pub fn bulk_read_fontmap_op(&self) -> u32 {Opcode::BulkReadFonts.to_u32().unwrap()} + /// the bulk read auto-increments a pointer on the gfx server, so this message is necessary + /// to reset the pointer to 0. + pub fn bulk_read_restart(&self) { + send_message(self.conn, + Message::new_blocking_scalar(Opcode::RestartBulkRead.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't reset bulk read"); + } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/graphics-server/src/main.rs b/services/graphics-server/src/main.rs index c4e3083f7..c7313a52a 100644 --- a/services/graphics-server/src/main.rs +++ b/services/graphics-server/src/main.rs @@ -19,20 +19,21 @@ use blitstr::GlyphStyle; use num_traits::FromPrimitive; use xous_ipc::Buffer; -use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack}; +use xous::{msg_scalar_unpack, msg_blocking_scalar_unpack, MemoryRange}; mod fontmap; +use api::{BulkRead, ArchivedBulkRead}; fn draw_boot_logo(display: &mut XousDisplay) { display.blit_screen(poweron::LOGO_MAP); } #[cfg(target_os = "none")] -fn map_fonts() { +fn map_fonts() -> MemoryRange { log::trace!("mapping fonts"); // this maps an extra page if the total length happens to fall on a 4096-byte boundary, but this is ok // because the reserved area is much larger - let fontlen: u32 = ((fontmap::FONT_TOTAL_LEN as u32) & 0xFFFF_F000) + 0x1000; + let fontlen: u32 = ((fontmap::FONT_TOTAL_LEN as u32 + 8) & 0xFFFF_F000) + 0x1000; log::trace!("requesting map of length 0x{:08x} at 0x{:08x}", fontlen, fontmap::FONT_BASE); let fontregion = xous::syscall::map_memory( xous::MemoryAddress::new(fontmap::FONT_BASE), @@ -48,11 +49,22 @@ fn map_fonts() { blitstr::map_font(blitstr::GlyphData::Regular((fontregion.as_ptr() as usize + fontmap::REGULAR_OFFSET) as usize)); blitstr::map_font(blitstr::GlyphData::Small((fontregion.as_ptr() as usize + fontmap::SMALL_OFFSET) as usize)); blitstr::map_font(blitstr::GlyphData::Bold((fontregion.as_ptr() as usize + fontmap::BOLD_OFFSET) as usize)); + + fontregion } #[cfg(not(target_os = "none"))] -fn map_fonts() { +fn map_fonts() -> MemoryRange { // does nothing + let fontlen: u32 = ((fontmap::FONT_TOTAL_LEN as u32) & 0xFFFF_F000) + 0x1000 + 8; + let fontregion = xous::syscall::map_memory( + None, + None, + fontlen as usize, + xous::MemoryFlags::R, + ).expect("couldn't map dummy memory for fonts"); + + fontregion } #[xous::xous_main] @@ -65,7 +77,8 @@ fn xmain() -> ! { let xns = xous_names::XousNames::new().unwrap(); // these connections should be established: // - GAM - let sid = xns.register_name(api::SERVER_NAME_GFX, Some(1)).expect("can't register server"); + // - keyrom (for verifying font maps) + let sid = xns.register_name(api::SERVER_NAME_GFX, Some(2)).expect("can't register server"); log::trace!("Server listening on address {:?}", sid); // Create a new monochrome simulator display. @@ -73,7 +86,7 @@ fn xmain() -> ! { draw_boot_logo(&mut display); - map_fonts(); + let fontregion = map_fonts(); let mut use_sleep_note = true; if false { @@ -101,6 +114,7 @@ fn xmain() -> ! { let sr_cid = xous::connect(sid).expect("couldn't create suspend callback connection"); let mut susres = susres::Susres::new(&xns, Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object"); + let mut bulkread = BulkRead::default(); // holding buffer for bulk reads; wastes ~8k when not in use, but saves a lot of copy/init for each iteration of the read loop { let mut msg = xous::receive_message(sid).unwrap(); log::trace!("Message: {:?}", msg); @@ -452,6 +466,34 @@ fn xmain() -> ! { if ena != 0 { display.set_devboot(true); } else { display.set_devboot(false); } }), + Some(Opcode::RestartBulkRead) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + bulkread.from_offset = 0; + xous::return_scalar(msg.sender, 0).expect("couldn't ack that bulk read pointer was reset"); + }), + Some(Opcode::BulkReadFonts) => { + let fontlen = fontmap::FONT_TOTAL_LEN as u32 + 8; + let mut buf = unsafe{ Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + //let mut bulkread = buf.as_flat::().unwrap(); // try to skip the copy/init step by using a persistent structure + let fontslice = fontregion.as_slice::(); + assert!(fontlen <= fontslice.len() as u32); + if bulkread.from_offset >= fontlen { + log::error!("BulkReadFonts attempt to read out of bound on the font area; ignoring!"); + continue + } + let readlen = if bulkread.from_offset + bulkread.buf.len() as u32 > fontlen { + // returns what is readable of the last bit; anything longer than the fontlen is undefined/invalid + fontlen as usize - bulkread.from_offset as usize + } else { + bulkread.buf.len() + }; + for (&src, dst) in fontslice[bulkread.from_offset as usize .. bulkread.from_offset as usize + readlen].iter() + .zip(bulkread.buf.iter_mut()) { + *dst = src; + } + bulkread.len = readlen as u32; + bulkread.from_offset += readlen as u32; + buf.replace(bulkread).unwrap(); + } Some(Opcode::Quit) => break, None => {log::error!("received opcode scalar that is not handled");} } diff --git a/services/root-keys/Cargo.toml b/services/root-keys/Cargo.toml index cf8989ba3..5ff4fb0e2 100644 --- a/services/root-keys/Cargo.toml +++ b/services/root-keys/Cargo.toml @@ -19,12 +19,37 @@ num-derive = {version = "0.3", default-features = false} num-traits = {version = "0.2", default-features = false} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} +# bcrypt cipher = "0.3" blowfish = { version = "0.8", features = ["bcrypt"] } -gam = {path = "../gam"} # for direct password modals +# password modals - keep them in this crate to minimize plaintext password manipulations +gam = {path = "../gam"} locales = {path = "../../locales"} +# to access font maps for signing verification +graphics-server = {path = "../graphics-server"} + +# private keys +engine-sha512 = {path="../engine-sha512"} +digest = "0.9" +aes-xous={path="../aes"} +engine-25519 = {path="../engine-25519"} +# hardware acceleration adaptations are inserted into a fork of the main branch. +rand_core = "0.5" +hex = {version = "0.4.3", default-features = false, features = []} +sha2 = {version = "0.9.5", default-features = false, features = []} +[dependencies.curve25519-dalek] +version = "3.1.0" # note this is patched to our fork in ./Cargo.toml +default-features = false +features = ["u32_backend", "betrusted"] + +[dependencies.ed25519-dalek] +version = "1.0.1" +#path = "../../../ed25519-dalek" +default-features = false +features = ["u32_backend", "rand"] + [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index e9add4d4b..aa8ddaa22 100755 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -1,20 +1,39 @@ +use gam::FONT_TOTAL_LEN; use ticktimer_server::Ticktimer; use utralib::generated::*; use crate::api::*; use core::num::NonZeroUsize; use num_traits::*; +use gam::modal::{Modal, Slider}; + use crate::bcrypt::*; use crate::PasswordType; -use gam::modal::{Modal, Slider}; +use core::convert::TryInto; +use ed25519_dalek::{Keypair, Signature, Signer}; +use engine_sha512::*; +use digest::Digest; +use graphics_server::BulkRead; +use core::mem::size_of; // TODO: add hardware acceleration for BCRYPT so we can hit the OWASP target without excessive UX delay const BCRYPT_COST: u32 = 7; // 10 is the minimum recommended by OWASP; takes 5696 ms to verify @ 10 rounds; 804 ms to verify 7 rounds -struct KeyRomLocations {} +/// Size of the total area allocated for signatures. It is equal to the size of one FLASH sector, which is the smallest +/// increment that can be erased. +const SIGBLOCK_SIZE: u32 = 0x1000; + +#[repr(C)] +struct SignatureInFlash { + pub version: u32, + pub signed_len: u32, + pub signature: [u8; 64], +} + +struct KeyRomLocs {} #[allow(dead_code)] -impl KeyRomLocations { +impl KeyRomLocs { const FPGA_KEY: u8 = 0x00; const SELFSIGN_PRIVKEY: u8 = 0x08; const SELFSIGN_PUBKEY: u8 = 0x10; @@ -22,8 +41,8 @@ impl KeyRomLocations { const THIRDPARTY_PUBKEY: u8 = 0x20; const USER_KEY: u8 = 0x28; const PEPPER: u8 = 0xf8; - const FPGA_REV: u8 = 0xfc; - const LOADER_REV: u8 = 0xfd; + const FPGA_MIN_REV: u8 = 0xfc; + const LOADER_MIN_REV: u8 = 0xfd; const CONFIG: u8 = 0xff; } @@ -40,7 +59,8 @@ impl KeyField { } } pub fn ms(&self, value: u32) -> u32 { - (value & self.mask) << self.offset + let ms_le = (value & self.mask) << self.offset; + ms_le.to_be() } } #[allow(dead_code)] @@ -53,16 +73,20 @@ pub(crate) mod keyrom_config { pub const ANTIROLLFORW_ENA: KeyField = KeyField::new(1, 18); pub const FORWARD_REV_LIMIT: KeyField = KeyField::new(4, 19); pub const FORWARD_MINOR_LIMIT: KeyField = KeyField::new(4, 23); - pub const INITIALIZED: KeyField = KeyField::new(4, 27); + pub const INITIALIZED: KeyField = KeyField::new(1, 27); } -#[repr(C)] +/// This structure is mapped into the password cache page and can be zero-ized at any time +/// we avoid using fancy Rust structures because everything has to "make sense" after a forced zero-ization +/// The "password" here is generated as follows: +/// `user plaintext (up to first 72 bytes) -> bcrypt (24 bytes) -> sha512trunc256 -> [u8; 32]` +/// The final sha512trunc256 expansion is because we will use this to XOR against secret keys stored in +/// the KEYROM that may be up to 256 bits in length. For shorter keys, the hashed password is simply truncated. + #[repr(C)] struct PasswordCache { - // this structure is mapped into the password cache page and can be zero-ized at any time - // we avoid using fancy Rust structures because everything has to "make sense" after a forced zero-ization - hashed_boot_pw: [u8; 24], + hashed_boot_pw: [u8; 32], hashed_boot_pw_valid: u32, // non-zero for valid - hashed_update_pw: [u8; 24], + hashed_update_pw: [u8; 32], hashed_update_pw_valid: u32, } @@ -82,6 +106,7 @@ pub(crate) struct RootKeys { susres: susres::Susres, // for disabling suspend/resume trng: trng::Trng, gam: gam::Gam, // for raising UX elements directly + gfx: graphics_server::Gfx, // for reading out font planes for signing verification } impl RootKeys { @@ -147,6 +172,7 @@ impl RootKeys { susres: susres::Susres::new_without_hook(&xns).expect("couldn't connect to susres without hook"), trng: trng::Trng::new(&xns).expect("couldn't connect to TRNG server"), gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"), + gfx: graphics_server::Gfx::new(&xns).expect("couldn't connect to gfx"), }; keys @@ -247,17 +273,24 @@ impl RootKeys { let elapsed = timer.elapsed_ms() - start_time; log::info!("bcrypt cost: {} time: {}ms", BCRYPT_COST, elapsed); // benchmark to figure out how to set cost parameter + // expand the 24-byte (192-bit) bcrypt result into 256 bits, so we can use it directly as XOR key material + // against 256-bit AES and curve25519 keys + // for such a small hash, software is the most performant choice + let mut hasher = engine_sha512::Sha512Trunc256::new(Some(engine_sha512::FallbackStrategy::SoftwareOnly)); + hasher.update(hashed_password); + let digest = hasher.finalize(); + let pcache_ptr: *mut PasswordCache = self.pass_cache.as_mut_ptr() as *mut PasswordCache; unsafe { match pw_type { PasswordType::Boot => { - for (&src, dst) in pw.as_bytes().iter().zip((*pcache_ptr).hashed_boot_pw.iter_mut()) { + for (&src, dst) in digest.iter().zip((*pcache_ptr).hashed_boot_pw.iter_mut()) { *dst = src; } (*pcache_ptr).hashed_boot_pw_valid = 1; } PasswordType::Update => { - for (&src, dst) in pw.as_bytes().iter().zip((*pcache_ptr).hashed_update_pw.iter_mut()) { + for (&src, dst) in digest.iter().zip((*pcache_ptr).hashed_update_pw.iter_mut()) { *dst = src; } (*pcache_ptr).hashed_update_pw_valid = 1; @@ -301,14 +334,14 @@ impl RootKeys { let sensitive_slice = self.sensitive_data.as_slice::(); let mut key: [u8; 16] = [0; 16]; for (word, &keyword) in key.chunks_mut(4).into_iter() - .zip(sensitive_slice[KeyRomLocations::PEPPER as usize..(KeyRomLocations::PEPPER + 4) as usize].iter()) { + .zip(sensitive_slice[KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::()*8)].iter()) { for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { *dst = byte; } } key } else { - self.read_key_128(KeyRomLocations::PEPPER) + self.read_key_128(KeyRomLocs::PEPPER) } } @@ -320,7 +353,7 @@ impl RootKeys { pub fn get_ux_password_type(&self) -> Option {self.cur_password_type} pub fn is_initialized(&mut self) -> bool { - self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, KeyRomLocations::CONFIG as u32); + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, KeyRomLocs::CONFIG as u32); let config = self.keyrom.rf(utra::keyrom::DATA_DATA); if config & keyrom_config::INITIALIZED.ms(1) != 0 { true @@ -343,7 +376,7 @@ impl RootKeys { } // provision the pepper - for keyword in sensitive_slice[KeyRomLocations::PEPPER as usize..(KeyRomLocations::PEPPER + 4) as usize].iter_mut() { + for keyword in sensitive_slice[KeyRomLocs::PEPPER as usize..KeyRomLocs::PEPPER as usize + 128/(size_of::()*8)].iter_mut() { *keyword = self.trng.get_u32().expect("couldn't get random number"); } } @@ -371,12 +404,196 @@ impl RootKeys { // kick the progress bar to indicate we've entered the routine update_progress(1, progress_modal, progress_action); + let keypair: Keypair = Keypair::generate(&mut self.trng); + // pub key is easy, no need to encrypt + let public_key: [u8; ed25519_dalek::PUBLIC_KEY_LENGTH] = keypair.public.to_bytes(); + { // scope sensitive_slice narrowly, as it borrows *self mutably, and can mess up later calls that borrow an immutable self + // sensitive_slice is our staging area for the new keyrom contents + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + for (src, dst) in public_key.chunks(4).into_iter() + .zip(sensitive_slice[KeyRomLocs::SELFSIGN_PUBKEY as usize..KeyRomLocs::SELFSIGN_PUBKEY as usize + 256/(size_of::()*8)].iter_mut()) { + *dst = u32::from_be_bytes(src.try_into().unwrap()) + } + } + + // extract the update password key from the cache, and apply it to the private key + let pcache: &PasswordCache = unsafe{&*(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + log::info!("cached boot passwords {:x?}", pcache.hashed_boot_pw); + log::info!("cached update password: {:x?}", pcache.hashed_update_pw); + // private key must XOR with password before storing + let mut private_key_enc: [u8; ed25519_dalek::SECRET_KEY_LENGTH] = [0; ed25519_dalek::SECRET_KEY_LENGTH]; + // we do this from to try and avoid making as few copies of the hashed password as possible + for (dst, (plain, key)) in + private_key_enc.iter_mut() + .zip(keypair.secret.to_bytes().iter() + .zip(pcache.hashed_update_pw.iter())) { + *dst = plain ^ key; + } + + // store the private key to the keyrom staging area + { + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + for (src, dst) in private_key_enc.chunks(4).into_iter() + .zip(sensitive_slice[KeyRomLocs::SELFSIGN_PRIVKEY as usize..KeyRomLocs::SELFSIGN_PRIVKEY as usize + 256/(size_of::()*8)].iter_mut()) { + *dst = u32::from_be_bytes(src.try_into().unwrap()) + } + } + + update_progress(10, progress_modal, progress_action); + + // generate and store a root key (aka boot key), this is what is unlocked by the "boot password" + // ironically, it's a "lower security" key because it just acts as a gatekeeper to further + // keys that would have a stronger password applied to them, based upon the importance of the secret + // think of this more as a user PIN login confirmation, than as a significant cryptographic event + let mut boot_key_enc: [u8; 32] = [0; 32]; + for (dst, key) in + boot_key_enc.chunks_mut(4).into_iter() + .zip(pcache.hashed_boot_pw.chunks(4).into_iter()) { + let key_word = self.trng.get_u32().unwrap().to_be_bytes(); + // just unroll this loop, it's fast and easy enough + (*dst)[0] = key[0] ^ key_word[0]; + (*dst)[1] = key[1] ^ key_word[1]; + (*dst)[2] = key[2] ^ key_word[2]; + (*dst)[3] = key[3] ^ key_word[3]; + // also note that interestingly, we don't have to XOR it with the hashed boot password -- + // this key isn't used by this routine, just initialized, so really, it only matters to + // XOR it with the password when you use it the first time to encrypt something. + } + + // store the boot key to the keyrom staging area + { + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + for (src, dst) in private_key_enc.chunks(4).into_iter() + .zip(sensitive_slice[KeyRomLocs::USER_KEY as usize..KeyRomLocs::USER_KEY as usize + 256/(size_of::()*8)].iter_mut()) { + *dst = u32::from_be_bytes(src.try_into().unwrap()) + } + } + + update_progress(20, progress_modal, progress_action); + + // sign the loader + let (loader_sig, loader_len) = self.sign_loader(&keypair); + update_progress(30, progress_modal, progress_action); + + // sign the kernel + let (kernel_sig, kernel_len) = self.sign_kernel(&keypair); + update_progress(40, progress_modal, progress_action); + + // encrypt the FPGA key using the update password. in an un-init system, it is provided to us in plaintext format + // e.g. in the case that we're doing a BBRAM boot (eFuse flow would give us a 0's key and we'd later on set it) + self.debug_print_key(KeyRomLocs::FPGA_KEY as usize, 256, "FPGA key before encryption: "); + { + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + for (word, key_word) in sensitive_slice[KeyRomLocs::FPGA_KEY as usize..KeyRomLocs::FPGA_KEY as usize + 256/(size_of::()*8)].iter_mut() + .zip(pcache.hashed_update_pw.chunks(4).into_iter()) { + *word = *word ^ u32::from_be_bytes(key_word.try_into().unwrap()); + } + } + update_progress(50, progress_modal, progress_action); + + // set the "init" bit in the staging area + { + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, KeyRomLocs::CONFIG as u32); + let config = self.keyrom.rf(utra::keyrom::DATA_DATA); + log::info!("config on device {:x}", config); + log::info!("cached copy before mod {:x}", sensitive_slice[KeyRomLocs::CONFIG as usize]); + log::info!("mask shift computation: {:x}", keyrom_config::INITIALIZED.ms(1)); + sensitive_slice[KeyRomLocs::CONFIG as usize] |= keyrom_config::INITIALIZED.ms(1); + log::info!("cached copy after mod {:x}", sensitive_slice[KeyRomLocs::CONFIG as usize]); + } + update_progress(60, progress_modal, progress_action); + + log::info!("Self private key: {:x?}", keypair.secret.to_bytes()); + log::info!("Self public key: {:x?}", keypair.public.to_bytes()); + self.debug_staging(); + // compute the keyrom patch set for the bitstream + // at this point the KEYROM as replicated in sensitive_slice should have all its assets in place // finalize the progress bar on exit -- always leave at 100% update_progress(100, progress_modal, progress_action); true } + + fn debug_staging(&self) { + self.debug_print_key(KeyRomLocs::FPGA_KEY as usize, 256, "FPGA key: "); + self.debug_print_key(KeyRomLocs::SELFSIGN_PRIVKEY as usize, 256, "Self private key: "); + self.debug_print_key(KeyRomLocs::SELFSIGN_PUBKEY as usize, 256, "Self public key: "); + self.debug_print_key(KeyRomLocs::DEVELOPER_PUBKEY as usize, 256, "Dev public key: "); + self.debug_print_key(KeyRomLocs::THIRDPARTY_PUBKEY as usize, 256, "3rd party public key: "); + self.debug_print_key(KeyRomLocs::USER_KEY as usize, 256, "Boot key: "); + self.debug_print_key(KeyRomLocs::PEPPER as usize, 128, "Pepper: "); + self.debug_print_key(KeyRomLocs::CONFIG as usize, 32, "Config (as BE): "); + } + fn debug_print_key(&self, offset: usize, num_bits: usize, name: &str) { + use core::fmt::Write; + let mut debugstr = xous_ipc::String::<4096>::new(); + let sensitive_slice = self.sensitive_data.as_slice_mut::(); + write!(debugstr, "{}", name).unwrap(); + for word in sensitive_slice[offset .. offset as usize + num_bits/(size_of::()*8)].iter() { + for byte in word.to_be_bytes().iter() { + write!(debugstr, "{:02x}", byte).unwrap(); + } + } + log::info!("{}", debugstr); + } + + pub fn sign_loader(&mut self, signing_key: &Keypair) -> (Signature, u32) { + let loader_len = + xous::LOADER_CODE_LEN + - SIGBLOCK_SIZE + + graphics_server::fontmap::FONT_TOTAL_LEN as u32 + + 8; // two u32 words are appended to the end, which repeat the "version" and "length" fields encoded in the signature block + + // this is a huge hash, so, get a hardware hasher, even if it means waiting for it + let mut hasher = engine_sha512::Sha512::new(Some(engine_sha512::FallbackStrategy::WaitForHardware)); + let loader_region = self.loader_code.as_slice::(); + // the loader data starts one page in; the first page is reserved for the signature itself + hasher.update(&loader_region[SIGBLOCK_SIZE as usize..]); + + // now get the font plane data + self.gfx.bulk_read_restart(); // reset the bulk read pointers on the gfx side + let mut bulkread = BulkRead::default(); + let mut buf = xous_ipc::Buffer::into_buf(bulkread).expect("couldn't transform bulkread into aligned buffer"); + // this form of loop was chosen to avoid the multiple re-initializations and copies that would be entailed + // in our usual idiom for pasing buffers around. instead, we create a single buffer, and re-use it for + // every iteration of the loop. + loop { + buf.lend_mut(self.gfx.conn(), self.gfx.bulk_read_fontmap_op()).expect("couldn't do bulkread from gfx"); + let br = buf.as_flat::().unwrap(); + hasher.update(&br.buf[..br.len as usize]); + if br.len != bulkread.buf.len() as u32 { + log::info!("non-full block len: {}", br.len); + } + if br.len < bulkread.buf.len() as u32 { + // read until we get a buffer that's not fully filled + break; + } + } + let digest = hasher.finalize(); + if false { + log::info!("len: {}", loader_len); + log::info!("{:x?}", digest); + // fake hasher for now + let mut hasher = engine_sha512::Sha512::new(Some(engine_sha512::FallbackStrategy::WaitForHardware)); + hasher.update(&loader_region[SIGBLOCK_SIZE as usize..]); + } + (signing_key.sign_prehashed(hasher, None).expect("couldn't sign the loader"), loader_len) + } + + pub fn sign_kernel(&mut self, signing_key: &Keypair) -> (Signature, u32) { + let mut hasher = engine_sha512::Sha512::new(Some(engine_sha512::FallbackStrategy::WaitForHardware)); + let kernel_region = self.kernel.as_slice::(); + // for the kernel length, we can't know/trust the given length in the signature field, so we sign the entire + // length of the region. This will increase the time it takes to verify; however, at the current trend, we'll probably + // use most of the available space for the kernel, so by the time we're done maybe only 10-20% of the space is empty. + let kernel_len = kernel_region.len() - SIGBLOCK_SIZE as usize; + hasher.update(&kernel_region[SIGBLOCK_SIZE as usize ..]); + + (signing_key.sign_prehashed(hasher, None).expect("couldn't sign the kernel"), kernel_len as u32) + } + /// Called by the UX layer at the epilogue of the initialization run. Allows suspend/resume to resume, /// and zero-izes any sensitive data that was created in the process. pub fn finish_key_init(&mut self) { diff --git a/tools/sign_image.py b/tools/sign_image.py index c4298f436..706b4ba1c 100755 --- a/tools/sign_image.py +++ b/tools/sign_image.py @@ -9,6 +9,7 @@ from nacl.encoding import RawEncoder import os.path import binascii +import hashlib DEVKEY_PATH='../devkey/dev.key' SIGNER_VERSION=1 @@ -25,6 +26,10 @@ def blob_sign(source, output, key, defile=False): signing_key = SigningKey(key[-32:], encoder=RawEncoder) signature = signing_key.sign(source, encoder=RawEncoder) + print("signing {} bytes".format(len(source))) + m = hashlib.sha512() + m.update(bytearray(source)) + print("hash of {}".format(m.hexdigest())) with open(output, "wb") as output_f: written = 0