From 2ff9163789ef03835d919e1fcf7d7cb4195164d0 Mon Sep 17 00:00:00 2001 From: bunnie Date: Sun, 9 Oct 2022 01:10:42 +0800 Subject: [PATCH] add checksums to PDDB backup every 1MiB block is checksummed with a sha512/256 truncated to 128 bits. This is used to confirm the media and transport integrity only. It is not intended to be a cryptographic check, it just confirms that the backup data was transferred correctly assuming no intentionally malicious actors in the middle. --- services/pddb/locales/i18n.json | 6 +++ services/pddb/src/api.rs | 13 ++++++ services/pddb/src/backend/hw.rs | 45 ++++++++++++++----- services/pddb/src/lib.rs | 32 ++++++++++++++ services/pddb/src/main.rs | 39 +++++++++++++++++ services/root-keys/locales/i18n.json | 8 +++- services/root-keys/src/api.rs | 55 +++++++++++++++++++++++- services/root-keys/src/backups.rs | 46 -------------------- services/root-keys/src/implementation.rs | 20 ++++++++- services/root-keys/src/lib.rs | 3 +- services/root-keys/src/main.rs | 12 +++++- services/status/locales/i18n.json | 6 +++ services/status/src/main.rs | 54 +++++++++++++++++++---- services/status/src/time.rs | 8 +++- 14 files changed, 272 insertions(+), 75 deletions(-) diff --git a/services/pddb/locales/i18n.json b/services/pddb/locales/i18n.json index a6e6d3764..023e8d762 100644 --- a/services/pddb/locales/i18n.json +++ b/services/pddb/locales/i18n.json @@ -83,6 +83,12 @@ "zh": "枚举完成。\n\n我们要继续搅拌吗? 这个过程大约需要 20 分钟。", "en-tts": "Enumeration finished.\n\nShall we proceed to churning? This process takes about 20 minutes." }, + "pddb.checksums": { + "en": "PDDB computing checksums...", + "ja": "PDDB はチェックサムを計算しています...", + "zh": "PDDB 正在计算校验和...", + "en-tts": "PDDB computing checksums..." + }, "pddb.okay": { "en": "Okay", "ja": "OK", diff --git a/services/pddb/src/api.rs b/services/pddb/src/api.rs index 00c73142b..06ef95024 100644 --- a/services/pddb/src/api.rs +++ b/services/pddb/src/api.rs @@ -216,6 +216,19 @@ pub(crate) enum Opcode { /// run a test or diagnostic command (depends on the build) InternalTest = 47, + /// Clear password cache and ask for it again + UncacheAndAskPassword = 48, + + /// Unmount the PDDB. + TryUnmount = 49, + + /// Compute a block of backup hashes + ComputeBackupHashes = 50, + + /// Halt PDDB operation. This is used to prevent any further actions on the PDDB, i.e. + /// in prepration for a system shutdown or backup event. + PddbHalt = 51, + /// This key type could not be decoded InvalidOpcode = u32::MAX as _, } diff --git a/services/pddb/src/backend/hw.rs b/services/pddb/src/backend/hw.rs index fef451807..aad430e1e 100644 --- a/services/pddb/src/backend/hw.rs +++ b/services/pddb/src/backend/hw.rs @@ -1,10 +1,13 @@ use std::convert::TryInto; use crate::*; +use backend::bcrypt::*; use aes_gcm_siv::{Nonce, Tag, Aes256GcmSiv}; use aes_gcm_siv::aead::{Aead, Payload}; use aes::{Aes256, Block, BLOCK_SIZE}; use aes::cipher::{BlockDecrypt, BlockEncrypt, KeyInit, generic_array::GenericArray}; +use modals::Modals; +use root_keys::api::KeywrapError; use root_keys::api::AesRootkeyType; use spinor::SPINOR_BULK_ERASE_SIZE; use subtle::ConstantTimeEq; @@ -27,6 +30,9 @@ type FspaceSet = BTreeSet::; use zeroize::Zeroize; +use sha2::{FallbackStrategy, Sha512Trunc256}; +use digest::Digest; + #[cfg(feature="migration1")] use crate::backend::migration1to2::*; @@ -607,7 +613,6 @@ impl PddbOs { self.rootkeys.clear_password(AesRootkeyType::User0); } pub (crate) fn try_login(&mut self) -> PasswordState { - use root_keys::api::KeywrapError; if self.system_basis_key.is_none() || self.cipher_ecb.is_none() { let scd = self.static_crypto_data_get(); if scd.version == 0xFFFF_FFFF { // system is in the blank state @@ -1613,8 +1618,6 @@ impl PddbOs { fn kcom_func(&self, key: &[u8; 32], nonce_com: &[u8; 32]) -> ([u8; 32], [u8; 32]) { - use sha2::{FallbackStrategy, Sha512Trunc256}; - use digest::Digest; let mut h_enc = Sha512Trunc256::new_with_strategy(FallbackStrategy::SoftwareOnly); h_enc.update(key); @@ -2467,10 +2470,6 @@ impl PddbOs { /// Derives a 256-bit AES encryption key for a basis given a basis name and its password. /// You will also need to derive the AAD for the basis using the basis_name. pub(crate) fn basis_derive_key(&self, basis_name: &str, password: &str) -> BasisKeys { - use sha2::{FallbackStrategy, Sha512Trunc256}; - use digest::Digest; - use backend::bcrypt::*; - // 1. derive the salt from the "key" region. First step is to create the salt lookup // table, which is done by hashing the name and password together with SHA-512 // manage the allocation of the data for the basis & password explicitly so that we may wipe them later @@ -2545,6 +2544,34 @@ impl PddbOs { pub(crate) fn reset_dont_ask_init(&self) { self.rootkeys.do_reset_dont_ask_init(); } + + pub(crate) fn checksums(&self, modals: Option::<&Modals>) -> root_keys::api::Checksums { + let mut checksums = root_keys::api::Checksums::default(); + let pddb = self.pddb_mr.as_slice(); + if let Some(m) = modals { + m.start_progress( + t!("pddb.checksums", xous::LANG), + 0, + checksums.checksums.len() as u32, + 0 + ).ok(); + } + for (index, region) in pddb.chunks(root_keys::api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE).enumerate() { + assert!(region.len() == root_keys::api::CHECKSUM_BLOCKLEN_PAGE as usize * PAGE_SIZE, "CHECKSUM_BLOCKLEN_PAGE is not an even divisor of the PDDB size"); + let mut hasher = Sha512Trunc256::new_with_strategy(FallbackStrategy::HardwareThenSoftware); + hasher.update(region); // reserve the first 32 bytes of salt for the HKDF + let digest = hasher.finalize(); + // copy only the first 128 bits of the hash into the checksum array + checksums.checksums[index].copy_from_slice(&digest.as_slice()[..16]); + if let Some(m) = modals { + m.update_progress(index as u32).ok(); + } + } + if let Some(m) = modals { + m.finish_progress().ok(); + } + checksums + } //-------------------------------- TESTING ----------------------------------------- // always gated behind a feature flag. Includes routines that are nonsensicle in normal operation at best, // and very dangerous from a security perspective at worst. @@ -2660,10 +2687,6 @@ impl PddbOs { /// by updated keys by the time this routine is called. #[cfg(feature="migration1")] pub(crate) fn basis_derive_key_v00_00_01_01(&self, basis_name: &str, password: &str, scd: &StaticCryptoDataV1) -> [u8; AES_KEYSIZE] { - use sha2::{FallbackStrategy, Sha512Trunc256}; - use digest::Digest; - use backend::bcrypt::*; - // 1. derive the salt from the "key" region. First step is to create the salt lookup // table, which is done by hashing the name and password together with SHA-512 // manage the allocation of the data for the basis & password explicitly so that we may wipe them later diff --git a/services/pddb/src/lib.rs b/services/pddb/src/lib.rs index 8c94a973f..0dbaba3db 100644 --- a/services/pddb/src/lib.rs +++ b/services/pddb/src/lib.rs @@ -150,6 +150,8 @@ impl Pddb { _ => panic!("Internal error"), } } + /// Attempts to mount the system basis. Returns `true` on success, `false` on failure. + /// This call may cause a password request box to pop up, in the case that the boot PIN is not currently cached. pub fn try_mount(&self) -> bool { let ret = send_message(self.conn, Message::new_blocking_scalar( Opcode::TryMount.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query"); @@ -160,6 +162,36 @@ impl Pddb { _ => panic!("Internal error"), } } + /// Unmounts the PDDB. First attempts to unmount any open secret bases, and then finally unmounts + /// the system basis. Returns `true` on success, `false` on failure. + pub fn try_unmount(&self) -> bool { + let ret = send_message(self.conn, Message::new_blocking_scalar( + Opcode::TryUnmount.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't execute IsMounted query"); + match ret { + xous::Result::Scalar1(code) => { + if code == 0 {false} else {true} + }, + _ => panic!("Internal error"), + } + } + /// This is a non-blocking message that permanently halts the PDDB server by wedging it in an infinite loop. + /// It is meant to be called prior to system shutdows or backups, to ensure that other auto-mounting procesess + /// don't undo the shutdown procedure because of an ill-timed "cron" job (the system doesn't literally have + /// a cron daemon, but it does have the notion of long-running background jobs that might do something like + /// trigger an NTP update, which would then try to write the updated time to the PDDB). + pub fn pddb_halt(&self) { + send_message(self.conn, Message::new_scalar( + Opcode::PddbHalt.to_usize().unwrap(), 0, 0, 0, 0)).expect("Couldn't halt the PDDB"); + } + /// Computes checksums on the entire PDDB database. This operation can take some time and causes a progress + /// bar to pop up. This should be called only after the PDDB has been unmounted, to ensure that the disk + /// contents do not change after the checksums have been computed. + pub fn compute_checksums(&self) -> root_keys::api::Checksums { + let alloc = root_keys::api::Checksums::default(); + let mut buf = Buffer::into_buf(alloc).expect("Couldn't convert memory structure"); + buf.lend_mut(self.conn, Opcode::ComputeBackupHashes.to_u32().unwrap()).expect("Couldn't execute ComputeBackupHashes"); + buf.to_original::().expect("Couldn't convert IPC structure") + } /// return a list of all open bases pub fn list_basis(&self) -> Vec:: { let list_alloc = PddbBasisList { diff --git a/services/pddb/src/main.rs b/services/pddb/src/main.rs index 6dcca5e63..158b38b5b 100644 --- a/services/pddb/src/main.rs +++ b/services/pddb/src/main.rs @@ -597,6 +597,8 @@ fn wrapped_main() -> ! { panic!("Unsupported syscall!"); } + let tt = ticktimer_server::Ticktimer::new().unwrap(); + // register a suspend/resume listener let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Early), &xns, Opcode::SuspendResume as u32, my_cid).expect("couldn't create suspend/resume object"); @@ -1503,6 +1505,39 @@ fn wrapped_main() -> ! { #[cfg(not(feature="hwtest"))] xous::return_scalar2(msg.sender, 0, 0).ok(); }), + Opcode::TryUnmount => { + basis_cache.sync(&mut pddb_os, None).expect("can't sync for unmount"); + // unmount all the open basis first + let mut mounted_bases = basis_cache.basis_list(); + mounted_bases.retain(|x| x != PDDB_DEFAULT_SYSTEM_BASIS); + for basis in mounted_bases { + basis_cache.basis_unmount(&mut pddb_os, &basis).expect("can't unmount extra bases"); + } + if basis_cache.basis_list().len() != 1 { + log::warn!("Couldn't unmount extra bases before unmounting the system basis. Failing unmount operation!"); + xous::return_scalar(msg.sender, 0).unwrap(); + } + // finally, unmount the system basis + basis_cache.basis_unmount(&mut pddb_os, PDDB_DEFAULT_SYSTEM_BASIS).expect("can't unmount system basis"); + if basis_cache.basis_list().len() == 0 { + log::info!(".System basis is unmounted."); + xous::return_scalar(msg.sender, 1).unwrap(); + } else { + log::warn!("Couldn't unmount the .System basis!"); + xous::return_scalar(msg.sender, 0).unwrap(); + } + } + Opcode::PddbHalt => { + loop { + log::info!("PDDB operation halted. No new PDDB requests will be honored!"); + tt.sleep_ms(10_000).unwrap(); + } + } + Opcode::ComputeBackupHashes => { + let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) }; + let result = pddb_os.checksums(Some(&modals)); + buffer.replace(result).unwrap(); + } Opcode::Quit => { log::warn!("quitting the PDDB server"); send_message( @@ -1512,6 +1547,10 @@ fn wrapped_main() -> ! { xous::return_scalar(msg.sender, 0).unwrap(); break } + Opcode::UncacheAndAskPassword => { + // lock_and_ensure_password(&modals, &mut pddb_os, pw_cid); + xous::return_scalar(msg.sender, 1).unwrap(); + } Opcode::InvalidOpcode => { log::error!("couldn't convert opcode: {:?}", msg); } diff --git a/services/root-keys/locales/i18n.json b/services/root-keys/locales/i18n.json index 6af4ec207..a80e9882d 100644 --- a/services/root-keys/locales/i18n.json +++ b/services/root-keys/locales/i18n.json @@ -84,11 +84,17 @@ "en-tts": "Preparing backup state..." }, "rootkeys.backup_staged": { - "en": "Backup data is prepared, and PDDB operation halted.\nConnect to a host computer by USB, and download the backup data bundle.\nScan the QR code for instructions:", + "en": "Backup data is prepared; PDDB is unmounted.\nConnect to a host computer by USB, and download the backup data bundle.\nScan the QR code for instructions:", "ja": "バックアップデータを用意します。 これで、ホストコンピューターに接続して、バックアップデータバンドルをダウンロードできます。", "zh": "备份数据已准备好。 您现在可以连接到主机并下载备份数据包。", "en-tts": "Backup data is prepared. You may now connect to a host computer and download the backup data bundle." }, + "rootkeys.backup_waiting": { + "en": "⚠ System in backup mode! ⚠\nTo resume normal function, either initiate a backup via USB, or reboot the device.", + "ja": "⚠ システムはバックアップモードです! ⚠\n通常の機能を再開するには、USB 経由でバックアップを開始するか、デバイスを再起動してください。", + "zh": "⚠ 系统处于备份模式! ⚠\n要恢复正常功能,请通过 USB 启动备份,或重新启动设备。", + "en-tts": "System in backup mode! To resume normal function, either initiate a backup via USB, or reboot the device." + }, "rootkeys.backup_staging_error": { "en": "Internal error performing backup. Process aborted.", "ja": "バックアップの実行中に内部エラーが発生しました。 プロセスが中止されました。", diff --git a/services/root-keys/src/api.rs b/services/root-keys/src/api.rs index 1a72dc103..8077ed879 100644 --- a/services/root-keys/src/api.rs +++ b/services/root-keys/src/api.rs @@ -249,10 +249,15 @@ pub (crate) struct KeyWrapper { #[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] pub (crate) struct BackupHeaderIpc { pub data: Option<[u8; core::mem::size_of::()]>, + pub checksums: Option, + } impl Default for BackupHeaderIpc { fn default() -> Self { - BackupHeaderIpc { data: None::<[u8; core::mem::size_of::()]> } + BackupHeaderIpc { + data: None::<[u8; core::mem::size_of::()]>, + checksums: None, + } } } @@ -442,4 +447,50 @@ impl DerefMut for BackupHeader { as &mut [u8] } } -} \ No newline at end of file +} + +/// The Checksums structure is an array of 16-byte (128-bit) checksums that +/// are applied to backed up data. There is one checksum per block region +/// (currently set to 1MiB). +/// +/// The actual checksum is a SHA512 of the region, but with only the first +/// 128 bits stored. The goal of the checksum isn't a cryptographic tamper +/// proofing -- this is already handled by the underlying AEAD's that are +/// applied to the PDDB. The utility of the checksum is to detect media +/// or transmission errors in storage, without having to fully decrypt +/// the entire PDDB to look for corruption. We use SHA512 and truncate it to +/// 128 bits not because it's the optimal hash, but because it's what we +/// have a hardware accelerator for. We don't truncate to 256 bits because +/// we're trying to pack as many checksums into a 4k header, and going to +/// 128 bits is still "strong" for a checksum and allows us to get the region +/// size down to 1MiB, which is a reasonably sized region for a retry-download +/// in case a checksum error is found. +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[repr(C, align(8))] +pub struct Checksums { + pub checksums: [[u8; 16]; crate::api::TOTAL_CHECKSUMS as usize], +} +impl Default for Checksums { + fn default() -> Self { + Checksums { + checksums: [[0u8; 16]; crate::api::TOTAL_CHECKSUMS as usize], + } + } +} +impl Deref for Checksums { + type Target = [u8]; + fn deref(&self) -> &[u8] { + unsafe { + core::slice::from_raw_parts(self as *const Checksums as *const u8, size_of::()) + as &[u8] + } + } +} +impl DerefMut for Checksums { + fn deref_mut(&mut self) -> &mut [u8] { + unsafe { + core::slice::from_raw_parts_mut(self as *mut Checksums as *mut u8, size_of::()) + as &mut [u8] + } + } +} diff --git a/services/root-keys/src/backups.rs b/services/root-keys/src/backups.rs index 2daad7a5c..a14fc9cb4 100644 --- a/services/root-keys/src/backups.rs +++ b/services/root-keys/src/backups.rs @@ -101,52 +101,6 @@ impl DerefMut for BackupDataCt { } } -/// The Checksums structure is an array of 16-byte (128-bit) checksums that -/// are applied to backed up data. There is one checksum per block region -/// (currently set to 1MiB). -/// -/// The actual checksum is a SHA512 of the region, but with only the first -/// 128 bits stored. The goal of the checksum isn't a cryptographic tamper -/// proofing -- this is already handled by the underlying AEAD's that are -/// applied to the PDDB. The utility of the checksum is to detect media -/// or transmission errors in storage, without having to fully decrypt -/// the entire PDDB to look for corruption. We use SHA512 and truncate it to -/// 128 bits not because it's the optimal hash, but because it's what we -/// have a hardware accelerator for. We don't truncate to 256 bits because -/// we're trying to pack as many checksums into a 4k header, and going to -/// 128 bits is still "strong" for a checksum and allows us to get the region -/// size down to 1MiB, which is a reasonably sized region for a retry-download -/// in case a checksum error is found. -#[repr(C, align(8))] -pub(crate) struct Checksums { - pub checksums: [[u8; 16]; crate::api::TOTAL_CHECKSUMS as usize], -} -impl Default for Checksums { - fn default() -> Self { - Checksums { - checksums: [[0u8; 16]; crate::api::TOTAL_CHECKSUMS as usize], - } - } -} -impl Deref for Checksums { - type Target = [u8]; - fn deref(&self) -> &[u8] { - unsafe { - core::slice::from_raw_parts(self as *const Checksums as *const u8, size_of::()) - as &[u8] - } - } -} -impl DerefMut for Checksums { - fn deref_mut(&mut self) -> &mut [u8] { - unsafe { - core::slice::from_raw_parts_mut(self as *mut Checksums as *mut u8, size_of::()) - as &mut [u8] - } - } -} - - /// Derive a key commitment. This takes in a base `key`, which is 256 bits; /// a `nonce` which is the 96-bit nonce used in the AES-GCM-SIV for a given block; /// and `nonce_com` which is the commitment nonce, set at 256 bits. diff --git a/services/root-keys/src/implementation.rs b/services/root-keys/src/implementation.rs index 7176db4eb..cc774ac89 100644 --- a/services/root-keys/src/implementation.rs +++ b/services/root-keys/src/implementation.rs @@ -2725,7 +2725,11 @@ impl<'a> RootKeys { } } } - pub fn write_backup(&mut self, mut header: BackupHeader, backup_ct: backups::BackupDataCt) -> Result<(), xous::Error> { + pub fn write_backup(&mut self, + mut header: BackupHeader, + backup_ct: backups::BackupDataCt, + checksums: Option + ) -> Result<(), xous::Error> { header.op = BackupOp::Backup; // set the "we're backing up" flag // condense the data into a single block, to reduce read/write cycles on the block @@ -2742,10 +2746,22 @@ impl<'a> RootKeys { block[size_of::() + size_of::()..] .copy_from_slice(digest.as_slice()); + // stage the artifacts into a full page header + const PAGE_LEN: usize = 4096; + let mut page = [0xFFu8; PAGE_LEN]; + // place the metadata at the top of the block + page[..block.len()].copy_from_slice(&block); + if let Some(cs) = checksums { + use std::ops::Deref; + let cs_slice = cs.deref(); + // stage the checksums, if any, aligned to the end of the block + assert!(block.len() + cs_slice.len() < PAGE_LEN, "Error: checksum block has outgrown the available space"); + page[PAGE_LEN - cs_slice.len()..].copy_from_slice(cs_slice); + } self.spinor.patch( self.kernel(), self.kernel_base(), - &block, + &page, xous::KERNEL_BACKUP_OFFSET ).map_err(|_| xous::Error::InternalError)?; Ok(()) diff --git a/services/root-keys/src/lib.rs b/services/root-keys/src/lib.rs index 3c9aeea86..06e348f0a 100644 --- a/services/root-keys/src/lib.rs +++ b/services/root-keys/src/lib.rs @@ -133,11 +133,12 @@ impl RootKeys { ).expect("couldn't send message to root keys"); } - pub fn do_create_backup_ux_flow(&self, metadata: BackupHeader) { + pub fn do_create_backup_ux_flow(&self, metadata: BackupHeader, checksums: Option) { let mut alloc = BackupHeaderIpc::default(); let mut data = [0u8; core::mem::size_of::()]; data.copy_from_slice(metadata.as_ref()); alloc.data = Some(data); + alloc.checksums = checksums; let buf = Buffer::into_buf(alloc).unwrap(); buf.send(self.conn, Opcode::CreateBackup.to_u32().unwrap()).unwrap(); } diff --git a/services/root-keys/src/main.rs b/services/root-keys/src/main.rs index f30ca8a25..3071d19d5 100644 --- a/services/root-keys/src/main.rs +++ b/services/root-keys/src/main.rs @@ -503,6 +503,7 @@ fn main() -> ! { let mut aes_sender: Option = None; let mut backup_header: Option = None; let mut deferred_response: Option = None; + let mut checksums: Option = None; // storage for PDDB backup checksums loop { let mut msg = xous::receive_message(keys_sid).unwrap(); let opcode: Option = FromPrimitive::from_usize(msg.body.id()); @@ -1408,6 +1409,7 @@ fn main() -> ! { log::error!("Create backup was called, but no header data was provided"); continue; } + checksums = ipc.checksums; keys.set_ux_password_type(Some(PasswordType::Update)); password_action.set_action_opcode(Opcode::UxCreateBackupPwReturn.to_u32().unwrap()); rootkeys_modal.modify( @@ -1468,7 +1470,7 @@ fn main() -> ! { // 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) { + match keys.write_backup(backup_header.take().unwrap(), backup_ct, checksums.take()) { Ok(_) => { // this switchover takes a couple seconds, give some user feedback modals.dynamic_notification(Some(t!("rootkeys.backup_prepwait", xous::LANG)), None).ok(); @@ -1477,7 +1479,10 @@ fn main() -> ! { usbd.debug_usb(Some(false)).unwrap(); modals.dynamic_notification_close().ok(); // there will be a bit of a pause while the QR text renders, but we'll have to fix that with other optimizations... + log::info!("{}BACKUP.STAGED,{}", xous::BOOKEND_START, xous::BOOKEND_END); modals.show_notification(t!("rootkeys.backup_staged", xous::LANG), Some("https://github.com/betrusted-io/betrusted-wiki/wiki/Backups")).ok(); + // this informs users who dismiss the QR code that they must reboot to resume normal operation + modals.show_notification(t!("rootkeys.backup_waiting", xous::LANG), None).ok(); } Err(_) => { modals.show_notification(t!("rootkeys.backup_staging_error", xous::LANG), None).ok(); @@ -1511,7 +1516,7 @@ fn main() -> ! { let mut showed_zero_key_notice = false; if let Ok((mut header, ct)) = keys.read_backup() { if header.op != BackupOp::Restore { - log::warn!("Header op was not Restore. Aborting!"); + log::warn!("Header op was not Restore. Found {:?} instead. Aborting!", header.op); modals.show_notification(t!("rootkeys.restore_corrupt", xous::LANG), None).ok(); if let Some(sender) = deferred_response { xous::return_scalar(sender, 1).ok(); @@ -1542,6 +1547,9 @@ fn main() -> ! { header.op = pt.header.op; // now check that the two records are identical if pt.header.deref() != header.deref() { + log::warn!("Corruption detected:"); + log::info!("plaintext header: {:?}", pt.header); + log::info!("encrypted header: {:?}", header); modals.show_notification(t!("rootkeys.restore_corrupt", xous::LANG), None).ok(); if let Some(sender) = deferred_response { xous::return_scalar(sender, 1).ok(); diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 6e00411b2..d1dc1a7aa 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -23,6 +23,12 @@ "zh": "忽略此更新", "en-tts": "Ignore this update" }, + "socup.unmount_fail": { + "ja": "バックアップの準備で PDDB をアンマウントできませんでした。 バックアップが中止されました。", + "en": "Couldn't unmount PDDB in preparation for backup. Backup aborted.", + "zh": "无法卸载 PDDB 以准备备份。 备份中止。", + "en-tts": "Couldn't unmount PDDB in preparation for backup. Backup aborted." + }, "ecup.invalid": { "ja": "ECファームウェアパッケージが破損しているか無効です: ", "en": "EC firmware package is corrupted or invalid: ", diff --git a/services/status/src/main.rs b/services/status/src/main.rs index 9276bb6ba..d42a66146 100644 --- a/services/status/src/main.rs +++ b/services/status/src/main.rs @@ -70,6 +70,7 @@ pub(crate) enum StatusOpcode { /// Prepare for a backup PrepareBackup, + PrepareBackupPhase2, /// Tells keyboard watching thread that a new keypress happened. Keypress, @@ -562,6 +563,8 @@ fn wrapped_main() -> ! { 0, 0, 0, 0,) ).expect("couldn't exit the gutter server"); gutter.join().expect("status boot gutter server did not exit gracefully"); + // allocate some storage for backup checksums + let checksums: Arc::>> = Arc::new(Mutex::new(None)); // --------------------------- graphical loop timing let mut stats_phase: usize = 0; @@ -1058,16 +1061,45 @@ fn wrapped_main() -> ! { com.set_backlight(0, 0).expect("cannot set backlight off"); }, Some(StatusOpcode::PrepareBackup) => { - // sync the PDDB to disk prior to making backups - let pddb = pddb::Pddb::new(); - pddb.sync().expect("couldn't synchronize PDDB to disk"); + // disconnect from the network, so that incoming network packets don't trigger any processes that + // could write to the PDDB. + netmgr.connection_manager_wifi_off_and_stop().ok(); - // TODO: add PDDB hash map computations here + UX flow to indicate pause + // close the active app and switch to shellchat + ticktimer.sleep_ms(100).ok(); + sec_notes.lock().unwrap().remove(&"current_app".to_string()); + sec_notes.lock().unwrap().insert("current_app".to_string(), format!("Running: Shellchat").to_string()); + gam.switch_to_app(gam::APP_NAME_SHELLCHAT, security_tv.token.unwrap()).expect("couldn't raise shellchat"); + secnotes_force_redraw = true; - // TODO: add a call to PDDB that blocks the PDDB forever. The system is rebooted - // after the backup is done. However, this call ensures that the PDDB does not - // get updated mid-way through a backup + // unmount the PDDB and compute a checksum; then halt the PDDB to freeze its state + thread::spawn({ + // thread the checksum process, because it can take a long time. + // we might also want to make it optional down the road, in case people want a "fast" backup option + let checksums = checksums.clone(); + move || { + // sync the PDDB to disk prior to making backups + let pddb = pddb::Pddb::new(); + if !pddb.try_unmount() { + // this is a rare case path...not worth turning the modals object into a mutex-wrapped thing just for this + let xns = xous_names::XousNames::new().unwrap(); + let modals = modals::Modals::new(&xns).unwrap(); + modals.show_notification(t!("socup.unmount_fail", xous::LANG), None).ok(); + } else { + *checksums.lock().unwrap() = Some(pddb.compute_checksums()); + // PDDB is halted forever. However, the system is reset after a backup is run. + pddb.pddb_halt(); + // now trigger phase 2 of the backup + log::info!("{}BACKUP.PHASE2,{}", xous::BOOKEND_START, xous::BOOKEND_END); + send_message(cb_cid, + Message::new_scalar(StatusOpcode::PrepareBackupPhase2.to_usize().unwrap(), 0, 0, 0, 0) + ).expect("couldn't initiate phase 2 backup"); + } + } + }); + }, + Some(StatusOpcode::PrepareBackupPhase2) => { let mut metadata = root_keys::api::BackupHeader::default(); // note: default() should set the language correctly by default since it's a systemwide constant metadata.timestamp = localtime.get_local_time_ms().unwrap_or(0); @@ -1080,7 +1112,13 @@ fn wrapped_main() -> ! { let map = kbd.get_keymap().expect("couldn't get key mapping"); let map_serialize: BackupKeyboardLayout = map.into(); metadata.kbd_layout = map_serialize.into(); - keys.lock().unwrap().do_create_backup_ux_flow(metadata); + // the backup process is coded to accept the option of no checksums, but the UX currently + // always computes it. + if let Some(checksums) = checksums.lock().unwrap().take() { + keys.lock().unwrap().do_create_backup_ux_flow(metadata, Some(checksums)); + } else { + keys.lock().unwrap().do_create_backup_ux_flow(metadata, None); + } } Some(StatusOpcode::Quit) => { xous::return_scalar(msg.sender, 1).ok(); diff --git a/services/status/src/time.rs b/services/status/src/time.rs index 8ca5010e1..8f2186654 100644 --- a/services/status/src/time.rs +++ b/services/status/src/time.rs @@ -413,7 +413,9 @@ pub fn start_time_server() { utc_offset_ms = offset; offset_key.seek(SeekFrom::Start(0)).expect("couldn't seek"); log::info!("setting offset to {} secs", offset / 1000); - assert_eq!(offset_key.write(&offset.to_le_bytes()).unwrap_or(0), 8, "couldn't commit UTC time offset to PDDB"); + if offset_key.write(&offset.to_le_bytes()).unwrap_or(0) != 8 { + log::warn!("Couldn't commit the latest time update. Is the PDDB mounted?"); + } offset_key.flush().expect("couldn't flush PDDB"); }), Some(TimeOp::SetTzOffsetMs) => xous::msg_scalar_unpack!(msg, tz_hi_ms, tz_lo_ms, _, _, { @@ -428,7 +430,9 @@ pub fn start_time_server() { tz_offset_ms = tz_ms; tz_key.seek(SeekFrom::Start(0)).expect("couldn't seek"); log::info!("setting tz offset to {} secs", tz_ms / 1000); - assert_eq!(tz_key.write(&tz_ms.to_le_bytes()).unwrap_or(0), 8, "couldn't commit TZ time offset to PDDB"); + if tz_key.write(&tz_ms.to_le_bytes()).unwrap_or(0) != 8 { + log::warn!("Couldn't commit the latest timezone update. Is the PDDB mounted?"); + } tz_key.flush().expect("couldn't flush PDDB"); } }),