diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index 04d08de4f..bafe9266a 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -1,4 +1,52 @@ { + "rootkeys.backup_key": { + "en": "This is your backup key:\nWRITE IT DOWN, KEEP IT SECRET.", + "ja": "これがバックアップキーです:\n書き留めて、秘密にしてください。", + "zh": "这是您的备份密钥:\n写下来,保密。", + "en-tts": "This is your backup key:\nWRITE IT DOWN, KEEP IT SECRET." + }, + "rootkeys.backup_verify": { + "en": "Would you like to verify that you wrote the backup key down correctly by re-entering it now?", + "ja": "今すぐ再入力して、バックアップキーを正しく書き留めたことを確認しますか?", + "zh": "您想通过现在重新输入来验证您是否正确记下了备份密钥吗?", + "en-tts": "Would you like to verify that you wrote the backup key down correctly by re-entering it now?" + }, + "rootkeys.backup_badpass": { + "en": "Password incorrect. Aborting backup!", + "ja": "正しくないパスワード。 バックアップを中止します!", + "zh": "密码错误。 中止备份!", + "en-tts": "Password incorrect. Aborting backup!" + }, + "rootkeys.backup_key_enter": { + "en": "Please enter your backup key now:", + "ja": "今すぐバックアップキーを入力してください:", + "zh": "请立即输入您的备份密钥:", + "en-tts": "Please enter your backup key now:" + }, + "rootkeys.backup_key_match": { + "en": "Backup key entered correctly!", + "ja": "バックアップキーが正しく入力されました!", + "zh": "备份密钥输入正确!", + "en-tts": "Backup key entered correctly!" + }, + "rootkeys.backup_key_mismatch": { + "en": "Backup key did not match.\n\nThis is your backup key, again:", + "ja": "バックアップキーが一致しませんでした。\n\nこれもバックアップキーです:", + "zh": "备份密钥不匹配。\n\n这是您的备份密钥,再次:", + "en-tts": "Backup key did not match. This is your backup key, again:" + }, + "rootkeys.backup_staged": { + "en": "Backup data is prepared. You may now connect to a host computer and download the backup data bundle.", + "ja": "バックアップデータを用意します。 これで、ホストコンピューターに接続して、バックアップデータバンドルをダウンロードできます。", + "zh": "备份数据已准备好。 您现在可以连接到主机并下载备份数据包。", + "en-tts": "Backup data is prepared. You may now connect to a host computer and download the backup data bundle." + }, + "rootkeys.backup_staging_error": { + "en": "Internal error performing backup. Process aborted.", + "ja": "バックアップの実行中に内部エラーが発生しました。 プロセスが中止されました。", + "zh": "执行备份的内部错误。 进程中止。", + "en-tts": "Internal error performing backup. Process aborted." + }, "rootkeys.bootpass": { "en": "Create a PIN code for device unlock.", "ja": "デバイスのロックを解除するためのPINコードを作成します。", diff --git a/services/root-keys/src/backups.rs b/services/root-keys/src/backups.rs index c70d1d544..11b9229a8 100644 --- a/services/root-keys/src/backups.rs +++ b/services/root-keys/src/backups.rs @@ -11,13 +11,19 @@ const BACKUP_AAD: &'static str = "PDDB backup v0.1.0"; #[derive(Zeroize, Default)] #[zeroize(drop)] -pub(crate) struct BackupKey([u8;32]); +pub(crate) struct BackupKey(pub [u8;32]); #[derive(Zeroize)] #[zeroize(drop)] -pub(crate) struct KeyRomExport([u32; 256]); +pub(crate) struct KeyRomExport(pub [u32; 256]); +impl Default for KeyRomExport { + fn default() -> Self { + KeyRomExport([0u32; 256]) + } +} #[repr(u32)] +#[derive(Copy, Clone)] pub enum BackupOp { /// backup and restore can be manipulated by the OS without updating the ciphertext Backup, @@ -27,6 +33,7 @@ pub enum BackupOp { } #[repr(C, align(8))] +#[derive(Copy, Clone)] pub struct BackupHeader { pub version: u32, // the `ver`s are all serialized SemVers. To be done by the caller. diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index c9bbc93c2..087e9ffd0 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -2344,4 +2344,96 @@ impl<'a> RootKeys { None } } + pub fn get_backup_key(&mut self) -> Option<(backups::BackupKey, backups::KeyRomExport)> { + // make sure the system is sane + self.xous_init_interlock(); + + // derive signing key + let pcache: &mut PasswordCache = unsafe{&mut *(self.pass_cache.as_mut_ptr() as *mut PasswordCache)}; + if pcache.hashed_update_pw_valid == 0 { + self.purge_password(PasswordType::Update); + log::error!("no password was set going into the update routine"); + #[cfg(feature = "hazardous-debug")] + log::debug!("key: {:x?}", pcache.hashed_update_pw); + log::debug!("valid: {}", pcache.hashed_update_pw_valid); + + return None; + } + let mut keypair_bytes: [u8; ed25519_dalek::KEYPAIR_LENGTH] = [0; ed25519_dalek::KEYPAIR_LENGTH]; + let enc_signing_key = self.read_key_256(KeyRomLocs::SELFSIGN_PRIVKEY); + for (key, (&enc_key, &pw)) in + keypair_bytes[..ed25519_dalek::SECRET_KEY_LENGTH].iter_mut() + .zip(enc_signing_key.iter().zip(pcache.hashed_update_pw.iter())) { + *key = enc_key ^ pw; + } + self.compute_key_rollback(&mut keypair_bytes[..ed25519_dalek::SECRET_KEY_LENGTH]); + #[cfg(feature = "hazardous-debug")] + log::debug!("keypair privkey (after anti-rollback): {:x?}", &keypair_bytes[..ed25519_dalek::SECRET_KEY_LENGTH]); + for (key, &src) in keypair_bytes[ed25519_dalek::SECRET_KEY_LENGTH..].iter_mut() + .zip(self.read_key_256(KeyRomLocs::SELFSIGN_PUBKEY).iter()) { + *key = src; + } + // Keypair zeroizes the secret key on drop. + let keypair = Keypair::from_bytes(&keypair_bytes).ok()?; + #[cfg(feature = "hazardous-debug")] + log::debug!("keypair privkey (after anti-rollback + conversion): {:x?}", keypair.secret.to_bytes()); + + // check if the keypair is valid by signing and verifying a short message + let test_data = "whiskey made me do it"; + let test_sig = keypair.sign(test_data.as_bytes()); + match keypair.verify(&test_data.as_bytes(), &test_sig) { + Ok(_) => { + for (&src, dst) in self.read_key_256(KeyRomLocs::FPGA_KEY).iter().zip(pcache.fpga_key.iter_mut()) { + *dst = src; + } + log::debug!("fpga key (encrypted): {:x?}", &pcache.fpga_key); + for (fkey, &pw) in pcache.fpga_key.iter_mut().zip(pcache.hashed_update_pw.iter()) { + *fkey = *fkey ^ pw; + } + pcache.fpga_key_valid = 1; + // copy the plaintext FPGA key into the backup key structure, which implements the zeroize trait. + let mut bkey = backups::BackupKey::default(); + bkey.0.copy_from_slice(&pcache.fpga_key); + // copy the key rom into the backup keyrom structure, which implements the zeroize trait. + let mut backup_rom = backups::KeyRomExport::default(); + for i in 0..256 { + self.keyrom.wfo(utra::keyrom::ADDRESS_ADDRESS, i); + backup_rom.0[i as usize] = self.keyrom.rf(utra::keyrom::DATA_DATA); + } + // we're done with the password now, clear all the temps + self.purge_password(PasswordType::Update); + for b in keypair_bytes.iter_mut() { + *b = 0; + } + self.purge_sensitive_data(); + Some((bkey, backup_rom)) + }, + Err(e) => { + log::warn!("update password was not connect ({:?})", e); + self.purge_password(PasswordType::Update); + for b in keypair_bytes.iter_mut() { + *b = 0; + } + None + } + } + } + pub fn write_backup(&mut self, mut header: backups::BackupHeader, backup_ct: backups::BackupDataCt) -> Result<(), xous::Error> { + header.op = backups::BackupOp::Backup; // set the "we're backing up" flag + self.spinor.patch( + self.kernel(), + self.kernel_base(), + header.as_ref(), + xous::BACKUP_OFFSET + ).map_err(|_| xous::Error::InternalError)?; + + self.spinor.patch( + self.kernel(), + self.kernel_base(), + backup_ct.as_ref(), + xous::BACKUP_OFFSET + size_of::() as u32 + ).map_err(|_| xous::Error::InternalError)?; + + Ok(()) + } } diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index 8b11dd52f..06e6951fd 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -102,11 +102,13 @@ impl RootKeys { ).expect("couldn't send message to root keys"); } - pub fn do_create_backup_ux_flow(&self) { - send_message(self.conn, - Message::new_scalar(Opcode::CreateBackup.to_usize().unwrap(), - 0, 0, 0, 0) - ).expect("couldn't send message to root keys"); + pub fn do_create_backup_ux_flow(&self, metadata: backups::BackupHeader) { + let mut alloc = BackupHeaderIpc::default(); + let mut data = [0u8; core::mem::size_of::()]; + data.copy_from_slice(metadata.as_ref()); + alloc.data = Some(data); + let mut buf = Buffer::into_buf(alloc).unwrap(); + buf.send(self.conn, Opcode::CreateBackup.to_u32().unwrap()).unwrap(); } pub fn do_restore_backup_ux_flow(&self) { send_message(self.conn, diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index 9a5474a9e..1831ebefe 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -434,6 +434,7 @@ fn main() -> ! { let mut reboot_initiated = false; let mut aes_sender: Option = None; + let mut backup_header: Option = None; loop { let mut msg = xous::receive_message(keys_sid).unwrap(); log::debug!("message: {:?}", msg); @@ -1201,7 +1202,7 @@ fn main() -> ! { keys.set_prompt_for_update(if state == 1 {true} else {false}); }), Some(Opcode::ShouldRestore) => { - let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let mut buf = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; let maybe_header = keys.read_backup_header(); let mut ret = BackupHeaderIpc::default(); if let Some(header) = maybe_header { @@ -1212,6 +1213,16 @@ fn main() -> ! { buf.replace(ret).unwrap(); } Some(Opcode::CreateBackup) => { + let buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let ipc = buf.to_original::().unwrap(); + if let Some(d) = ipc.data { + let mut header = backups::BackupHeader::default(); + header.as_mut().copy_from_slice(&d); + backup_header = Some(header); + } else { + log::error!("Create backup was called, but no header data was provided"); + continue; + } keys.set_ux_password_type(Some(PasswordType::Update)); password_action.set_action_opcode(Opcode::UxCreateBackupPwReturn.to_u32().unwrap()); rootkeys_modal.modify( @@ -1224,7 +1235,7 @@ fn main() -> ! { log::info!("{}ROOTKEY.UPDPW,{}", xous::BOOKEND_START, xous::BOOKEND_END); rootkeys_modal.activate(); } - Some(Opcode::UxUpdateGwPasswordReturn) => { + Some(Opcode::UxCreateBackupPwReturn) => { let mut buf = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let plaintext_pw = buf.to_original::().unwrap(); @@ -1234,7 +1245,50 @@ fn main() -> ! { keys.set_ux_password_type(None); // check if the entered password is valid. - + if let Some((fpga_key, keyrom)) = keys.get_backup_key() { + // this gets shown in an "insecure" modal but -- we're expatriating this data anyways, so meh? + modals.show_bip39(Some(t!("rootkeys.backup_key", xous::LANG)), &fpga_key.0.to_vec()).ok(); + // let the user confirm the key, or skip it. YOLO! + loop { + modals.add_list_item(t!("rootkeys.confirm.yes", xous::LANG)).expect("modals error"); + modals.add_list_item(t!("rootkeys.confirm.no", xous::LANG)).expect("modals error"); + log::info!("{}ROOTKEY.CONFIRM,{}", xous::BOOKEND_START, xous::BOOKEND_END); + match modals.get_radiobutton(t!("rootkeys.backup_verify", xous::LANG)) { + Ok(response) => { + if response == t!("rootkeys.confirm.yes", xous::LANG) { + match modals.input_bip39(Some(t!("rootkeys.backup_key_enter", xous::LANG))) { + Ok(verify) => { + if &verify == &fpga_key.0 { + modals.show_notification(t!("rootkeys.backup_key_match", xous::LANG), None).ok(); + } else { + modals.show_bip39(Some(t!("rootkeys.backup_key_mismatch", xous::LANG)), &fpga_key.0.to_vec()).ok(); + } + } + _ => { + modals.show_bip39(Some(t!("rootkeys.backup_key_mismatch", xous::LANG)), &fpga_key.0.to_vec()).ok(); + } + } + } else { + break; + } + } + _ => break, + } + } + // now write out the backup + let backup_ct = backups::create_backup(fpga_key, backup_header.unwrap(), keyrom); + // this final statement has a take/unwrap to set backup_header back to None + match keys.write_backup(backup_header.take().unwrap(), backup_ct) { + Ok(_) => { + modals.show_notification(t!("rootkeys.backup_staged", xous::LANG), None).ok(); + } + Err(_) => { + modals.show_notification(t!("rootkeys.backup_staging_error", xous::LANG), None).ok(); + } + } + } else { + modals.show_notification(t!("rootkeys.backup_badpass", xous::LANG), None).ok(); + } } Some(Opcode::TestUx) => msg_blocking_scalar_unpack!(msg, _arg, _, _, _, { // dummy test for now