1use core::cell::RefCell;
2
3use embedded_storage::nor_flash::{NorFlash, NorFlashError, NorFlashErrorKind};
4use hazard3_embedded_hal::flash::partition::BlockingPartition;
5use hazard3_sync::blocking_mutex::Mutex;
6use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
7
8use crate::verification::blocking::verify;
9use crate::verification::{Digest, VerificationError, VerifyingKey};
10use crate::{DFU_DETACH_MAGIC, REVERT_MAGIC, STATE_ERASE_VALUE, SWAP_MAGIC, State};
11
12#[derive(PartialEq, Eq, Debug)]
14pub enum BootError {
15 Flash(NorFlashErrorKind),
17 BadMagic,
19}
20
21#[cfg(feature = "defmt")]
22impl defmt::Format for BootError {
23 fn format(&self, fmt: defmt::Formatter) {
24 match self {
25 BootError::Flash(_) => defmt::write!(fmt, "BootError::Flash(_)"),
26 BootError::BadMagic => defmt::write!(fmt, "BootError::BadMagic"),
27 }
28 }
29}
30
31impl<E> From<E> for BootError
32where
33 E: NorFlashError,
34{
35 fn from(error: E) -> Self {
36 BootError::Flash(error.kind())
37 }
38}
39
40pub struct BootLoaderConfig<ACTIVE, DFU, STATE> {
46 pub active: ACTIVE,
48 pub dfu: DFU,
50 pub state: STATE,
52}
53
54impl<'a, ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash>
55 BootLoaderConfig<
56 BlockingPartition<'a, NoopRawMutex, ACTIVE>,
57 BlockingPartition<'a, NoopRawMutex, DFU>,
58 BlockingPartition<'a, NoopRawMutex, STATE>,
59 >
60{
61 pub fn from_linkerfile_blocking(
95 active_flash: &'a Mutex<NoopRawMutex, RefCell<ACTIVE>>,
96 dfu_flash: &'a Mutex<NoopRawMutex, RefCell<DFU>>,
97 state_flash: &'a Mutex<NoopRawMutex, RefCell<STATE>>,
98 ) -> Self {
99 unsafe extern "C" {
100 static __bootloader_state_start: u32;
101 static __bootloader_state_end: u32;
102 static __bootloader_active_start: u32;
103 static __bootloader_active_end: u32;
104 static __bootloader_dfu_start: u32;
105 static __bootloader_dfu_end: u32;
106 }
107
108 let active = unsafe {
109 let start = &__bootloader_active_start as *const u32 as u32;
110 let end = &__bootloader_active_end as *const u32 as u32;
111 trace!("ACTIVE: 0x{:x} - 0x{:x}", start, end);
112
113 BlockingPartition::new(active_flash, start, end - start)
114 };
115 let dfu = unsafe {
116 let start = &__bootloader_dfu_start as *const u32 as u32;
117 let end = &__bootloader_dfu_end as *const u32 as u32;
118 trace!("DFU: 0x{:x} - 0x{:x}", start, end);
119
120 BlockingPartition::new(dfu_flash, start, end - start)
121 };
122 let state = unsafe {
123 let start = &__bootloader_state_start as *const u32 as u32;
124 let end = &__bootloader_state_end as *const u32 as u32;
125 trace!("STATE: 0x{:x} - 0x{:x}", start, end);
126
127 BlockingPartition::new(state_flash, start, end - start)
128 };
129
130 Self { active, dfu, state }
131 }
132}
133
134pub struct BootLoader<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> {
136 active: ACTIVE,
137 dfu: DFU,
138 state: STATE,
147}
148
149impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, STATE> {
150 const PAGE_SIZE: u32 = if ACTIVE::ERASE_SIZE > DFU::ERASE_SIZE {
152 ACTIVE::ERASE_SIZE as u32
153 } else {
154 DFU::ERASE_SIZE as u32
155 };
156
157 pub fn new(config: BootLoaderConfig<ACTIVE, DFU, STATE>) -> Self {
162 Self {
163 active: config.active,
164 dfu: config.dfu,
165 state: config.state,
166 }
167 }
168
169 pub fn verify_update<D: Digest, V: VerifyingKey>(
187 &mut self,
188 aligned_buf: &mut [u8],
189 signature_buf: &mut [u8],
190 public_key: &[u8],
191 update_len: u32,
192 signature_offset: u32,
193 ) -> Result<State, BootError> {
194 let state = self.read_state(aligned_buf)?;
195 if state != State::Swap || self.current_progress(aligned_buf)? != 0 {
196 return Ok(state);
197 }
198 self.dfu.read(signature_offset, signature_buf)?;
199 match verify::<_, D, V>(&mut self.dfu, public_key, signature_buf, update_len, aligned_buf) {
200 Ok(()) => Ok(State::Swap),
201 Err(VerificationError::Flash(error)) => Err(BootError::Flash(error)),
202 Err(VerificationError::Signature(_)) => {
203 self.state.erase(0, self.state.capacity() as u32)?;
206 let state_word = &mut aligned_buf[..STATE::WRITE_SIZE];
207 state_word.fill(REVERT_MAGIC);
208 self.state.write(0, state_word)?;
209 Ok(State::Revert)
210 }
211 }
212 }
213
214 pub fn prepare_boot(&mut self, aligned_buf: &mut [u8]) -> Result<State, BootError> {
287 const {
288 core::assert!(Self::PAGE_SIZE % ACTIVE::WRITE_SIZE as u32 == 0);
289 core::assert!(Self::PAGE_SIZE % ACTIVE::ERASE_SIZE as u32 == 0);
290 core::assert!(Self::PAGE_SIZE % DFU::WRITE_SIZE as u32 == 0);
291 core::assert!(Self::PAGE_SIZE % DFU::ERASE_SIZE as u32 == 0);
292 }
293
294 assert_eq!(0, Self::PAGE_SIZE % aligned_buf.len() as u32);
296 assert!(aligned_buf.len() >= STATE::WRITE_SIZE);
297 assert_eq!(0, aligned_buf.len() % ACTIVE::WRITE_SIZE);
298 assert_eq!(0, aligned_buf.len() % DFU::WRITE_SIZE);
299
300 assert_partitions(&self.active, &self.dfu, &self.state, Self::PAGE_SIZE);
302
303 let state = self.read_state(aligned_buf)?;
305 if state == State::Swap {
306 if !self.is_swapped(aligned_buf)? {
311 trace!("Swapping");
312 self.swap(aligned_buf)?;
313 trace!("Swapping done");
314 } else {
315 trace!("Reverting");
316 self.revert(aligned_buf)?;
317
318 let state_word = &mut aligned_buf[..STATE::WRITE_SIZE];
319
320 state_word.fill(!STATE_ERASE_VALUE);
322 self.state.write(STATE::WRITE_SIZE as u32, state_word)?;
323
324 self.state.write(0, state_word)?;
326
327 self.state.erase(0, self.state.capacity() as u32)?;
329
330 state_word.fill(REVERT_MAGIC);
332 self.state.write(0, state_word)?;
333 }
334 }
335 Ok(state)
336 }
337
338 pub fn read_state(&mut self, aligned_buf: &mut [u8]) -> Result<State, BootError> {
343 let state_word = &mut aligned_buf[..STATE::WRITE_SIZE];
344 self.state.read(0, state_word)?;
345
346 if !state_word.iter().any(|&b| b != SWAP_MAGIC) {
347 Ok(State::Swap)
348 } else if !state_word.iter().any(|&b| b != DFU_DETACH_MAGIC) {
349 Ok(State::DfuDetach)
350 } else if !state_word.iter().any(|&b| b != REVERT_MAGIC) {
351 Ok(State::Revert)
352 } else {
353 Ok(State::Boot)
354 }
355 }
356
357 fn is_swapped(&mut self, aligned_buf: &mut [u8]) -> Result<bool, BootError> {
358 let page_count = self.active.capacity() / Self::PAGE_SIZE as usize;
359 let progress = self.current_progress(aligned_buf)?;
360
361 Ok(progress >= page_count * 2)
362 }
363
364 fn current_progress(&mut self, aligned_buf: &mut [u8]) -> Result<usize, BootError> {
365 let write_size = STATE::WRITE_SIZE as u32;
366 let state_words = self.state.capacity() / STATE::WRITE_SIZE;
367 assert!(state_words > 3);
369 let max_index = state_words - 3;
370 let state_word = &mut aligned_buf[..write_size as usize];
371
372 self.state.read(write_size, state_word)?;
373 if state_word.iter().any(|&b| b != STATE_ERASE_VALUE) {
374 return Ok(max_index);
376 }
377
378 for index in 0..max_index {
379 self.state.read((2 + index) as u32 * write_size, state_word)?;
380
381 if state_word.iter().any(|&b| b == STATE_ERASE_VALUE) {
382 return Ok(index);
383 }
384 }
385 Ok(max_index)
386 }
387
388 fn update_progress(&mut self, progress_index: usize, aligned_buf: &mut [u8]) -> Result<(), BootError> {
389 let state_word = &mut aligned_buf[..STATE::WRITE_SIZE];
390 state_word.fill(!STATE_ERASE_VALUE);
391 self.state
392 .write((2 + progress_index) as u32 * STATE::WRITE_SIZE as u32, state_word)?;
393 Ok(())
394 }
395
396 fn copy_page_once_to_active(
397 &mut self,
398 progress_index: usize,
399 from_offset: u32,
400 to_offset: u32,
401 aligned_buf: &mut [u8],
402 ) -> Result<(), BootError> {
403 if self.current_progress(aligned_buf)? <= progress_index {
404 let page_size = Self::PAGE_SIZE as u32;
405
406 self.active.erase(to_offset, to_offset + page_size)?;
407
408 for offset_in_page in (0..page_size).step_by(aligned_buf.len()) {
409 self.dfu.read(from_offset + offset_in_page as u32, aligned_buf)?;
410 self.active.write(to_offset + offset_in_page as u32, aligned_buf)?;
411 }
412
413 self.update_progress(progress_index, aligned_buf)?;
414 }
415 Ok(())
416 }
417
418 fn copy_page_once_to_dfu(
419 &mut self,
420 progress_index: usize,
421 from_offset: u32,
422 to_offset: u32,
423 aligned_buf: &mut [u8],
424 ) -> Result<(), BootError> {
425 if self.current_progress(aligned_buf)? <= progress_index {
426 let page_size = Self::PAGE_SIZE as u32;
427
428 self.dfu.erase(to_offset as u32, to_offset + page_size)?;
429
430 for offset_in_page in (0..page_size).step_by(aligned_buf.len()) {
431 self.active.read(from_offset + offset_in_page as u32, aligned_buf)?;
432 self.dfu.write(to_offset + offset_in_page as u32, aligned_buf)?;
433 }
434
435 self.update_progress(progress_index, aligned_buf)?;
436 }
437 Ok(())
438 }
439
440 fn swap(&mut self, aligned_buf: &mut [u8]) -> Result<(), BootError> {
441 let page_count = self.active.capacity() as u32 / Self::PAGE_SIZE;
442 for page_num in 0..page_count {
443 let progress_index = (page_num * 2) as usize;
444
445 let active_from_offset = (page_count - 1 - page_num) * Self::PAGE_SIZE;
447 let dfu_to_offset = (page_count - page_num) * Self::PAGE_SIZE;
448 self.copy_page_once_to_dfu(progress_index, active_from_offset, dfu_to_offset, aligned_buf)?;
450
451 let active_to_offset = (page_count - 1 - page_num) * Self::PAGE_SIZE;
453 let dfu_from_offset = (page_count - 1 - page_num) * Self::PAGE_SIZE;
454 self.copy_page_once_to_active(progress_index + 1, dfu_from_offset, active_to_offset, aligned_buf)?;
456 }
457
458 Ok(())
459 }
460
461 fn revert(&mut self, aligned_buf: &mut [u8]) -> Result<(), BootError> {
462 let page_count = self.active.capacity() as u32 / Self::PAGE_SIZE;
463 for page_num in 0..page_count {
464 let progress_index = (page_count * 2 + page_num * 2) as usize;
465
466 let active_from_offset = page_num * Self::PAGE_SIZE;
468 let dfu_to_offset = page_num * Self::PAGE_SIZE;
469 self.copy_page_once_to_dfu(progress_index, active_from_offset, dfu_to_offset, aligned_buf)?;
470
471 let active_to_offset = page_num * Self::PAGE_SIZE;
473 let dfu_from_offset = (page_num + 1) * Self::PAGE_SIZE;
474 self.copy_page_once_to_active(progress_index + 1, dfu_from_offset, active_to_offset, aligned_buf)?;
475 }
476
477 Ok(())
478 }
479}
480
481fn assert_partitions<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash>(
482 active: &ACTIVE,
483 dfu: &DFU,
484 state: &STATE,
485 page_size: u32,
486) {
487 assert_eq!(active.capacity() as u32 % page_size, 0);
488 assert_eq!(dfu.capacity() as u32 % page_size, 0);
489 assert!(dfu.capacity() as u32 - active.capacity() as u32 >= page_size);
491 assert!(2 + 4 * (active.capacity() as u32 / page_size) <= state.capacity() as u32 / STATE::WRITE_SIZE as u32);
492}
493
494#[cfg(test)]
495mod tests {
496 use super::*;
497 use crate::mem_flash::MemFlash;
498
499 #[test]
500 #[should_panic]
501 fn test_range_asserts() {
502 const ACTIVE_SIZE: usize = 4194304 - 4096;
503 const DFU_SIZE: usize = 4194304;
504 const STATE_SIZE: usize = 4096;
505 static ACTIVE: MemFlash<ACTIVE_SIZE, 4, 4> = MemFlash::new(0xFF);
506 static DFU: MemFlash<DFU_SIZE, 4, 4> = MemFlash::new(0xFF);
507 static STATE: MemFlash<STATE_SIZE, 4, 4> = MemFlash::new(0xFF);
508 assert_partitions(&ACTIVE, &DFU, &STATE, 4096);
509 }
510}
511
512#[cfg(test)]
513mod verification_tests {
514 use hazard3_crypto::Sha512;
515 use hazard3_crypto::ed25519::{SigningKey, VerifyingKey};
516 use hazard3_crypto_rand as _;
517 use hazard3_crypto_rustcrypto as _;
518 use hazard3_sync::once_lock::OnceLock;
519
520 use super::*;
521 use crate::AlignedBuffer;
522 use crate::mem_flash::MemFlash;
523
524 type Loader = BootLoader<MemFlash<96, 16, 4>, MemFlash<112, 16, 4, 4>, MemFlash<128, 128, 4>>;
525
526 fn pending() -> (Loader, [u8; 32]) {
527 static SIGNED: OnceLock<([u8; 64], [u8; 32])> = OnceLock::new();
529
530 let (signature, public_key) = *SIGNED.get_or_init(|| {
531 let key = SigningKey::from_bytes(&[1; 32]);
532 let signature = key.sign(&Sha512::digest(&[0xaa; 32])).unwrap();
533 (signature.to_bytes(), key.verifying_key().unwrap().to_bytes())
534 });
535
536 let mut dfu = MemFlash::default();
537 dfu.mem[..32].fill(0xaa);
538 dfu.mem[32..96].copy_from_slice(&signature);
539 let mut state = MemFlash::default();
540 state.mem[..4].fill(SWAP_MAGIC);
541 (
542 BootLoader::new(BootLoaderConfig {
543 active: MemFlash::new(0x55),
544 dfu,
545 state,
546 }),
547 public_key,
548 )
549 }
550
551 #[test]
552 fn invalid_signature_preserves_images_and_reports_revert() {
553 let (mut boot, key) = pending();
554 boot.dfu.mem[32..96].fill(0);
555 let staged = boot.dfu.mem;
556 let mut cbuf = AlignedBuffer([0; 4]);
557 let mut sbuf = AlignedBuffer([0; 64]);
558 assert_eq!(
559 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32),
560 Ok(State::Revert)
561 );
562 assert_eq!(boot.active.mem, [0x55; 96]);
563 assert_eq!(boot.dfu.mem, staged);
564 assert_eq!(boot.read_state(cbuf.as_mut()), Ok(State::Revert));
565 boot.dfu.pending_read_successes = Some(0);
566 assert_eq!(
567 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32),
568 Ok(State::Revert)
569 );
570 assert_eq!(boot.prepare_boot(cbuf.as_mut()), Ok(State::Revert));
571 assert_eq!(boot.active.mem, [0x55; 96]);
572 }
573
574 #[test]
575 fn read_errors_preserve_pending_swap_and_rejection_write_errors_preserve_active() {
576 for reads in [0, 1] {
578 let (mut boot, key) = pending();
579 let staged = boot.dfu.mem;
580 let mut cbuf = AlignedBuffer([0; 4]);
581 let mut sbuf = AlignedBuffer([0; 64]);
582 boot.dfu.pending_read_successes = Some(reads);
583 assert_eq!(
584 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32),
585 Err(BootError::Flash(NorFlashErrorKind::Other))
586 );
587 assert_eq!(boot.read_state(cbuf.as_mut()), Ok(State::Swap));
588 assert_eq!(boot.active.mem, [0x55; 96]);
589 assert_eq!(boot.dfu.mem, staged);
590 }
591 let (mut boot, key) = pending();
592 boot.dfu.mem[32..96].fill(0);
593
594 let mut cbuf = AlignedBuffer([0; 4]);
595 let mut sbuf = AlignedBuffer([0; 64]);
596 boot.state.pending_write_successes = Some(0);
598 assert!(
599 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32)
600 .is_err()
601 );
602 boot.state.pending_write_successes = None;
603 boot.dfu.pending_read_successes = Some(0);
604 assert_eq!(
605 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32),
606 Ok(State::Boot)
607 );
608 assert_eq!(boot.active.mem, [0x55; 96]);
609 }
610
611 #[test]
612 fn interrupted_swap_verifies_only_before_progress_and_can_revert() {
613 let wrong_key = SigningKey::from_bytes(&[2; 32]).verifying_key().unwrap().to_bytes();
614 for partition in 0..3 {
615 for writes in 0..=24 {
616 let (mut boot, key) = pending();
617 let candidate: [u8; 96] = boot.dfu.mem[..96].try_into().unwrap();
618 match partition {
619 0 => boot.active.pending_write_successes = Some(writes),
620 1 => boot.dfu.pending_write_successes = Some(writes),
621 _ => boot.state.pending_write_successes = Some(writes),
622 }
623 let mut cbuf = AlignedBuffer([0; 4]);
624 let mut sbuf = AlignedBuffer([0; 64]);
625 assert_eq!(
626 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &key, 32, 32),
627 Ok(State::Swap)
628 );
629 assert_eq!(boot.active.mem, [0x55; 96]);
630 assert_eq!(&boot.dfu.mem[..96], &candidate);
631 let result = boot.prepare_boot(cbuf.as_mut());
632 boot.active.pending_write_successes = None;
633 boot.dfu.pending_write_successes = None;
634 boot.state.pending_write_successes = None;
635 if result.is_err() {
636 let unstarted = boot.current_progress(cbuf.as_mut()).unwrap() == 0;
637 if unstarted {
638 assert_eq!(&boot.dfu.mem[..96], &candidate);
639 assert_eq!(
641 boot.verify_update::<Sha512, VerifyingKey>(
642 cbuf.as_mut(),
643 sbuf.as_mut(),
644 &wrong_key,
645 32,
646 32
647 ),
648 Ok(State::Revert)
649 );
650 assert_eq!(boot.prepare_boot(cbuf.as_mut()), Ok(State::Revert));
651 assert_eq!(boot.active.mem, [0x55; 96]);
652 continue;
653 }
654 assert_eq!(
656 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &wrong_key, 32, 32),
657 Ok(State::Swap)
658 );
659 assert_eq!(boot.prepare_boot(cbuf.as_mut()), Ok(State::Swap));
660 }
661 assert_eq!(boot.active.mem, candidate);
662 assert_eq!(
664 boot.verify_update::<Sha512, VerifyingKey>(cbuf.as_mut(), sbuf.as_mut(), &wrong_key, 32, 32),
665 Ok(State::Swap)
666 );
667 assert_eq!(boot.active.mem, candidate);
668 boot.prepare_boot(cbuf.as_mut()).unwrap();
669 assert_eq!(boot.read_state(cbuf.as_mut()), Ok(State::Revert));
670 assert_eq!(boot.active.mem, [0x55; 96]);
671 }
672 }
673 }
674
675 #[test]
677 fn torn_state_erase_after_revert_keeps_reverted_image() {
678 for keep in 0..1u64 << 16 {
679 let (mut boot, _) = pending();
680 let mut buf = AlignedBuffer([0; 4]);
681 assert_eq!(boot.prepare_boot(buf.as_mut()), Ok(State::Swap));
682 boot.state.pending_erase_tear = Some(keep);
683 assert!(boot.prepare_boot(buf.as_mut()).is_err());
684 assert_eq!(boot.prepare_boot(buf.as_mut()), Ok(State::Boot), "keep {keep:#x}");
685 assert_eq!(boot.active.mem, [0x55; 96], "keep {keep:#x}");
686 }
687 }
688
689 #[test]
690 fn torn_state_erase_in_mark_booted_keeps_swapped_image() {
691 for keep in 0..1u64 << 16 {
692 let (mut boot, _) = pending();
693 let candidate: [u8; 96] = boot.dfu.mem[..96].try_into().unwrap();
694 let mut buf = AlignedBuffer([0; 4]);
695 assert_eq!(boot.prepare_boot(buf.as_mut()), Ok(State::Swap));
696 boot.state.pending_erase_tear = Some(keep);
697 let mut aligned = AlignedBuffer([0; 4]);
698 assert!(
699 crate::BlockingFirmwareState::new(&mut boot.state, aligned.as_mut())
700 .mark_booted()
701 .is_err()
702 );
703 assert_eq!(boot.prepare_boot(buf.as_mut()), Ok(State::Boot), "keep {keep:#x}");
704 assert_eq!(boot.active.mem, candidate, "keep {keep:#x}");
705 }
706 }
707}