diff --git a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs index e15171fd1..32550ba82 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/bao1x.rs @@ -437,7 +437,7 @@ pub fn early_init(mut board_type: bao1x_api::BoardTypeCoding) -> (bao1x_api::Boa cu.set(); // can't check slots in alt-boot mode because it's effectively baremetal as far as permissions go #[cfg(not(feature = "alt-boot1"))] - crate::platform::slots::check_slots(&board_type); + crate::platform::slots::check_slots(); // protect() is called inside sigcheck on boot! // Rx setup diff --git a/bao1x-boot/boot1/src/platform/bao1x/slots.rs b/bao1x-boot/boot1/src/platform/bao1x/slots.rs index 9f313bf9f..4e39c6b25 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/slots.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/slots.rs @@ -16,7 +16,7 @@ use bao1x_hal::{ /// - Repair any ACLs that are not set correctly. "Repair" is expected on first boot at the factory, since /// the chip comes blank. But repair is also useful in case an adversary manages to flip any ACL states /// on us. -pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { +pub fn check_slots() { let owc = bao1x_hal::acram::OneWayCounter::new(); let mut slot_mgr = bao1x_hal::acram::SlotManager::new(); let mut maybe_trng: Option = None; @@ -49,13 +49,13 @@ pub fn check_slots(board_type: &bao1x_api::BoardTypeCoding) { // this one may allocate a TRNG, which takes >50 ms to warm up. if slot_mgr.read(&SERIAL_NUMBER).unwrap().iter().all(|&b| b == 0 || b == 0xFF) { - let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type)); + let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new()); let k = trng.generate_key(); // don't fail on write failure - otherwise we get stuck here and can't debug the chip slot_mgr.write(&mut rram, &SERIAL_NUMBER, &k).ok(); } if slot_mgr.read(&UUID).unwrap().iter().all(|&b| b == 0 || b == 0xFF) { - let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new(&board_type)); + let trng = maybe_trng.get_or_insert_with(|| super::trng::ManagedTrng::new()); let k = trng.generate_key(); // don't fail on write failure - otherwise we get stuck here and can't debug the chip slot_mgr.write(&mut rram, &UUID, &k).ok(); diff --git a/bao1x-boot/boot1/src/platform/bao1x/trng.rs b/bao1x-boot/boot1/src/platform/bao1x/trng.rs index 05050365d..425694f2e 100644 --- a/bao1x-boot/boot1/src/platform/bao1x/trng.rs +++ b/bao1x-boot/boot1/src/platform/bao1x/trng.rs @@ -1,103 +1,17 @@ -use bao1x_hal::iox::Iox; use rand_chacha::ChaCha8Rng; use rand_chacha::rand_core::RngCore; use rand_chacha::rand_core::SeedableRng; use utralib::*; -use xous_bio_bdma::*; - -const BITS_PER_SAMPLE: usize = 4; pub struct ManagedTrng { ro_trng: bao1x_hal::sce::trng::Trng, - av_trng: Option, csprng: ChaCha8Rng, } impl ManagedTrng { - pub fn new(board_type: &bao1x_api::BoardTypeCoding) -> Self { + pub fn new() -> Self { let mut ro_trng = bao1x_hal::sce::trng::Trng::new(utra::trng::HW_TRNG_BASE); ro_trng.setup_raw_generation(32); - let av_trng = if *board_type == bao1x_api::BoardTypeCoding::Baosec { - let mut bio_ss = BioSharedState::new(); - - let iox = Iox::new(utra::iox::HW_IOX_BASE as *mut u32); - - let trng_pin = bao1x_hal::board::setup_trng_input_pin(&iox); - let bio_bit = bao1x_api::bio::port_and_pin_to_bio_bit(trng_pin.0, trng_pin.1).unwrap(); - let trng_power = bao1x_hal::board::setup_trng_power_pin(&iox); - iox.set_gpio_pin(trng_power.0, trng_power.1, bao1x_api::IoxValue::High); - crate::delay(50); // wait for power to stabilize on the avalanche generator - - // avalanche generator TRNG - maybe replace this with a proper API call once this has - // been baked into something a little friendlier/easier to maintain? - // stop all the machines, so that code can be loaded - bio_ss.bio.wo(utra::bio_bdma::SFR_CTRL, 0x0); - bio_ss.load_code(avtrng_bio_code(), 0, BioCore::Core0); - - // don't use QDIV - bio_ss.bio.wo(utra::bio_bdma::SFR_QDIV0, 0x1_0001); - - // use extclock on channel 0, tied to the trng pin - bio_ss.bio.wo( - utra::bio_bdma::SFR_EXTCLOCK, - bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_USE_EXTCLK, 0b0001) - | bio_ss.bio.ms(utra::bio_bdma::SFR_EXTCLOCK_EXTCLK_GPIO_0, bio_bit.value() as u32), - ); - - // start the machine - bio_ss.set_core_run_states([true, false, false, false]); - bio_ss.bio.wo(utra::bio_bdma::SFR_TXF0, bio_bit.value() as u32); // start the sampling - - // check if the TRNG seems to be working. If not, reject the board setting and reboot - /* - let mut timer = utralib::CSR::new(utra::timer0::HW_TIMER0_BASE as *mut u32); - timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); - let av_good: bool; - let mut ms_passed = 0; - let mut samples_collected = 0; - const TIMEOUT_MS: usize = 10; - const SAMPLES_REQUIRED: usize = 10; - loop { - if timer.rf(utra::timer0::EV_PENDING_ZERO) != 0 { - ms_passed += 1; - timer.wfo(utra::timer0::EV_PENDING_ZERO, 1); - } - if ms_passed > TIMEOUT_MS { - av_good = false; - break; - } - if bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) != 0 { - let _ = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0); - samples_collected += 1; - ms_passed = 0; - } - if samples_collected > SAMPLES_REQUIRED { - av_good = true; - break; - } - } - if av_good { - Some(bio_ss) - } else { - crate::println!( - "AV TRNG is not present or functioning. Setting board type to dabao, and rebooting!" - ); - let one_way = bao1x_hal::acram::OneWayCounter::new(); - while one_way.get_decoded::().expect("owc coding error") - != bao1x_api::BoardTypeCoding::Dabao - { - one_way.inc_coded::().expect("increment error"); - } - // reset the system - let mut rcurst = CSR::new(utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); - rcurst.wo(utra::sysctrl::SFR_RCURST0, 0x55AA); - // this is actually unreachable - None - }*/ - None - } else { - None - }; // do a quick health check on the TRNG before using it. Looks for repeated values over 8 samples. // this will rule out e.g. TRNG output tied to 0 or 1, or an external feed just feeding it data. @@ -131,7 +45,7 @@ impl ManagedTrng { // extract the seed of the current version of the CSPRNG seed = csprng.get_seed(); - reseed(&mut ro_trng, &av_trng, &mut seed); + reseed(&mut ro_trng, &mut seed); // Make a new CSPRNG from the old seed that was XOR'd with the TRNG data csprng = ChaCha8Rng::from_seed(seed); @@ -147,7 +61,7 @@ impl ManagedTrng { // Make a final version of the CSPRNG based on the mixed state. csprng = ChaCha8Rng::from_seed(seed); } - Self { ro_trng, av_trng, csprng } + Self { ro_trng, csprng } } pub fn generate_key(&mut self) -> [u8; 32] { @@ -156,7 +70,7 @@ impl ManagedTrng { // reseed the csprng with more random data let mut seed = self.csprng.get_seed(); - reseed(&mut self.ro_trng, &self.av_trng, &mut seed); + reseed(&mut self.ro_trng, &mut seed); self.csprng = ChaCha8Rng::from_seed(seed); // mix the reseeded data against the csprng itself for s in seed.chunks_mut(8) { @@ -169,40 +83,12 @@ impl ManagedTrng { } } -fn reseed(trng: &mut bao1x_hal::sce::trng::Trng, av_trng: &Option, seed: &mut [u8]) { +fn reseed(trng: &mut bao1x_hal::sce::trng::Trng, seed: &mut [u8]) { // XOR the seed with TRNG data for s in seed.chunks_mut(4) { let incoming = trng.get_u32().expect("TRNG error"); for (s_byte, &ro_byte) in s.iter_mut().zip(incoming.to_le_bytes().iter()) { *s_byte ^= ro_byte; } - // if the avalanche generator is available, use that too. - if let Some(bio_ss) = av_trng { - let mut raw32 = 0; - for _ in 0..(size_of::() * 8) / BITS_PER_SAMPLE { - // wait for the next interval to arrive - while bio_ss.bio.rf(utra::bio_bdma::SFR_FLEVEL_PCLK_REGFIFO_LEVEL0) == 0 {} - let raw = bio_ss.bio.r(utra::bio_bdma::SFR_RXF0); - raw32 <<= BITS_PER_SAMPLE; - // shift right by one because bit 0 always samples as 0, due to instruction timing - raw32 |= (raw >> 1) & ((1 << BITS_PER_SAMPLE) - 1) - } - for (s_byte, &av_byte) in s.iter_mut().zip(raw32.to_le_bytes().iter()) { - *s_byte ^= av_byte; - } - } } } - -#[rustfmt::skip] -bio_code!(avtrng_bio_code, BM_AVTRNG_BIO_START, BM_AVTRNG_BIO_END, - "mv x1, x16", // get pin for trng input - "li x2, 1", - "sll x1, x2, x1", // shift the pin into a bitmask - "mv x25, x1", // make it an input -"10:", - "mv x20, x0", // wait for quantum: this time, the toggle from the TRNG - "mv x1, x31", // remember aclk time - "mv x16, x1", // save result to FIFO - "j 10b" // and do it again -); diff --git a/bao1x-boot/boot1/src/repl.rs b/bao1x-boot/boot1/src/repl.rs index 198b81ac0..09ad5b847 100644 --- a/bao1x-boot/boot1/src/repl.rs +++ b/bao1x-boot/boot1/src/repl.rs @@ -267,7 +267,7 @@ impl Repl { count += 1; } crate::println!("Board type set to {:?} after {} increments", new_type, count); - crate::platform::slots::check_slots(&new_type); + crate::platform::slots::check_slots(); crate::println!("Key & data slots checked according to the new type"); } "altboot" => { @@ -452,8 +452,12 @@ impl Repl { let collateral = slot_mgr.read(&COLLATERAL).unwrap(); let check_val = alloc::vec![bao1x_hal::sigcheck::ERASE_VALUE; COLLATERAL.len() * SLOT_ELEMENT_LEN_BYTES]; + let uninit_val = alloc::vec![0; COLLATERAL.len() * SLOT_ELEMENT_LEN_BYTES]; + // these strings below are used in CI. If they are changed, CI needs to be updated if collateral == &check_val { crate::println!("Collateral erased"); + } else if collateral == &uninit_val { + crate::println!("Collateral is uninitialized or access is denied"); } else { crate::println!("Collateral is set"); } @@ -646,6 +650,45 @@ impl Repl { } } #[cfg(feature = "test-boot0-keys")] + "rand_collateral" => { + use bao1x_hal::acram::AccessSettings; + // put random data in collateral - to simulate a third party keying + let slot_mgr = bao1x_hal::acram::SlotManager::new(); + let mut rram = bao1x_hal::rram::Reram::new(); + let slot = &bao1x_api::offsets::COLLATERAL; + let mut trng = super::trng::ManagedTrng::new(); + // only clear ACL if it isn't already cleared + if slot_mgr + .get_acl(slot) + .unwrap_or(AccessSettings::Data(DataSlotAccess::new_with_raw_value(0xFFFF_FFFF))) + .raw_u32() + != 0 + { + // clear the ACL so we can operate on the data + slot_mgr + .set_acl( + &mut rram, + slot, + &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)), + ) + .expect("couldn't reset ACL"); + } + let mut random: Vec = alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); + random.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, 0); + for chunk in random.chunks_mut(SLOT_ELEMENT_LEN_BYTES) { + let r = trng.generate_key(); + chunk.copy_from_slice(&r); + } + + slot_mgr.write(&mut rram, slot, &random).ok(); + + let bytes = unsafe { slot_mgr.read_unchecked(slot) }; + crate::println!("Random test data:"); + for (i, chunk) in bytes.chunks(32).enumerate() { + crate::println!(" {:03x}: {:02x?}", i * 32, chunk); + } + } + #[cfg(feature = "test-boot0-keys")] "publock" => { let rram = CSR::new(utra::rrc::HW_RRC_BASE as *mut u32); crate::println!("RRAM security settings: {:x}", rram.rf(utra::rrc::SFR_RRCCR_SFR_RRCCR)); diff --git a/libs/bao1x-hal/src/acram.rs b/libs/bao1x-hal/src/acram.rs index 68106a8a0..e65ff42ec 100644 --- a/libs/bao1x-hal/src/acram.rs +++ b/libs/bao1x-hal/src/acram.rs @@ -360,6 +360,27 @@ impl SlotManager { } } + /// Safety: may return garbage data if the ACLs aren't correct. No security is compromised + /// in the case that the ACL isn't correct, but the caller would not be notified of the + /// mismatch. This call is mostly useful for verifying that data is in fact being disregarded + /// or erased. + /// + /// SlotIndex is also assumed to be correct; if it is invalid, the function will panic. + pub unsafe fn read_unchecked(&self, slot: &SlotIndex) -> &[u8] { + let offset = slot.try_into_data_offset().unwrap(); + + // safety: the unsafes below remind us to check that all values are valid during + // the pointer type cast. In this case, there are no invalid values for a `u8`. + match slot { + SlotIndex::Data(_, _, _) => unsafe { + &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES] + }, + SlotIndex::DataRange(range, _, _) => unsafe { + &self.data_range.as_slice()[offset..offset + SLOT_ELEMENT_LEN_BYTES * range.len()] + }, + } + } + /// Safety: the caller must resolve the index into either the data or the key array correctly. /// There is access or type checking done. This is a "raw read" primitive mostly used for debugging. pub unsafe fn read_data_slot(&self, absolute_offset: usize) -> &[u8] { diff --git a/libs/bao1x-hal/src/sigcheck.rs b/libs/bao1x-hal/src/sigcheck.rs index 59469b25d..3f26fe778 100644 --- a/libs/bao1x-hal/src/sigcheck.rs +++ b/libs/bao1x-hal/src/sigcheck.rs @@ -5,11 +5,10 @@ use alloc::vec::Vec; use bao1x_api::REVOCATION_DUPE_DISTANCE; use bao1x_api::bollard; use bao1x_api::pubkeys::DEVELOPER_KEY_SLOT; -use bao1x_api::pubkeys::KEYSLOT_INITIAL_TAGS; use bao1x_api::pubkeys::SecurityConfiguration; use bao1x_api::signatures::*; #[cfg(not(feature = "std"))] -use bao1x_api::{DEVELOPER_MODE, DataSlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES, SlotType}; +use bao1x_api::{DEVELOPER_MODE, DataSlotAccess, RwPerms, SLOT_ELEMENT_LEN_BYTES}; use digest::Digest; use sha2_bao1x::{Sha256, Sha512}; use xous::arch::PAGE_SIZE; @@ -318,37 +317,35 @@ pub fn erase_collateral(csprng: &mut Option<&mut Csprng>) -> Result<(), String> let mut rram = crate::rram::Reram::new(); let slot = &bao1x_api::offsets::COLLATERAL; - for data_index in slot.try_into_data_iter().unwrap() { - bollard!(die_no_std, 4); - csprng.as_deref_mut().map(|rng| rng.random_delay()); - // only clear ACL if it isn't already cleared - if slot_mgr - .get_acl(slot) - .unwrap_or(AccessSettings::Data(DataSlotAccess::new_with_raw_value(0xFFFF_FFFF))) - .raw_u32() - != 0 - { - // clear the ACL so we can operate on the data - slot_mgr - .set_acl(&mut rram, slot, &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0))) - .expect("couldn't reset ACL"); - } - let bytes = unsafe { slot_mgr.read_data_slot(data_index) }; - // only erase if the key hasn't already been erased, to avoid stressing the RRAM array - // erase_secrets() may be called on every boot in some modes. - bollard!(die_no_std, 4); - if !bytes.iter().all(|&b| b == ERASE_VALUE) { - let mut eraser = alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); - eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); - - slot_mgr.write(&mut rram, slot, &eraser).ok(); - } - let check = unsafe { slot_mgr.read_data_slot(data_index) }; - if !check.iter().all(|&b| b == ERASE_VALUE) { - crate::println!("Failed to erase key at {}: {:x?}", data_index, check); - } - bollard!(die_no_std, 4); + bollard!(die_no_std, 4); + csprng.as_deref_mut().map(|rng| rng.random_delay()); + // only clear ACL if it isn't already cleared + if slot_mgr + .get_acl(slot) + .unwrap_or(AccessSettings::Data(DataSlotAccess::new_with_raw_value(0xFFFF_FFFF))) + .raw_u32() + != 0 + { + // clear the ACL so we can operate on the data + slot_mgr + .set_acl(&mut rram, slot, &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0))) + .expect("couldn't reset ACL"); } + let bytes = unsafe { slot_mgr.read_unchecked(slot) }; + // only erase if the key hasn't already been erased, to avoid stressing the RRAM array + // erase_secrets() may be called on every boot in some modes. + bollard!(die_no_std, 4); + if !bytes.iter().all(|&b| b == ERASE_VALUE) { + let mut eraser = alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); + eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); + + slot_mgr.write(&mut rram, slot, &eraser).ok(); + } + let check = unsafe { slot_mgr.read_unchecked(slot) }; + if !check.iter().all(|&b| b == ERASE_VALUE) { + crate::println!("Failed to erase key at {:?}: {:x?}", slot, check); + } + bollard!(die_no_std, 4); Ok(()) } @@ -379,72 +376,64 @@ pub fn erase_secrets(csprng: &mut Option<&mut Csprng>) -> Result<(), String> { for slot in crate::board::KEY_SLOTS.iter() { bollard!(die_no_std, 4); csprng.as_deref_mut().map(|rng| rng.random_delay()); - if slot.get_type() == SlotType::Data { - let (_pa, rw_perms) = slot.get_access_spec(); - let mut erased_keys = 0; - for data_index in slot.try_into_data_iter().unwrap() { - bollard!(die_no_std, 4); - csprng.as_deref_mut().map(|rng| rng.random_delay()); - match rw_perms { - RwPerms::ReadWrite | RwPerms::WriteOnly => { - // only clear ACL if it isn't already cleared - if slot_mgr - .get_acl(slot) - .unwrap_or(AccessSettings::Data(DataSlotAccess::new_with_raw_value(0xFFFF_FFFF))) - .raw_u32() - != 0 - { - // clear the ACL so we can operate on the data - match slot_mgr.set_acl( - &mut rram, - slot, - &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)), - ) { - Ok(_) => (), - Err(e) => { - crate::println!("Couldn't erase ACL: {:?}", e); - } - } - } - let bytes = unsafe { slot_mgr.read_data_slot(data_index) }; - if bytes.iter().all(|&b| b == 0) { - zero_key_count += 1; - } - // only erase if the key hasn't already been erased, to avoid stressing the RRAM array - // erase_secrets() may be called on every boot in some modes. - bollard!(die_no_std, 4); - if !bytes.iter().all(|&b| b == ERASE_VALUE) { - let mut eraser = - alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); - eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); - - slot_mgr.write(&mut rram, slot, &eraser).ok(); - } - let check = unsafe { slot_mgr.read_data_slot(data_index) }; - if !check.iter().all(|&b| b == ERASE_VALUE) { - crate::println!("Failed to erase key at {}: {:x?}", data_index, check); - /* // commented out - can lead to boot loops - // reboot on failure to erase - let mut rcurst = - utralib::CSR::new(utralib::utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); - rcurst.wo(utralib::utra::sysctrl::SFR_RCURST0, 0x55AA); - */ - } else { - erased_keys += 1; + let (_pa, rw_perms) = slot.get_access_spec(); + let mut erased_keys = 0; + csprng.as_deref_mut().map(|rng| rng.random_delay()); + match rw_perms { + RwPerms::ReadWrite | RwPerms::WriteOnly => { + // only clear ACL if it isn't already cleared + if slot_mgr + .get_acl(slot) + .unwrap_or(AccessSettings::Data(DataSlotAccess::new_with_raw_value(0xFFFF_FFFF))) + .raw_u32() + != 0 + { + // clear the ACL so we can operate on the data + match slot_mgr.set_acl( + &mut rram, + slot, + &AccessSettings::Data(DataSlotAccess::new_with_raw_value(0)), + ) { + Ok(_) => (), + Err(e) => { + crate::println!("Couldn't erase ACL: {:?}", e); } } - _ => {} } + // safety: this function knows to check or expect invalid ACL situations + let bytes = unsafe { slot_mgr.read_unchecked(slot) }; + if bytes.iter().all(|&b| b == 0) { + zero_key_count += 1; + } + // only erase if the key hasn't already been erased, to avoid stressing the RRAM array + // erase_secrets() may be called on every boot in some modes. bollard!(die_no_std, 4); + if !bytes.iter().all(|&b| b == ERASE_VALUE) { + let mut eraser = alloc::vec::Vec::with_capacity(slot.len() * SLOT_ELEMENT_LEN_BYTES); + eraser.resize(slot.len() * SLOT_ELEMENT_LEN_BYTES, ERASE_VALUE); + slot_mgr.write(&mut rram, slot, &eraser).ok(); + } + let check = unsafe { slot_mgr.read_unchecked(slot) }; + if !check.iter().all(|&b| b == ERASE_VALUE) { + crate::println!("Failed to erase key at {:?}: {:x?}", slot, check); + /* // commented out - can lead to boot loops + // reboot on failure to erase + let mut rcurst = + utralib::CSR::new(utralib::utra::sysctrl::HW_SYSCTRL_BASE as *mut u32); + rcurst.wo(utralib::utra::sysctrl::SFR_RCURST0, 0x55AA); + */ + } else { + erased_keys += 1; + } } - crate::println!( - "Key range at {}: {}/{} keys confirmed erased", - slot.get_base(), - erased_keys, - slot.len() - ); - bollard!(die_no_std, 4); + _ => {} } + crate::println!( + "Key range at {}: {}/{} keys confirmed erased", + slot.get_base(), + erased_keys, + slot.len() + ); bollard!(die_no_std, 4); } bollard!(die_no_std, 4); @@ -495,9 +484,8 @@ pub fn hardened_erase_policy( } bollard!(die_no_std, 4); csprng.random_delay(); - // if the tag isn't one of the first 3 "blessed" tags, assume developer mode. This is - // a supplemental check, so we don't harden it. - if !KEYSLOT_INITIAL_TAGS[..3].contains(&&tag) { + // if the tag is the developer tag, erase the keys. + if &tag == b"dev " { erase_secrets(&mut Some(csprng))?; } bollard!(die_no_std, 4); @@ -525,9 +513,8 @@ pub fn hardened_erase_policy( } bollard!(die_no_std, 4); csprng.random_delay(); - // if the tag isn't one of the first 3 "blessed" tags, assume developer mode. This is - // a supplemental check, so we don't harden it. - if !KEYSLOT_INITIAL_TAGS[..3].contains(&&tag) { + // if the tag is the developer tag, erase the keys. + if &tag == b"dev " { erase_secrets(&mut Some(csprng))?; } bollard!(die_no_std, 4); diff --git a/tools/src/bin/xous-app-uf2.rs b/tools/src/bin/xous-app-uf2.rs index 00b239e53..bf5f5392f 100644 --- a/tools/src/bin/xous-app-uf2.rs +++ b/tools/src/bin/xous-app-uf2.rs @@ -163,6 +163,7 @@ fn main() -> Result<(), Box> { xous_tools::sign_image::Version::Bao1xV1, Some("app"), Some(anti_rollback as usize), + false, )?; let app_uf2 = "apps.uf2"; diff --git a/tools/src/bin/xous-sign-image.rs b/tools/src/bin/xous-sign-image.rs index cc6aa79b4..3cb5c494e 100644 --- a/tools/src/bin/xous-sign-image.rs +++ b/tools/src/bin/xous-sign-image.rs @@ -108,6 +108,13 @@ fn main() -> Result<(), Box> { .help("Manually specify an anti-rollback value for the image. Overrides the system configuration file.") .required(false) ) + .arg( + Arg::with_name("fake-pubkeys") + .long("fake public key block") + .takes_value(false) + .help("When specified, fills the public key block with random, fake data. Used for testing third-party boot flow policies") + .required(false) + ) .get_matches(); let minver = @@ -157,6 +164,7 @@ fn main() -> Result<(), Box> { sig_length, matches.value_of("function-code"), arb_override.map(|x| x as usize), + matches.is_present("fake-pubkeys"), )?; if matches.is_present("bao1x") { @@ -199,6 +207,7 @@ fn main() -> Result<(), Box> { sig_length, Some(matches.value_of("function-code").unwrap_or("kernel")), arb_override.map(|x| x as usize), + matches.is_present("fake-pubkeys"), )?; if matches.is_present("bao1x") { diff --git a/tools/src/sign_image.rs b/tools/src/sign_image.rs index b2c0012f3..fb7fe48c1 100644 --- a/tools/src/sign_image.rs +++ b/tools/src/sign_image.rs @@ -4,11 +4,12 @@ use std::io::{Read, Write}; use std::path::Path; use bao1x_api::signatures::{ - FunctionCode, PADDING_LEN, SIGBLOCK_LEN, SealedFields, SignatureInFlash, UNSIGNED_LEN, + FunctionCode, PADDING_LEN, Pubkey, SIGBLOCK_LEN, SealedFields, SignatureInFlash, UNSIGNED_LEN, }; use ed25519_dalek::{DigestSigner, SigningKey}; use pkcs8::PrivateKeyInfo; use pkcs8::der::Decodable; +use rand::RngCore; use ring::signature::{Ed25519KeyPair, KeyPair}; use sha2::{Digest, Sha512}; @@ -76,6 +77,7 @@ pub fn sign_image( version: Version, function_code: Option<&str>, anti_rollback_manual: Option, + fake_pubkeys: bool, ) -> Result, Box> { let mut dest_file = vec![]; @@ -237,10 +239,20 @@ pub fn sign_image( header.sealed_data.semver = semver; // whack in all the public keys, defined in the bao1x-api crate - for (dst, src) in - header.sealed_data.pubkeys.iter_mut().zip(bao1x_api::pubkeys::PUBKEY_HEADER.iter()) - { - dst.populate_from(src); + if !fake_pubkeys { + for (dst, src) in + header.sealed_data.pubkeys.iter_mut().zip(bao1x_api::pubkeys::PUBKEY_HEADER.iter()) + { + dst.populate_from(src); + } + } else { + // populate with fake, random data. The data changes every time. + for dst in header.sealed_data.pubkeys.iter_mut() { + let mut fake_pk = Pubkey::default(); + rand::rngs::OsRng.fill_bytes(&mut fake_pk.pk); + rand::rngs::OsRng.fill_bytes(&mut fake_pk.tag); + dst.populate_from(&fake_pk); + } } let mut protected = Vec::new(); @@ -305,6 +317,7 @@ pub fn sign_file( sector_length: usize, function_code: Option<&str>, arb_override: Option, + fake_pubkeys: bool, ) -> Result<(), Box> where S: AsRef, @@ -326,6 +339,7 @@ where version, function_code, arb_override, + fake_pubkeys, )?; dest_file.write_all(&result)?; Ok(()) diff --git a/tools/src/swap_writer.rs b/tools/src/swap_writer.rs index 62859ce37..ba4e643cf 100644 --- a/tools/src/swap_writer.rs +++ b/tools/src/swap_writer.rs @@ -142,6 +142,7 @@ impl SwapWriter { Version::Bao1xV1, function, anti_rollback_manual, + false, ) .map_err(|_| std::io::Error::new(std::io::ErrorKind::Other, "Can't sign swap image"))?; // write the header, less space for the signature