add bcrypt for password hashing, take care of life cycle of plaintext

This commit is contained in:
bunnie 2021-07-30 04:07:10 +08:00
parent 17be958d87
commit 919e9e87ff
6 changed files with 256 additions and 51 deletions

12
Cargo.lock generated
View file

@ -225,6 +225,17 @@ dependencies = [
"generic-array 0.14.4", "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]] [[package]]
name = "bstr" name = "bstr"
version = "0.2.14" version = "0.2.14"
@ -1610,6 +1621,7 @@ dependencies = [
name = "root-keys" name = "root-keys"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"blowfish",
"cipher", "cipher",
"gam", "gam",
"locales", "locales",

View file

@ -20,6 +20,7 @@ num-traits = {version = "0.2", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]} rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
cipher = "0.3" cipher = "0.3"
blowfish = { version = "0.8", features = ["bcrypt"] }
gam = {path = "../gam"} # for direct password modals gam = {path = "../gam"} # for direct password modals
locales = {path = "../../locales"} locales = {path = "../../locales"}

View file

@ -42,9 +42,8 @@ pub struct ProgressReport {
} }
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] #[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum PasswordRetentionPolicy { pub enum PasswordRetentionPolicy {
AlwaysKeep, AlwaysKeep,
EraseOnSuspend, EraseOnSuspend,
EraseOnIdle,
AlwaysPurge, AlwaysPurge,
} }

View file

@ -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...!

View file

@ -1,21 +1,27 @@
use ticktimer_server::Ticktimer;
use utralib::generated::*; use utralib::generated::*;
use crate::api::*; use crate::api::*;
use core::num::NonZeroUsize; use core::num::NonZeroUsize;
use num_traits::*; 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 {} struct KeyRomLocations {}
#[allow(dead_code)] #[allow(dead_code)]
impl KeyRomLocations { impl KeyRomLocations {
const FPGA_KEY: u32 = 0x00; const FPGA_KEY: u8 = 0x00;
const SELFSIGN_PRIVKEY: u32 = 0x08; const SELFSIGN_PRIVKEY: u8 = 0x08;
const SELFSIGN_PUBKEY: u32 = 0x10; const SELFSIGN_PUBKEY: u8 = 0x10;
const DEVELOPER_PUBKEY: u32 = 0x18; const DEVELOPER_PUBKEY: u8 = 0x18;
const THIRDPARTY_PUBKEY: u32 = 0x20; const THIRDPARTY_PUBKEY: u8 = 0x20;
const USER_KEY: u32 = 0x28; const USER_KEY: u8 = 0x28;
const PEPPER: u32 = 0xf8; const PEPPER: u8 = 0xf8;
const FPGA_REV: u32 = 0xfc; const FPGA_REV: u8 = 0xfc;
const LOADER_REV: u32 = 0xfd; const LOADER_REV: u8 = 0xfd;
const CONFIG: u32 = 0xff; const CONFIG: u8 = 0xff;
} }
pub struct KeyField { pub struct KeyField {
@ -50,7 +56,11 @@ pub(crate) mod keyrom_config {
#[repr(C)] #[repr(C)]
struct PasswordCache { struct PasswordCache {
// this structure is mapped into the password cache page and can be zero-ized at any time // 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 { pub(crate) struct RootKeys {
@ -61,9 +71,10 @@ pub(crate) struct RootKeys {
kernel: xous::MemoryRange, kernel: xous::MemoryRange,
/// regions of RAM that holds all plaintext passwords, keys, and temp data. stuck in two well-defined page so we can /// 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 /// zero-ize it upon demand, without guessing about stack frames and/or Rust optimizers removing writes
sensitive_data: xous::MemoryRange, sensitive_data: xous::MemoryRange, // this gets purged at least on every suspend, but ideally purged sooner than that
pass_cache: xous::MemoryRange, pass_cache: xous::MemoryRange, // this can be purged based on a policy, as set below
password_policy: PasswordRetentionPolicy, boot_password_policy: PasswordRetentionPolicy,
update_password_policy: PasswordRetentionPolicy,
susres: susres::Susres, // for disabling suspend/resume susres: susres::Susres, // for disabling suspend/resume
trng: trng::Trng, trng: trng::Trng,
gam: gam::Gam, // for raising UX elements directly gam: gam::Gam, // for raising UX elements directly
@ -126,7 +137,8 @@ impl RootKeys {
kernel, kernel,
sensitive_data, sensitive_data,
pass_cache, 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"), 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"), trng: trng::Trng::new(&xns).expect("couldn't connect to TRNG server"),
gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"), gam: gam::Gam::new(&xns).expect("couldn't connect to GAM"),
@ -135,20 +147,119 @@ impl RootKeys {
keys 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::<u32>();
for d in data.iter_mut() {
*d = 0;
}
core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
}
pub fn suspend(&mut self) { pub fn suspend(&mut self) {
match self.password_policy { match self.boot_password_policy {
PasswordRetentionPolicy::AlwaysKeep => { PasswordRetentionPolicy::AlwaysKeep => {
() ()
}, },
_ => { _ => {
let data = self.sensitive_data.as_slice_mut::<u32>(); self.purge_password(PasswordType::Boot);
for d in data.iter_mut() { }
*d = 0; }
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<PasswordRetentionPolicy>, 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<xous::CID>, current_step: u32, total_steps: u32, finished: bool) { fn update_progress(&mut self, maybe_cid: Option<xous::CID>, current_step: u32, total_steps: u32, finished: bool) {
@ -171,6 +282,17 @@ impl RootKeys {
} }
key 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<xous::SID>) { pub fn try_init_keys(&mut self, maybe_progress: Option<xous::SID>) {
let mut step = 0; // current step let mut step = 0; // current step
@ -186,7 +308,7 @@ impl RootKeys {
step += 1; step += 1;
self.update_progress(progress_cid, step, total, false); 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); let config = self.keyrom.rf(utra::keyrom::DATA_DATA);
if config & keyrom_config::INITIALIZED.ms(1) != 0 { if config & keyrom_config::INITIALIZED.ms(1) != 0 {
@ -214,7 +336,7 @@ impl RootKeys {
// - pepper // - pepper
// provision the 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"); *keyword = self.trng.get_u32().expect("couldn't get random number");
} }

View file

@ -20,23 +20,21 @@ mod implementation;
#[cfg(target_os = "none")] #[cfg(target_os = "none")]
use implementation::*; use implementation::*;
#[cfg(target_os = "none")]
mod bcrypt;
// a stub to try to avoid breaking hosted mode for as long as possible. // a stub to try to avoid breaking hosted mode for as long as possible.
#[cfg(not(target_os = "none"))] #[cfg(not(target_os = "none"))]
mod implementation { mod implementation {
use crate::ROOTKEY_MODAL_NAME; use crate::ROOTKEY_MODAL_NAME;
use gam::modal::*; use crate::PasswordRetentionPolicy;
use xous_ipc::String;
pub struct RootKeys { pub struct RootKeys {
gam: gam::Gam,
ticktimer: ticktimer_server::Ticktimer,
} }
impl RootKeys { impl RootKeys {
pub fn new(xns: &xous_names::XousNames) -> RootKeys { pub fn new(xns: &xous_names::XousNames) -> RootKeys {
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) { pub fn suspend(&self) {
@ -44,11 +42,24 @@ mod implementation {
pub fn resume(&self) { pub fn resume(&self) {
} }
pub fn update_policy(&mut self, policy: Option<PasswordRetentionPolicy>) {
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<xous::SID>) { pub fn try_init_keys(&mut self, _maybe_progress: Option<xous::SID>) {
} }
} }
} }
// 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] #[xous::xous_main]
fn xmain() -> ! { fn xmain() -> ! {
use crate::implementation::RootKeys; use crate::implementation::RootKeys;
@ -62,9 +73,10 @@ fn xmain() -> ! {
Connections allowed to the keys server: Connections allowed to the keys server:
1. Shellchat (to originate update test requests) 1. Shellchat (to originate update test requests)
2. Password entry UX thread 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); log::trace!("registered with NS -- {:?}", keys_sid);
let mut keys = RootKeys::new(&xns); let mut keys = RootKeys::new(&xns);
@ -84,13 +96,6 @@ fn xmain() -> ! {
action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::AlwaysKeep.to_u32().unwrap(), 0, 0, 0,]), action_payload: MenuPayload::Scalar([PasswordRetentionPolicy::AlwaysKeep.to_u32().unwrap(), 0, 0, 0,]),
close_on_select: true, 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 { policy_menu.add_item(MenuItem {
name: String::<64>::from_str(t!("rootkeys.policy_suspend", xous::LANG)), name: String::<64>::from_str(t!("rootkeys.policy_suspend", xous::LANG)),
action_conn: main_cid, action_conn: main_cid,
@ -134,7 +139,7 @@ fn xmain() -> ! {
); );
let mut cur_plaintext = String::<256>::new(); let mut cur_plaintext = String::<256>::new();
let mut cur_policy: Option<PasswordRetentionPolicy> = None; let mut cur_password_type: Option<PasswordType> = None;
loop { loop {
let msg = xous::receive_message(keys_sid).unwrap(); let msg = xous::receive_message(keys_sid).unwrap();
log::trace!("message: {:?}", msg); log::trace!("message: {:?}", msg);
@ -159,14 +164,21 @@ fn xmain() -> ! {
Some(Opcode::PasswordModalEntry) => { Some(Opcode::PasswordModalEntry) => {
let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let mut plaintext_pw = buf.to_original::<gam::modal::TextEntryPayload, _>().unwrap(); let mut plaintext_pw = buf.to_original::<gam::modal::TextEntryPayload, _>().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 if let Some(pw_type) = cur_password_type {
buf.volatile_clear(); keys.hash_and_save_password(plaintext_pw.as_str(), pw_type);
log::info!("cur_plaintext: {}", cur_plaintext); plaintext_pw.volatile_clear(); // ensure the data is destroyed after sending to the keys enclave
// now explicitly request a policy decision buf.volatile_clear();
xous::send_message(main_cid,
Message::new_scalar(Opcode::RaisePolicyMenu.to_usize().unwrap(), 0, 0, 0, 0) // now explicitly request a policy decision
).expect("couldn't raise policy menu follow-up dialogue"); 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) => { Some(Opcode::RaisePolicyMenu) => {
xous::yield_slice(); // let any pending redraws happen before raising this menu xous::yield_slice(); // let any pending redraws happen before raising this menu
@ -174,9 +186,14 @@ fn xmain() -> ! {
policy_menu.activate(); policy_menu.activate();
} }
Some(Opcode::PasswordPolicy) => msg_scalar_unpack!(msg, policy_code, _, _, _, { Some(Opcode::PasswordPolicy) => msg_scalar_unpack!(msg, policy_code, _, _, _, {
cur_policy = FromPrimitive::from_usize(policy_code); if let Some(pw_type) = cur_password_type {
log::info!("cur_policy: {:?}", cur_policy); 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) => { Some(Opcode::MenuRedraw) => {
policy_menu.redraw(); policy_menu.redraw();
}, },