the base layer of the AES oracle is in place for the rootkeys

This commit is contained in:
bunnie 2021-08-17 04:15:24 +08:00
parent a1967a2128
commit 498f530165
6 changed files with 211 additions and 35 deletions

View file

@ -189,6 +189,16 @@
"zh": "更新完成重启应用", "zh": "更新完成重启应用",
"en-audio": "Xous signing finished. Reboot at your earliest convenience." "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": { "rootkeys.policy_request": {
"en": "Please pick a password\nretention policy:", "en": "Please pick a password\nretention policy:",
"zh": "请选择密码保留策略:", "zh": "请选择密码保留策略:",

View file

@ -44,7 +44,9 @@ pub(crate) enum Opcode {
UxSignXousRun, UxSignXousRun,
/// Ux AES calls /// Ux AES calls
//UxAesEnsurePassword, UxAesEnsurePassword,
UxAesPasswordPolicy,
UxAesEnsureReturn,
// General Ux calls // General Ux calls
UxGutter, // NOP for UX calls that require a destination UxGutter, // NOP for UX calls that require a destination
@ -97,11 +99,18 @@ pub enum RootkeyResult {
pub use cipher::{BlockCipher, consts::U16}; pub use cipher::{BlockCipher, consts::U16};
use zeroize::Zeroize; use zeroize::Zeroize;
/// 128-bit AES block
#[allow(dead_code)]
pub type Block = cipher::generic_array::GenericArray<u8, cipher::consts::U16>;
/// 16 x 128-bit AES blocks to be processed in bulk
#[allow(dead_code)]
pub type ParBlocks = cipher::generic_array::GenericArray<Block, cipher::consts::U16>;
pub const PAR_BLOCKS: usize = 16; pub const PAR_BLOCKS: usize = 16;
/// Selects which key to use for the decryption/encryption oracle. /// Selects which key to use for the decryption/encryption oracle.
/// currently only one type is available, the User key, but dozens more /// currently only one type is available, the User key, but dozens more
/// could be accommodated. /// 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 { pub enum AesRootkeyType {
User0 = 0x28, User0 = 0x28,
NoneSpecified = 0xff, NoneSpecified = 0xff,

View file

@ -683,12 +683,16 @@ impl<'a> RootKeys {
let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY); let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY);
let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)}; let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)};
if pcache.hashed_boot_pw_valid == 0 { if pcache.hashed_boot_pw_valid == 0 {
self.purge_password(PasswordType::Boot);
log::warn!("boot password isn't valid! Returning bogus results."); log::warn!("boot password isn't valid! Returning bogus results.");
} }
for (key, &pw) in for (key, &pw) in
key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) { key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) {
*key = *key ^ pw; *key = *key ^ pw;
} }
if self.boot_password_policy == PasswordRetentionPolicy::AlwaysPurge {
self.purge_password(PasswordType::Boot);
}
key_enc key_enc
}, },
_ => { _ => {
@ -711,12 +715,16 @@ impl<'a> RootKeys {
let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY); let mut key_enc = self.read_key_256(KeyRomLocs::USER_KEY);
let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)}; let pcache: &PasswordCache = unsafe{& *(self.pass_cache.as_ptr() as *const PasswordCache)};
if pcache.hashed_boot_pw_valid == 0 { if pcache.hashed_boot_pw_valid == 0 {
self.purge_password(PasswordType::Boot);
log::warn!("boot password isn't valid! Returning bogus results."); log::warn!("boot password isn't valid! Returning bogus results.");
} }
for (key, &pw) in for (key, &pw) in
key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) { key_enc.iter_mut().zip(pcache.hashed_boot_pw.iter()) {
*key = *key ^ pw; *key = *key ^ pw;
} }
if self.boot_password_policy == PasswordRetentionPolicy::AlwaysPurge {
self.purge_password(PasswordType::Boot);
}
key_enc key_enc
}, },
_ => { _ => {
@ -980,6 +988,14 @@ impl<'a> RootKeys {
true 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 /// 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. /// of the run, and also sets up some missing fields of KEYROM necessary to encrypt passwords.

View file

@ -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) { pub fn test_ux(&mut self, arg: usize) {
send_message(self.conn, let response = send_message(self.conn,
Message::new_scalar(Opcode::TestUx.to_usize().unwrap(), Message::new_blocking_scalar(Opcode::TestUx.to_usize().unwrap(),
arg, 0, 0, 0) arg, 0, 0, 0)
).expect("couldn't send test message"); ).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<u8, cipher::consts::U16>;
/// 16 x 128-bit AES blocks to be processed in bulk
pub type ParBlocks = cipher::generic_array::GenericArray<Block, cipher::consts::U16>;
impl BlockCipher for RootKeys { impl BlockCipher for RootKeys {
type BlockSize = U16; // 128-bit cipher type BlockSize = U16; // 128-bit cipher
// we have to manually match this to PAR_BLOCKS!! // we have to manually match this to PAR_BLOCKS!!
@ -181,6 +193,9 @@ impl BlockCipher for RootKeys {
impl BlockEncrypt for RootKeys { impl BlockEncrypt for RootKeys {
fn encrypt_block(&self, block: &mut Block) { fn encrypt_block(&self, block: &mut Block) {
if !self.ensure_aes_password() {
return;
}
let op = AesOp { let op = AesOp {
key_index: self.key_index.to_u8().unwrap(), key_index: self.key_index.to_u8().unwrap(),
block: AesBlockType::SingleBlock(block.as_slice().try_into().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) { 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]; 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_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()) { 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 { impl BlockDecrypt for RootKeys {
fn decrypt_block(&self, block: &mut Block) { fn decrypt_block(&self, block: &mut Block) {
if !self.ensure_aes_password() {
return;
}
let op = AesOp { let op = AesOp {
key_index: self.key_index.to_u8().unwrap(), key_index: self.key_index.to_u8().unwrap(),
block: AesBlockType::SingleBlock(block.as_slice().try_into().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) { fn decrypt_par_blocks(&self, blocks: &mut ParBlocks) {
if !self.ensure_aes_password() {
return;
}
let mut pb_buf: [[u8; 16]; 16] = [[0; 16]; 16]; 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_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()) { for (dst, &src) in dst_block.iter_mut().zip(src_block.as_slice().iter()) {

View file

@ -174,6 +174,9 @@ mod implementation {
pub fn is_pcache_update_password_valid(&self) -> bool { pub fn is_pcache_update_password_valid(&self) -> bool {
false false
} }
pub fn is_pcache_boot_password_valid(&self) -> bool {
false
}
pub fn fetch_gw_metadata(&self, _region_enum: GatewareRegion) -> MetadataInFlash { pub fn fetch_gw_metadata(&self, _region_enum: GatewareRegion) -> MetadataInFlash {
MetadataInFlash { MetadataInFlash {
@ -293,8 +296,9 @@ fn xmain() -> ! {
); );
let mut reboot_initiated = false; let mut reboot_initiated = false;
let mut aes_sender: Option<xous::MessageSender> = None;
loop { loop {
let msg = xous::receive_message(keys_sid).unwrap(); let mut msg = xous::receive_message(keys_sid).unwrap();
log::debug!("message: {:?}", msg); log::debug!("message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, { Some(Opcode::SuspendResume) => msg_scalar_unpack!(msg, token, _, _, _, {
@ -327,28 +331,6 @@ fn xmain() -> ! {
xous::return_scalar(msg.sender, 0).unwrap(); 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::<AesOp, _>().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 // UX flow opcodes
Some(Opcode::UxTryInitKeys) => msg_scalar_unpack!(msg, _, _, _, _, { 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::<gam::modal::TextEntryPayload, _>().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::<RadioButtonPayload, _>().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::<AesOp, _>().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, _, _, _, _, { Some(Opcode::CheckGatewareSignature) => msg_blocking_scalar_unpack!(msg, _, _, _, _, {
if keys.is_initialized() { if keys.is_initialized() {
if keys.verify_gateware_self_signature() { if keys.verify_gateware_self_signature() {
@ -949,8 +1038,9 @@ fn xmain() -> ! {
xous::return_scalar(msg.sender, 2).expect("couldn't send return value"); xous::return_scalar(msg.sender, 2).expect("couldn't send return value");
} }
}), }),
Some(Opcode::TestUx) => msg_scalar_unpack!(msg, _arg, _, _, _, { Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, _arg, _, _, _, {
// empty test routine for now // dummy test for now
xous::return_scalar(msg.sender, 1234).unwrap();
}), }),
Some(Opcode::UxGetPolicy) => { Some(Opcode::UxGetPolicy) => {
policy_menu.activate(); policy_menu.activate();

View file

@ -1,5 +1,5 @@
use crate::{ShellCmdApi, CommonEnv}; use crate::{ShellCmdApi, CommonEnv};
use root_keys::api::AesRootkeyType; use root_keys::api::{AesRootkeyType, Block};
use xous_ipc::String; use xous_ipc::String;
#[derive(Debug)] #[derive(Debug)]
@ -56,6 +56,33 @@ impl<'a> ShellCmdApi<'a> for Keys {
//debug_here::debug_here!(); //debug_here::debug_here!();
write!(ret, "show UX").unwrap(); 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" => { "usblock" => {
env.llio.debug_usb(Some(true)).unwrap(); env.llio.debug_usb(Some(true)).unwrap();
write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap(); write!(ret, "USB debug port locked out; one word at 0x80000000 is disclosable via USB.").unwrap();