From 8b37303b06f88eaeddee4e16d669738a1306e372 Mon Sep 17 00:00:00 2001 From: bunnie Date: Wed, 5 Jan 2022 11:17:13 +0800 Subject: [PATCH] add a check on correct password entry The rootkey enclave actually doesn't check if your password is correct -- it has no way of knowing because it doesn't know how the keys will be used. Password checking is delegated to the requesting process because also the password retry method and policy depends upon the application, and is a significant amount of UX plumbing (in fact the rootkeys should have less UX plumbing than it has right now - this is something to do in the near future). Add a mechanism in the PDDB to check if a password was entered correctly, and retry if it isn't. Without this, an incorrect password would actually trigger a reformat of the PDDB, since it can't find the system basis structure with a bad password. --- services/pddb/locales/i18n.json | 5 ++ services/pddb/src/backend/hw.rs | 82 ++++++++++++++++- services/pddb/src/main.rs | 107 ++++++++++++++--------- services/root-keys/src/api.rs | 2 + services/root-keys/src/implementation.rs | 6 ++ services/root-keys/src/lib.rs | 7 ++ services/root-keys/src/main.rs | 7 +- 7 files changed, 172 insertions(+), 44 deletions(-) diff --git a/services/pddb/locales/i18n.json b/services/pddb/locales/i18n.json index 5a731228b..afbb93a70 100644 --- a/services/pddb/locales/i18n.json +++ b/services/pddb/locales/i18n.json @@ -19,6 +19,11 @@ "zh": "不", "en-audio": "No" }, + "pddb.badpass": { + "en": "Incorrect password.\n\nTry again?\n", + "zh": "密码错误。 再试一次?", + "en-audio": "Incorrect password. Try again?" + }, "pddb.requestformat": { "en": "The PDDB storage needs\nformatting. This takes\nabout 15 minutes and can't\nbe interrupted.\n\nProceed?\n", "zh": "存储需要格式化。这需要8分钟。继续?", diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index bb3955c6b..c4bc427c4 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -3,7 +3,7 @@ use std::convert::TryInto; use crate::*; use aes_gcm_siv::{Aes256GcmSiv, Nonce, Key, Tag}; use aes_gcm_siv::aead::{Aead, NewAead, Payload}; -use aes::{Aes256, Block}; +use aes::{Aes256, Block, BLOCK_SIZE}; use aes::cipher::{BlockDecrypt, BlockEncrypt, NewBlockCipher, generic_array::GenericArray}; use root_keys::api::AesRootkeyType; use spinor::SPINOR_BULK_ERASE_SIZE; @@ -37,8 +37,10 @@ pub const VPAGE_SIZE: usize = PAGE_SIZE - size_of::() - size_of::() pub(crate) struct StaticCryptoData { /// aes-256 key of the system basis, encrypted with the User0 root key pub(crate) system_key: [u8; AES_KEYSIZE], + /// check data to confirm the password was entered correctly; it is the encryption of the first 128 bits of the salt below. + pub(crate) check_data: [u8; BLOCK_SIZE], /// a pool of fixed data used to pick salts, based on a hash of the basis name - pub(crate) salt_base: [u8; 4064], + pub(crate) salt_base: [u8; 4048], } impl Deref for StaticCryptoData { type Target = [u8]; @@ -444,6 +446,64 @@ impl PddbOs { } self.cipher_ecb = None; } + pub(crate) fn clear_password(&self) { + self.rootkeys.clear_password(AesRootkeyType::User0); + } + pub (crate) fn try_login(&mut self) -> bool { + if self.system_basis_key.is_none() || self.cipher_ecb.is_none() { + let scd = self.static_crypto_data_get(); + let mut system_key: [u8; AES_KEYSIZE] = [0; AES_KEYSIZE]; + let mut blank = true; + for (&src, dst) in scd.system_key.iter().zip(system_key.iter_mut()) { + *dst = src; + if src != 0xFF { + blank = false; + } + } + for block in system_key.chunks_mut(aes::BLOCK_SIZE) { + self.rootkeys.decrypt_block(block.try_into().unwrap()); + } + if !blank { + // form the ECB cipher and check the check data + let cipher = Aes256::new(GenericArray::from_slice(&system_key)); + let mut block = [0u8; BLOCK_SIZE]; + for (&src, dst) in scd.check_data[0..BLOCK_SIZE].iter().zip(block.iter_mut()) { + *dst = src; + } + let ga = GenericArray::from_mut_slice(&mut block); + //log::info!("test block before: {:x?}", ga); + cipher.decrypt_block(ga); + //log::info!("test block after check: {:x?}", ga); + let mut success = true; + let mut checkedlen = 0; + for (&a, &b) in scd.salt_base[0..BLOCK_SIZE].iter().zip(ga.iter()) { + if a != b { + success = false; + } + checkedlen += 1; + } + if checkedlen != BLOCK_SIZE { + success = false; + } + if success { + let mut system_key: [u8; AES_KEYSIZE] = [0; AES_KEYSIZE]; + for (&src, dst) in scd.system_key.iter().zip(system_key.iter_mut()) { + *dst = src; + } + for block in system_key.chunks_mut(aes::BLOCK_SIZE) { + self.rootkeys.decrypt_block(block.try_into().unwrap()); + } + self.system_basis_key = Some(system_key); + self.cipher_ecb = Some(cipher); + } + success + } else { + true // the first password entered is always correct. If you made a typo, nothing we can do about it... + } + } else { + true + } + } fn syskey_ensure(&mut self) { if self.system_basis_key.is_none() { let scd = self.static_crypto_data_get(); @@ -1154,7 +1214,7 @@ impl PddbOs { } for offset in (xous::PDDB_LOC..(xous::PDDB_LOC + PDDB_A_LEN as u32)).step_by(SPINOR_BULK_ERASE_SIZE as usize) { if (offset / SPINOR_BULK_ERASE_SIZE) % 4 == 0 { - log::info!("Initial erase: {}/{}", offset - xous::PDDB_LOC, PDDB_A_LEN as u32 - xous::PDDB_LOC); + log::info!("Initial erase: {}/{}", offset - xous::PDDB_LOC, PDDB_A_LEN as u32); if let Some(modals) = progress { modals.update_progress(offset as u32).expect("couldn't update progress bar"); } @@ -1220,7 +1280,8 @@ impl PddbOs { } let mut crypto_keys = StaticCryptoData { system_key: [0; AES_KEYSIZE], - salt_base: [0; 4064], + check_data: [0; BLOCK_SIZE], + salt_base: [0; 4048], }; if let Some(modals) = progress { modals.update_progress(50).expect("couldn't update progress bar"); @@ -1231,6 +1292,19 @@ impl PddbOs { *dst = src; } self.entropy.borrow_mut().get_slice(&mut crypto_keys.salt_base); + let cipher_ecb = self.cipher_ecb.as_ref().unwrap(); + let mut block = [0u8; BLOCK_SIZE]; + // the test data is just the first 128 bits of the salt base + for (&src, dst) in crypto_keys.salt_base[0..BLOCK_SIZE].iter().zip(block.iter_mut()) { + *dst = src; + } + let ga = GenericArray::from_mut_slice(&mut block); + log::info!("test block before: {:x?}", ga); + cipher_ecb.encrypt_block(ga); + for (&src, dst) in ga.iter().zip(crypto_keys.check_data.iter_mut()) { + *dst = src; + } + log::info!("test block after: {:x?}", crypto_keys.check_data); self.patch_keys(crypto_keys.deref(), 0); if let Some(modals) = progress { modals.update_progress(100).expect("couldn't update progress bar"); diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 8e990c93d..e8be7b595 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -401,6 +401,7 @@ fn xmain() -> ! { let xns = xous_names::XousNames::new().unwrap(); let pddb_sid = xns.register_name(api::SERVER_NAME_PDDB, None).expect("can't register server"); log::trace!("registered with NS -- {:?}", pddb_sid); + let tt = ticktimer_server::Ticktimer::new().unwrap(); log::trace!("ready to accept requests"); @@ -450,57 +451,85 @@ fn xmain() -> ! { log::info!("Got password: {:?}", ret.plaintext_pw); } if pddb_os.rootkeys_initialized() { - log::info!("Attempting to mount the PDDB"); - if let Some(sys_basis) = pddb_os.pddb_mount() { - log::info!("PDDB mount operation finished successfully"); - basis_cache.basis_add(sys_basis); - } else { - log::debug!("PDDB did not mount; requesting format"); - modals.add_list_item(t!("pddb.okay", xous::LANG)).expect("couldn't build radio item list"); - modals.add_list_item(t!("pddb.cancel", xous::LANG)).expect("couldn't build radio item list"); - let do_format: bool; - match modals.get_radiobutton(t!("pddb.requestformat", xous::LANG)) { - Ok(response) => { - if response.as_str() == t!("pddb.okay", xous::LANG) { - do_format = true; - } else if response.as_str() == t!("pddb.cancel", xous::LANG) { - log::info!("PDDB format aborted by user"); - do_format = false; - } else { - panic!("Got unexpected return from radiobutton"); - } - } - _ => panic!("get_radiobutton failed"), - } - if do_format { - modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); + tt.sleep_ms(1000).unwrap(); // wait 1 second after boot before attempting to mount, to let the boot screen finish redrawing (cometic issue). + log::info!("Requesting login password"); + let mut done = false; + let mut skip = false; + while !done { + done = pddb_os.try_login(); + if !done { + pddb_os.clear_password(); // clear the bad password entry modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); - let fast: bool; - match modals.get_radiobutton(t!("pddb.devbypass", xous::LANG)) { + modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); + match modals.get_radiobutton(t!("pddb.badpass", xous::LANG)) { Ok(response) => { if response.as_str() == t!("pddb.yes", xous::LANG) { - fast = true; + done = false; } else if response.as_str() == t!("pddb.no", xous::LANG) { - fast = false; + done = true; + skip = true; } else { panic!("Got unexpected return from radiobutton"); } } _ => panic!("get_radiobutton failed"), } - pddb_os.pddb_format(fast, Some(&modals)).expect("couldn't format PDDB"); + } + } - #[cfg(not(any(target_os = "none", target_os = "xous")))] - pddb_os.dbg_dump(Some("full".to_string()), None); + if !skip { + log::info!("Attempting to mount the PDDB"); + if let Some(sys_basis) = pddb_os.pddb_mount() { + log::info!("PDDB mount operation finished successfully"); + basis_cache.basis_add(sys_basis); + } else { + log::debug!("PDDB did not mount; requesting format"); + modals.add_list_item(t!("pddb.okay", xous::LANG)).expect("couldn't build radio item list"); + modals.add_list_item(t!("pddb.cancel", xous::LANG)).expect("couldn't build radio item list"); + let do_format: bool; + match modals.get_radiobutton(t!("pddb.requestformat", xous::LANG)) { + Ok(response) => { + if response.as_str() == t!("pddb.okay", xous::LANG) { + do_format = true; + } else if response.as_str() == t!("pddb.cancel", xous::LANG) { + log::info!("PDDB format aborted by user"); + do_format = false; + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + if do_format { + modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list"); + modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list"); + let fast: bool; + match modals.get_radiobutton(t!("pddb.devbypass", xous::LANG)) { + Ok(response) => { + if response.as_str() == t!("pddb.yes", xous::LANG) { + fast = true; + } else if response.as_str() == t!("pddb.no", xous::LANG) { + fast = false; + } else { + panic!("Got unexpected return from radiobutton"); + } + } + _ => panic!("get_radiobutton failed"), + } + pddb_os.pddb_format(fast, Some(&modals)).expect("couldn't format PDDB"); - if let Some(sys_basis) = pddb_os.pddb_mount() { - log::info!("PDDB mount operation finished successfully"); - basis_cache.basis_add(sys_basis); - } else { - log::error!("Despite formatting, no PDDB was found!"); - let mut err = String::from(t!("pddb.internalerror", xous::LANG)); - err.push_str(" #1"); // punt and leave an error code, because this "should" be rare - modals.show_notification(err.as_str()).expect("notification failed"); + #[cfg(not(any(target_os = "none", target_os = "xous")))] + pddb_os.dbg_dump(Some("full".to_string()), None); + + if let Some(sys_basis) = pddb_os.pddb_mount() { + log::info!("PDDB mount operation finished successfully"); + basis_cache.basis_add(sys_basis); + } else { + log::error!("Despite formatting, no PDDB was found!"); + let mut err = String::from(t!("pddb.internalerror", xous::LANG)); + err.push_str(" #1"); // punt and leave an error code, because this "should" be rare + modals.show_notification(err.as_str()).expect("notification failed"); + } } } } diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index 15603ff3f..82eecb4ac 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -21,6 +21,8 @@ pub(crate) enum Opcode { AesOracle, /// create new FPGA keys; provisioning requires a slave device to be connected that can run the JTAG sequence BbramProvision, + /// clear a cached password + ClearPasswordCacheEntry, TestUx, diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index 24ade6bcc..3b323190a 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -417,6 +417,12 @@ impl<'a> RootKeys { } } } + pub fn purge_user_password(&mut self, pw_type: AesRootkeyType) { + match pw_type { + AesRootkeyType::User0 => self.purge_password(PasswordType::Boot), + _ => log::warn!("Requested to purge a password for a key that we don't have. Ignoring."), + } + } pub fn purge_password(&mut self, pw_type: PasswordType) { unsafe { let pcache_ptr: *mut PasswordCache = self.pass_cache.as_mut_ptr() as *mut PasswordCache; diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index ba874d048..bd4120fd2 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -161,6 +161,13 @@ impl RootKeys { 0, 0, 0, 0) ).expect("couldn't send bbram provision message"); } + + pub fn clear_password(&self, pass_type: AesRootkeyType) { + send_message(self.conn, + Message::new_blocking_scalar(Opcode::ClearPasswordCacheEntry.to_usize().unwrap(), + pass_type.to_usize().unwrap(), 0, 0, 0) + ).expect("couldn't send bbram provision message"); + } } use core::sync::atomic::{AtomicU32, Ordering}; diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 48561c886..a1a85385e 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -375,6 +375,11 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, 0).unwrap(); } }), + Some(Opcode::ClearPasswordCacheEntry) => msg_blocking_scalar_unpack!(msg, pass_type_code, _, _, _, { + let pass_type: AesRootkeyType = FromPrimitive::from_usize(pass_type_code).unwrap_or(AesRootkeyType::NoneSpecified); + keys.purge_user_password(pass_type); + xous::return_scalar(msg.sender, 1).unwrap(); + }), // UX flow opcodes Some(Opcode::UxTryInitKeys) => msg_scalar_unpack!(msg, _, _, _, _, { @@ -1026,7 +1031,7 @@ fn xmain() -> ! { ); confirm_radiobox.is_password = true; confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_suspend", xous::LANG))); - confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_clear", xous::LANG))); + // confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_clear", xous::LANG))); // this policy makes no sense in the use case of the key confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_keep", xous::LANG))); rootkeys_modal.modify( Some(ActionType::RadioButtons(confirm_radiobox)),