From 498f530165c777fabddb95c14dd7c59029de527b Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 17 Aug 2021 04:15:24 +0800 Subject: [PATCH] the base layer of the AES oracle is in place for the rootkeys --- services/root-keys/locales/i18n.json | 10 ++ services/root-keys/src/api.rs | 13 ++- services/root-keys/src/implementation.rs | 16 +++ services/root-keys/src/lib.rs | 38 ++++-- services/root-keys/src/main.rs | 140 +++++++++++++++++++---- services/shellchat/src/cmds/keys.rs | 29 ++++- 6 files changed, 211 insertions(+), 35 deletions(-) diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index 74f66ecaa..0b08e19b1 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -189,6 +189,16 @@ "zh": "更新完成重启应用", "en-audio": "Xous signing finished. Reboot at your earliest convenience." }, + "rootkeys.get_login_password": { + "en": "Password request\nDevice unlock\nSecurity: Low\nWhy: User login", + "zh": "输入密码\n解锁\n安全含义:低", + "en-audio": "Enter device unlock password to access basic service." + }, + "rootkeys.bad_password_request": { + "en": "Someone issued a request\nfor a non-existent\npassword.", + "zh": "**improve**无效的密码请求", + "en-audio": "Someone issued a request for a non-existent password." + }, "rootkeys.policy_request": { "en": "Please pick a password\nretention policy:", "zh": "请选择密码保留策略:", diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index b7d274b59..0c0a6c126 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -44,7 +44,9 @@ pub(crate) enum Opcode { UxSignXousRun, /// Ux AES calls - //UxAesEnsurePassword, + UxAesEnsurePassword, + UxAesPasswordPolicy, + UxAesEnsureReturn, // General Ux calls UxGutter, // NOP for UX calls that require a destination @@ -97,11 +99,18 @@ pub enum RootkeyResult { pub use cipher::{BlockCipher, consts::U16}; use zeroize::Zeroize; +/// 128-bit AES block +#[allow(dead_code)] +pub type Block = cipher::generic_array::GenericArray; +/// 16 x 128-bit AES blocks to be processed in bulk +#[allow(dead_code)] +pub type ParBlocks = cipher::generic_array::GenericArray; + pub const PAR_BLOCKS: usize = 16; /// Selects which key to use for the decryption/encryption oracle. /// currently only one type is available, the User key, but dozens more /// could be accommodated. -#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, Eq)] +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, PartialEq, Eq, Copy, Clone)] pub enum AesRootkeyType { User0 = 0x28, NoneSpecified = 0xff, diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index 136cf3441..70a545f15 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -683,12 +683,16 @@ impl<'a> RootKeys { let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY); let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)}; if pcache.hashed_boot_pw_valid == 0 { + self.purge_password(PasswordType::Boot); log::warn!("boot password isn't valid! Returning bogus results."); } for (key, &pw) in key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) { *key = *key ^ pw; } + if self.boot_password_policy == PasswordRetentionPolicy::AlwaysPurge { + self.purge_password(PasswordType::Boot); + } key_enc }, _ => { @@ -711,12 +715,16 @@ impl<'a> RootKeys { let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY); let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)}; if pcache.hashed_boot_pw_valid == 0 { + self.purge_password(PasswordType::Boot); log::warn!("boot password isn't valid! Returning bogus results."); } for (key, &pw) in key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) { *key = *key ^ pw; } + if self.boot_password_policy == PasswordRetentionPolicy::AlwaysPurge { + self.purge_password(PasswordType::Boot); + } key_enc }, _ => { @@ -980,6 +988,14 @@ impl<'a> RootKeys { true } } + pub fn is_pcache_boot_password_valid(&self) -> bool { + let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + if pcache.hashed_boot_pw_valid == 0 { + false + } else { + true + } + } /// Called by the UX layer to set up a key init run. It disables suspend/resume for the duration /// of the run, and also sets up some missing fields of KEYROM necessary to encrypt passwords. diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index 6d65eeb12..1ee665c55 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -146,11 +146,28 @@ impl RootKeys { } } + fn ensure_aes_password(&self) -> bool { + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::UxAesEnsurePassword.to_usize().unwrap(), self.key_index as usize, 0, 0, 0,) + ).expect("failed to ensure password is current"); + if let xous::Result::Scalar1(result) = response { + if result != 1 { + log::error!("there was a problem ensuring our password was unlocked, aborting!"); + return false; + } + } else { + log::error!("there was a problem ensuring our password was unlocked, aborting!"); + return false; + } + true + } + pub fn test_ux(&mut self, arg: usize) { - send_message(self.conn, - Message::new_scalar(Opcode::TestUx.to_usize().unwrap(), + let response = send_message(self.conn, + Message::new_blocking_scalar(Opcode::TestUx.to_usize().unwrap(), arg, 0, 0, 0) ).expect("couldn't send test message"); + log::info!("test_ux response: {:?}", response); } } @@ -168,11 +185,6 @@ impl Drop for RootKeys { } } -/// 128-bit AES block -pub type Block = cipher::generic_array::GenericArray; -/// 16 x 128-bit AES blocks to be processed in bulk -pub type ParBlocks = cipher::generic_array::GenericArray; - impl BlockCipher for RootKeys { type BlockSize = U16; // 128-bit cipher // we have to manually match this to PAR_BLOCKS!! @@ -181,6 +193,9 @@ impl BlockCipher for RootKeys { impl BlockEncrypt for RootKeys { fn encrypt_block(&self, block: &mut Block) { + if !self.ensure_aes_password() { + return; + } let op = AesOp { key_index: self.key_index.to_u8().unwrap(), block: AesBlockType::SingleBlock(block.as_slice().try_into().unwrap()), @@ -196,6 +211,9 @@ impl BlockEncrypt for RootKeys { } } fn encrypt_par_blocks(&self, blocks: &mut ParBlocks) { + if !self.ensure_aes_password() { + return; + } let mut pb_buf: [[u8; 16]; PAR_BLOCKS] = [[0; 16]; PAR_BLOCKS]; for (dst_block, src_block) in pb_buf.iter_mut().zip(blocks.as_slice().iter()) { for (dst, &src) in dst_block.iter_mut().zip(src_block.as_slice().iter()) { @@ -222,6 +240,9 @@ impl BlockEncrypt for RootKeys { impl BlockDecrypt for RootKeys { fn decrypt_block(&self, block: &mut Block) { + if !self.ensure_aes_password() { + return; + } let op = AesOp { key_index: self.key_index.to_u8().unwrap(), block: AesBlockType::SingleBlock(block.as_slice().try_into().unwrap()), @@ -237,6 +258,9 @@ impl BlockDecrypt for RootKeys { } } fn decrypt_par_blocks(&self, blocks: &mut ParBlocks) { + if !self.ensure_aes_password() { + return; + } let mut pb_buf: [[u8; 16]; 16] = [[0; 16]; 16]; for (dst_block, src_block) in pb_buf.iter_mut().zip(blocks.as_slice().iter()) { for (dst, &src) in dst_block.iter_mut().zip(src_block.as_slice().iter()) { diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 7c3ca4571..7f6adc52e 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -174,6 +174,9 @@ mod implementation { pub fn is_pcache_update_password_valid(&self) -> bool { false } + pub fn is_pcache_boot_password_valid(&self) -> bool { + false + } pub fn fetch_gw_metadata(&self, _region_enum: GatewareRegion) -> MetadataInFlash { MetadataInFlash { @@ -293,8 +296,9 @@ fn xmain() -> ! { ); let mut reboot_initiated = false; + let mut aes_sender: Option = None; loop { - let msg = xous::receive_message(keys_sid).unwrap(); + let mut msg = xous::receive_message(keys_sid).unwrap(); log::debug!("message: {:?}", msg); match FromPrimitive::from_usize(msg.body.id()) { Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { @@ -327,28 +331,6 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, 0).unwrap(); } }), - Some(Opcode::AesOperation) => { - let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; - // as_flat saves a copy step, but we have to deserialize some enums manually - let aes_op = buffer.as_flat::().unwrap(); - // deserialize the specifier - let optype = match aes_op.aes_op { - ArchivedAesOpType::Decrypt => { - AesOpType::Decrypt - }, - ArchivedAesOpType::Encrypt => { - AesOpType::Encrypt - } - }; - match aes_op.block { - ArchivedAesBlockType::SingleBlock(mut b) => { - keys.aes_op(aes_op.key_index, optype, &mut b); - } - ArchivedAesBlockType::ParBlock(mut pb) => { - keys.aes_par_op(aes_op.key_index, optype, &mut pb); - } - } - }, // UX flow opcodes Some(Opcode::UxTryInitKeys) => msg_scalar_unpack!(msg, _, _, _, _, { @@ -938,6 +920,113 @@ fn xmain() -> ! { } } } + Some(Opcode::UxAesEnsurePassword) => msg_blocking_scalar_unpack!(msg, key_index, _, _, _, { + if key_index as u8 == AesRootkeyType::User0.to_u8().unwrap() { + if keys.is_pcache_boot_password_valid() { + // short circuit the process if the cache is hot + xous::return_scalar(msg.sender, 1).unwrap(); + continue; + } + if aes_sender.is_some() { + log::error!("multiple concurrent requests to UxAesEnsurePasword, not allowed!"); + xous::return_scalar(msg.sender, 0).unwrap(); + } else { + aes_sender = Some(msg.sender); + } + keys.set_ux_password_type(Some(PasswordType::Boot)); + password_action.set_action_opcode(Opcode::UxAesPasswordPolicy.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::TextEntry(password_action)), + Some(t!("rootkeys.get_login_password", xous::LANG)), false, + None, true, None + ); + rootkeys_modal.activate(); + // note that the scalar is *not* yet returned, it will be returned by the opcode called by the password assurance + } else { + // insert other indices, as we come to have them in else-ifs + // note that there needs to be a way to keep the ensured password in sync with the + // actual key index (if multiple passwords are used/required). For now, because there is only + // one password, we can use is_pcache_boot_password_valid() to sync that up; but as we add + // more keys with more passwords, this policy may need to become markedly more complicated! + + // otherwise, an invalid password request + dismiss_modal_action.set_action_opcode(Opcode::UxGutter.to_u32().unwrap()); + rootkeys_modal.modify( + Some(ActionType::Notification(dismiss_modal_action)), + Some(t!("rootkeys.bad_password_request", xous::LANG)), false, + None, false, None); + rootkeys_modal.activate(); + + xous::return_scalar(msg.sender, 0).unwrap(); + } + }), + Some(Opcode::UxAesPasswordPolicy) => { + let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut plaintext_pw = buf.to_original::().unwrap(); + + keys.hash_and_save_password(plaintext_pw.as_str()); + plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + + let mut confirm_radiobox = gam::modal::RadioButtons::new( + main_cid, + Opcode::UxAesEnsureReturn.to_u32().unwrap() + ); + confirm_radiobox.is_password = true; + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_clear", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_suspend", xous::LANG))); + confirm_radiobox.add_item(ItemName::new(t!("rootkeys.policy_keep", xous::LANG))); + rootkeys_modal.modify( + Some(ActionType::RadioButtons(confirm_radiobox)), + Some(t!("rootkeys.policy_request", xous::LANG)), false, + None, true, None); + rootkeys_modal.activate(); + }, + Some(Opcode::UxAesEnsureReturn) => { + let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let payload = buffer.to_original::().unwrap(); + if payload.as_str() == t!("rootkeys.policy_keep", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysKeep)); + } else if payload.as_str() == t!("rootkeys.policy_suspend", xous::LANG) { + keys.update_policy(Some(PasswordRetentionPolicy::EraseOnSuspend)); + } else if payload.as_str() == "no change" { + // don't change the policy + } else { + keys.update_policy(Some(PasswordRetentionPolicy::AlwaysPurge)); // default to the most paranoid level + } + keys.set_ux_password_type(None); + if let Some(sender) = aes_sender.take() { + xous::return_scalar(sender, 1).unwrap(); + } else { + log::error!("entered a UxAesEnsureReturn but the flow was not set up correctly!"); + panic!("entered a UxAesEnsureReturn but the flow was not set up correctly!") + } + } + Some(Opcode::AesOperation) => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + // as_flat saves a copy step, but we have to deserialize some enums manually + let mut aes_op = buffer.to_original::().unwrap(); + let op = match aes_op.aes_op { // seems stupid, but we have to do this because we want to have zeroize on the AesOp record, and it means we can't have Copy on this. + AesOpType::Decrypt => AesOpType::Decrypt, + AesOpType::Encrypt => AesOpType::Encrypt, + }; + // deserialize the specifier + match aes_op.block { + AesBlockType::SingleBlock(mut b) => { + log::info!("b: {:x?}", b); + keys.aes_op(aes_op.key_index, op, &mut b); + log::info!("b: {:x?}", b); + aes_op.block = AesBlockType::SingleBlock(b); + log::info!("after b: {:x?}", aes_op); + } + AesBlockType::ParBlock(mut pb) => { + keys.aes_par_op(aes_op.key_index, op, &mut pb); + aes_op.block = AesBlockType::ParBlock(pb); + } + }; + buffer.replace(aes_op).unwrap(); + }, + Some(Opcode::CheckGatewareSignature) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { if keys.is_initialized() { if keys.verify_gateware_self_signature() { @@ -949,8 +1038,9 @@ fn xmain() -> ! { xous::return_scalar(msg.sender, 2).expect("couldn't send return value"); } }), - Some(Opcode::TestUx) => msg_scalar_unpack!(msg, _arg, _, _, _, { - // empty test routine for now + Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, _arg, _, _, _, { + // dummy test for now + xous::return_scalar(msg.sender, 1234).unwrap(); }), Some(Opcode::UxGetPolicy) => { policy_menu.activate(); diff --git a/services/shellchat/src/cmds/keys.rs b/services/shellchat/src/cmds/keys.rs index d98705d7b..eb4f5d413 100644 --- a/services/shellchat/src/cmds/keys.rs +++ b/services/shellchat/src/cmds/keys.rs @@ -1,5 +1,5 @@ use crate::{ShellCmdApi, CommonEnv}; -use root_keys::api::AesRootkeyType; +use root_keys::api::{AesRootkeyType, Block}; use xous_ipc::String; #[derive(Debug)] @@ -56,6 +56,33 @@ impl<'a> ShellCmdApi<'a> for Keys { //debug_here::debug_here!(); write!(ret, "show UX").unwrap(); } + "aes" => { + use aes_xous::{BlockEncrypt, BlockDecrypt}; + let mut pass = true; + let mut block = Block::clone_from_slice(&[0; 16]); + self.rootkeys.encrypt_block(&mut block); + log::info!("encrypted block: {:?}", block); + let mut sum = 0; + for &b in block.as_slice().iter() { + sum += b as u32; // we don't use .sum() because we need more bits than a u8 + } + if sum == 0 { + pass = false; + } + // this will cause a second password box to pop up if you told it to use-once. + self.rootkeys.decrypt_block(&mut block); + log::info!("decrypted block: {:?}", block); + for &b in block.as_slice().iter() { + if b != 0 { + pass = false; + } + } + if pass { + write!(ret, "aes test passed").unwrap(); + } else { + write!(ret, "aes test failed").unwrap(); + } + } "usblock" => { env.llio.debug_usb(Some(true)).unwrap(); write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap();