From 919e9e87ff0d7b103c790c66c0538ddf23ad42cc Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 30 Jul 2021 04:07:10 +0800 Subject: [PATCH] add bcrypt for password hashing, take care of life cycle of plaintext --- Cargo.lock | 12 ++ services/root-keys/Cargo.toml | 1 + services/root-keys/src/api.rs | 3 +- services/root-keys/src/bcrypt.rs | 54 ++++++++ services/root-keys/src/implementation.rs | 168 +++++++++++++++++++---- services/root-keys/src/main.rs | 69 ++++++---- 6 files changed, 256 insertions(+), 51 deletions(-) create mode 100644 services/root-keys/src/bcrypt.rs diff --git a/Cargo.lock b/Cargo.lock index c0604008a..b1c3e5afc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -225,6 +225,17 @@ dependencies = [ "generic-array 0.14.4", ] +[[package]] +name = "blowfish" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe3ff3fc1de48c1ac2e3341c4df38b0d1bfb8fdf04632a187c8b75aaa319a7ab" +dependencies = [ + "byteorder", + "cipher", + "opaque-debug", +] + [[package]] name = "bstr" version = "0.2.14" @@ -1610,6 +1621,7 @@ dependencies = [ name = "root-keys" version = "0.1.0" dependencies = [ + "blowfish", "cipher", "gam", "locales", diff --git a/services/root-keys/Cargo.toml b/services/root-keys/Cargo.toml index 386108ed2..0540a0999 100644 --- a/services/root-keys/Cargo.toml +++ b/services/root-keys/Cargo.toml @@ -20,6 +20,7 @@ num-traits = {version = "0.2", default-features = false} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} cipher = "0.3" +blowfish = { version = "0.8", features = ["bcrypt"] } gam = {path = "../gam"} # for direct password modals locales = {path = "../../locales"} diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index 0d530ded2..18080dde1 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -42,9 +42,8 @@ pub struct ProgressReport { } #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] -pub(crate) enum PasswordRetentionPolicy { +pub enum PasswordRetentionPolicy { AlwaysKeep, EraseOnSuspend, - EraseOnIdle, AlwaysPurge, } diff --git a/services/root-keys/src/bcrypt.rs b/services/root-keys/src/bcrypt.rs new file mode 100644 index 000000000..acac87c2c --- /dev/null +++ b/services/root-keys/src/bcrypt.rs @@ -0,0 +1,54 @@ + +// this code is based on https://github.com/Keats/rust-bcrypt +// the original crate is not used directly because the base64 wrappers cause the crate +// to be incompatible with a no-std environment. We are storing binary data directly +// in our use case. + +// Cost constants +const MIN_COST: u32 = 4; +const MAX_COST: u32 = 31; +pub const DEFAULT_COST: u32 = 12; + +use blowfish::Blowfish; + +fn setup(cost: u32, salt: &[u8], key: &[u8]) -> Blowfish { + assert!(cost < 32); + let mut state = Blowfish::bc_init_state(); + + state.salted_expand_key(salt, key); + for _ in 0..1u32 << cost { + state.bc_expand_key(key); + state.bc_expand_key(salt); + } + + state +} + +pub fn bcrypt(cost: u32, salt: &[u8], password: &[u8], output: &mut [u8]) { + assert!(salt.len() == 16); + assert!(!password.is_empty() && password.len() <= 72); + assert!(output.len() == 24); + + let state = setup(cost, salt, password); + // OrpheanBeholderScryDoubt + #[allow(clippy::unreadable_literal)] + let mut ctext = [ + 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274, + ]; + for i in 0..3 { + let i: usize = i * 2; + for _ in 0..64 { + let (l, r) = state.bc_encrypt(ctext[i], ctext[i + 1]); + ctext[i] = l; + ctext[i + 1] = r; + } + + let buf = ctext[i].to_be_bytes(); + output[i * 4..][..4].copy_from_slice(&buf); + let buf = ctext[i + 1].to_be_bytes(); + output[(i + 1) * 4..][..4].copy_from_slice(&buf); + } +} + +//// TODO: add at least one test vector to confirm this implementation isn't +//// totally braindead...! \ No newline at end of file diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index e50d3fb40..25efda1f2 100755 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -1,21 +1,27 @@ +use ticktimer_server::Ticktimer; use utralib::generated::*; use crate::api::*; use core::num::NonZeroUsize; use num_traits::*; +use crate::bcrypt::*; +use crate::PasswordType; + +const BCRYPT_COST: u32 = 10; // 10 is the minimum recommended by OWASP; takes xxx ms to verify @ 10 rounds + struct KeyRomLocations {} #[allow(dead_code)] impl KeyRomLocations { - const FPGA_KEY: u32 = 0x00; - const SELFSIGN_PRIVKEY: u32 = 0x08; - const SELFSIGN_PUBKEY: u32 = 0x10; - const DEVELOPER_PUBKEY: u32 = 0x18; - const THIRDPARTY_PUBKEY: u32 = 0x20; - const USER_KEY: u32 = 0x28; - const PEPPER: u32 = 0xf8; - const FPGA_REV: u32 = 0xfc; - const LOADER_REV: u32 = 0xfd; - const CONFIG: u32 = 0xff; + const FPGA_KEY: u8 = 0x00; + const SELFSIGN_PRIVKEY: u8 = 0x08; + const SELFSIGN_PUBKEY: u8 = 0x10; + const DEVELOPER_PUBKEY: u8 = 0x18; + 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 CONFIG: u8 = 0xff; } pub struct KeyField { @@ -50,7 +56,11 @@ pub(crate) mod keyrom_config { #[repr(C)] struct PasswordCache { // this structure is mapped into the password cache page and can be zero-ized at any time - canary: u32, // this is 0 if the page was cleared; it is set immediately upon allocation/initialization/update + // 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_valid: u32, // non-zero for valid + hashed_update_pw: [u8; 24], + hashed_update_pw_valid: u32, } pub(crate) struct RootKeys { @@ -61,9 +71,10 @@ pub(crate) struct RootKeys { kernel: xous::MemoryRange, /// regions of RAM that holds all plaintext passwords, keys, and temp data. stuck in two well-defined page so we can /// zero-ize it upon demand, without guessing about stack frames and/or Rust optimizers removing writes - sensitive_data: xous::MemoryRange, - pass_cache: xous::MemoryRange, - password_policy: PasswordRetentionPolicy, + sensitive_data: xous::MemoryRange, // this gets purged at least on every suspend, but ideally purged sooner than that + pass_cache: xous::MemoryRange, // this can be purged based on a policy, as set below + boot_password_policy: PasswordRetentionPolicy, + update_password_policy: PasswordRetentionPolicy, susres: susres::Susres, // for disabling suspend/resume trng: trng::Trng, gam: gam::Gam, // for raising UX elements directly @@ -126,7 +137,8 @@ impl RootKeys { kernel, sensitive_data, pass_cache, - password_policy: PasswordRetentionPolicy::AlwaysKeep, + update_password_policy: PasswordRetentionPolicy::AlwaysPurge, + boot_password_policy: PasswordRetentionPolicy::AlwaysKeep, 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"), @@ -135,20 +147,119 @@ impl RootKeys { keys } + fn purge_password(&mut self, pw_type: PasswordType) { + unsafe { + let pcache_ptr: *mut PasswordCache = self.pass_cache.as_mut_ptr() as *mut PasswordCache; + match pw_type { + PasswordType::Boot => { + for p in (*pcache_ptr).hashed_boot_pw.iter_mut() { + *p = 0; + } + (*pcache_ptr).hashed_boot_pw_valid = 0; + } + PasswordType::Update => { + for p in (*pcache_ptr).hashed_update_pw.iter_mut() { + *p = 0; + } + (*pcache_ptr).hashed_update_pw_valid = 0; + } + } + } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); + } + fn purge_sensitive_data(&mut self) { + let data = self.sensitive_data.as_slice_mut::(); + for d in data.iter_mut() { + *d = 0; + } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); + } + pub fn suspend(&mut self) { - match self.password_policy { + match self.boot_password_policy { PasswordRetentionPolicy::AlwaysKeep => { () }, _ => { - let data = self.sensitive_data.as_slice_mut::(); - for d in data.iter_mut() { - *d = 0; + self.purge_password(PasswordType::Boot); + } + } + match self.update_password_policy { + PasswordRetentionPolicy::AlwaysKeep => { + () + }, + _ => { + self.purge_password(PasswordType::Update); + } + } + self.purge_sensitive_data(); + } + pub fn resume(&mut self) { + } + + pub fn update_policy(&mut self, policy: Option, pw_type: PasswordType) { + if let Some(p) = policy { + match pw_type { + PasswordType::Boot => self.boot_password_policy = p, + PasswordType::Update => self.update_password_policy = p, + }; + } else { + match pw_type { + PasswordType::Boot => PasswordRetentionPolicy::AlwaysPurge, + PasswordType::Update => PasswordRetentionPolicy::AlwaysPurge, + }; + } + } + + /// plaintext password is passed as a &str. Any copies internally are destroyed. + pub fn hash_and_save_password(&mut self, pw: &str, pw_type: PasswordType) { + let pw_len = if pw.len() > 72 { + log::warn!("password of length {} is truncated to 72 bytes [bcrypt]", pw.len()); + 72 + } else { + pw.len() + }; + let mut plaintext_copy: [u8; 72] = [0; 72]; + for (src, dst) in pw.bytes().zip(plaintext_copy.iter_mut()) { + *dst = src; + } + let mut hashed_password: [u8; 24] = [0; 24]; + let salt = self.read_key_128(KeyRomLocations::PEPPER); + + let timer = ticktimer_server::Ticktimer::new().expect("couldn't connect to ticktimer"); + // this function was pulled in from another crate. A quick look around makes me think it doesn't + // create any extra copies of the plaintext anywhere -- the &[u8] gets dereferenced and mixed up + // in some key expansion immediately + let start_time = timer.elapsed_ms(); + bcrypt(BCRYPT_COST, &salt, &plaintext_copy[..pw_len], &mut hashed_password); + 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 + + 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()) { + *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()) { + *dst = src; + } + (*pcache_ptr).hashed_update_pw_valid = 1; } } } - } - pub fn resume(&mut self) { + + // an unsafe method is used because the compiler will correctly reason that plaintext_copy goes out of scope + // and these writes are never read, and therefore they may be optimized out. + let pt_ptr = plaintext_copy.as_mut_ptr(); + for i in 0..plaintext_copy.len() { + unsafe{pt_ptr.add(i).write_volatile(core::mem::zeroed());} + } + core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst); } fn update_progress(&mut self, maybe_cid: Option, current_step: u32, total_steps: u32, finished: bool) { @@ -171,6 +282,17 @@ impl RootKeys { } key } + fn read_key_128(&mut self, index: u8) -> [u8; 16] { + let mut key: [u8; 16] = [0; 16]; + for (addr, word) in key.chunks_mut(4).into_iter().enumerate() { + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, index as u32 + addr as u32); + let keyword = self.keyrom.rf(utra::keyrom::DATA_DATA); + for (&byte, dst) in keyword.to_be_bytes().iter().zip(word.iter_mut()) { + *dst = byte; + } + } + key + } pub fn try_init_keys(&mut self, maybe_progress: Option) { let mut step = 0; // current step @@ -186,7 +308,7 @@ impl RootKeys { step += 1; self.update_progress(progress_cid, step, total, false); - self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, KeyRomLocations::CONFIG); + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, KeyRomLocations::CONFIG as u32); let config = self.keyrom.rf(utra::keyrom::DATA_DATA); if config & keyrom_config::INITIALIZED.ms(1) != 0 { @@ -214,7 +336,7 @@ impl RootKeys { // - pepper // provision the pepper - for keyword in sensitive_slice[KeyRomLocations::PEPPER as usize..(KeyRomLocations::PEPPER + 8) as usize].iter_mut() { + for keyword in sensitive_slice[KeyRomLocations::PEPPER as usize..(KeyRomLocations::PEPPER + 4) as usize].iter_mut() { *keyword = self.trng.get_u32().expect("couldn't get random number"); } diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 0aafb7128..dd3751643 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -20,23 +20,21 @@ mod implementation; #[cfg(target_os = "none")] use implementation::*; +#[cfg(target_os = "none")] +mod bcrypt; + // a stub to try to avoid breaking hosted mode for as long as possible. #[cfg(not(target_os = "none"))] mod implementation { use crate::ROOTKEY_MODAL_NAME; - use gam::modal::*; - use xous_ipc::String; + use crate::PasswordRetentionPolicy; pub struct RootKeys { - gam: gam::Gam, - ticktimer: ticktimer_server::Ticktimer, } impl RootKeys { pub fn new(xns: &xous_names::XousNames) -> RootKeys { RootKeys { - gam: gam::Gam::new(&xns).expect("couldn't allocate GAM for testing"), - ticktimer: ticktimer_server::Ticktimer::new().expect("couldn't get ticktimer"), } } pub fn suspend(&self) { @@ -44,11 +42,24 @@ mod implementation { pub fn resume(&self) { } + pub fn update_policy(&mut self, policy: Option) { + log::info!("policy updated: {:?}", policy); + } + pub fn set_plaintext_password(&mut self, pw: &str) { + log::info!("got password plaintext: {}", pw); + } pub fn try_init_keys(&mut self, _maybe_progress: Option) { } } } +// enumerate the possible password types dealt with by this manager +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub(crate) enum PasswordType { + Boot, + Update, +} + #[xous::xous_main] fn xmain() -> ! { use crate::implementation::RootKeys; @@ -62,9 +73,10 @@ fn xmain() -> ! { Connections allowed to the keys server: 1. Shellchat (to originate update test requests) 2. Password entry UX thread - 2. (future) PDDB + 3. Key purge timer + 4. (future) PDDB */ - let keys_sid = xns.register_name(api::SERVER_NAME_KEYS, Some(2)).expect("can't register server"); + let keys_sid = xns.register_name(api::SERVER_NAME_KEYS, Some(3)).expect("can't register server"); log::trace!("registered with NS -- {:?}", keys_sid); let mut keys = RootKeys::new(&xns); @@ -84,13 +96,6 @@ fn xmain() -> ! { action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::AlwaysKeep.to_u32().unwrap(), 0, 0, 0,]), close_on_select: true, }); - policy_menu.add_item(MenuItem { - name: String::<64>::from_str(t!("rootkeys.policy_idle", xous::LANG)), - action_conn: main_cid, - action_opcode: Opcode::PasswordPolicy.to_u32().unwrap(), - action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::EraseOnIdle.to_u32().unwrap(), 0, 0, 0,]), - close_on_select: true, - }); policy_menu.add_item(MenuItem { name: String::<64>::from_str(t!("rootkeys.policy_suspend", xous::LANG)), action_conn: main_cid, @@ -134,7 +139,7 @@ fn xmain() -> ! { ); let mut cur_plaintext = String::<256>::new(); - let mut cur_policy: Option = None; + let mut cur_password_type: Option = None; loop { let msg = xous::receive_message(keys_sid).unwrap(); log::trace!("message: {:?}", msg); @@ -159,14 +164,21 @@ fn xmain() -> ! { Some(Opcode::PasswordModalEntry) => { let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let mut plaintext_pw = buf.to_original::().unwrap(); - write!(cur_plaintext, "{}", plaintext_pw.as_str()).expect("couldn't copy plaintext password"); - plaintext_pw.volatile_clear(); // ensure the data is destroyed after printing - buf.volatile_clear(); - log::info!("cur_plaintext: {}", cur_plaintext); - // now explicitly request a policy decision - xous::send_message(main_cid, - Message::new_scalar(Opcode::RaisePolicyMenu.to_usize().unwrap(), 0, 0, 0, 0) - ).expect("couldn't raise policy menu follow-up dialogue"); + + if let Some(pw_type) = cur_password_type { + keys.hash_and_save_password(plaintext_pw.as_str(), pw_type); + plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + + // now explicitly request a policy decision + xous::send_message(main_cid, + Message::new_scalar(Opcode::RaisePolicyMenu.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't raise policy menu follow-up dialogue"); + } else { + plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave + buf.volatile_clear(); + log::error!("got a password from our UX but didn't expect one. Ignoring it.") + } }, Some(Opcode::RaisePolicyMenu) => { xous::yield_slice(); // let any pending redraws happen before raising this menu @@ -174,9 +186,14 @@ fn xmain() -> ! { policy_menu.activate(); } Some(Opcode::PasswordPolicy) => msg_scalar_unpack!(msg, policy_code, _, _, _, { - cur_policy = FromPrimitive::from_usize(policy_code); - log::info!("cur_policy: {:?}", cur_policy); + if let Some(pw_type) = cur_password_type { + keys.update_policy(FromPrimitive::from_usize(policy_code), pw_type); + } else { + log::error!("got a policy from our UX but didn't expect one. Ignoring.") + } }), + + // boilerplate Ux handlers Some(Opcode::MenuRedraw) => { policy_menu.redraw(); },