Skip to main content

hazard3_boot/
boot_loader.rs

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/// Errors returned by bootloader
13#[derive(PartialEq, Eq, Debug)]
14pub enum BootError {
15    /// Error from flash.
16    Flash(NorFlashErrorKind),
17    /// Invalid bootloader magic
18    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
40/// Bootloader flash configuration holding the three flashes used by the bootloader
41///
42/// If only a single flash is actually used, then that flash should be partitioned into three partitions before use.
43/// The easiest way to do this is to use [`BootLoaderConfig::from_linkerfile_blocking`] which will partition
44/// the provided flash according to symbols defined in the linkerfile.
45pub struct BootLoaderConfig<ACTIVE, DFU, STATE> {
46    /// Flash type used for the active partition - the partition which will be booted from.
47    pub active: ACTIVE,
48    /// Flash type used for the dfu partition - the partition which will be swapped in when requested.
49    pub dfu: DFU,
50    /// Flash type used for the state partition.
51    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    /// Constructs a `BootLoaderConfig` instance from flash memory and address symbols defined in the linker file.
62    ///
63    /// This method initializes `BlockingPartition` instances for the active, DFU (Device Firmware Update),
64    /// and state partitions, leveraging start and end addresses specified by the linker. These partitions
65    /// are critical for managing firmware updates, application state, and boot operations within the bootloader.
66    ///
67    /// # Parameters
68    /// - `active_flash`: A reference to a mutex-protected `RefCell` for the active partition's flash interface.
69    /// - `dfu_flash`: A reference to a mutex-protected `RefCell` for the DFU partition's flash interface.
70    /// - `state_flash`: A reference to a mutex-protected `RefCell` for the state partition's flash interface.
71    ///
72    /// # Safety
73    /// The method contains `unsafe` blocks for dereferencing raw pointers that represent the start and end addresses
74    /// of the bootloader's partitions in flash memory. It is crucial that these addresses are accurately defined
75    /// in the memory.x file to prevent undefined behavior.
76    ///
77    /// The caller must ensure that the memory regions defined by these symbols are valid and that the flash memory
78    /// interfaces provided are compatible with these regions.
79    ///
80    /// # Returns
81    /// A `BootLoaderConfig` instance with `BlockingPartition` instances for the active, DFU, and state partitions.
82    ///
83    /// # Example
84    /// ```ignore
85    /// // Assume `active_flash`, `dfu_flash`, and `state_flash` all share the same flash memory interface.
86    /// let layout = Flash::new_blocking(p.FLASH, Default::default()).into_blocking_regions();
87    /// let flash = Mutex::new(RefCell::new(layout.bank1_region));
88    ///
89    /// let config = BootLoaderConfig::from_linkerfile_blocking(&flash, &flash, &flash);
90    /// // `config` can now be used to create a `BootLoader` instance for managing boot operations.
91    /// ```
92    /// Working examples can be found in the bootloader examples folder.
93    // #[cfg(target_os = "none")]
94    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
134/// BootLoader works with any flash implementing embedded_storage.
135pub struct BootLoader<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> {
136    active: ACTIVE,
137    dfu: DFU,
138    /// The state partition has the following format:
139    /// All ranges are in multiples of WRITE_SIZE bytes.
140    /// N = Active partition size divided by WRITE_SIZE.
141    /// | Range              | Description                                                                      |
142    /// | 0..1               | Magic indicating bootloader state. BOOT_MAGIC means boot, SWAP_MAGIC means swap. |
143    /// | 1..2               | Progress validity. ERASE_VALUE means valid, !ERASE_VALUE means invalid.          |
144    /// | 2..(2 + 2N)        | Progress index used while swapping                                               |
145    /// | (2 + 2N)..(2 + 4N) | Progress index used while reverting
146    state: STATE,
147}
148
149impl<ACTIVE: NorFlash, DFU: NorFlash, STATE: NorFlash> BootLoader<ACTIVE, DFU, STATE> {
150    /// Get the page size which is the "unit of operation" within the bootloader.
151    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    /// Create a new instance of a bootloader with the flash partitions.
158    ///
159    /// - All partitions must be aligned with the PAGE_SIZE const generic parameter.
160    /// - The dfu partition must be at least PAGE_SIZE bigger than the active partition.
161    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    /// Verify the update in the DFU partition without copying either image.
170    ///
171    /// On `Swap` with zero copy progress, verify the signature at `signature_offset`
172    /// over the digest of DFU bytes `0..update_len`.
173    ///
174    /// An invalid signature records and returns `Revert`. Other states and swaps
175    /// with recorded progress are left unchanged. Flash errors are returned.
176    /// Call this before [`Self::prepare_boot`] on every boot; successful
177    /// verification is not recorded separately from swap progress.
178    ///
179    /// The `signature_buf` is used to hold the signature, and should be of exactly the same
180    /// length as the signature from the provided algorithm.
181    /// Furthermore it should satisfy the flashes buffer alignment requirements.
182    /// The signature at `signature_offset` must be readable from DFU.
183    ///
184    /// `aligned_buf` must satisfy [`Self::read_state`]'s buffer requirements and
185    /// the [hashing requirements](crate::BlockingFirmwareUpdater::hash).
186    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                // Invalidating progress here would make an interrupted rejection
204                // look like a completed swap requiring rollback.
205                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    /// Perform necessary boot preparations like swapping images.
215    ///
216    /// The DFU partition is assumed to be 1 page bigger than the active partition for the swap
217    /// algorithm to work correctly.
218    ///
219    /// The provided aligned_buf argument must satisfy any alignment requirements
220    /// given by the partition flashes. All flash operations will use this buffer.
221    ///
222    /// ## SWAPPING
223    ///
224    /// Assume a flash size of 3 pages for the active partition, and 4 pages for the DFU partition.
225    /// The swap index contains the copy progress, as to allow continuation of the copy process on
226    /// power failure. The index counter is represented within 1 or more pages (depending on total
227    /// flash size), where a page X is considered swapped if index at location (`X + WRITE_SIZE`)
228    /// contains a zero value. This ensures that index updates can be performed atomically and
229    /// avoid a situation where the wrong index value is set (page write size is "atomic").
230    ///
231    ///
232    /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
233    /// |-----------|------------|--------|--------|--------|--------|
234    /// |    Active |          0 |      1 |      2 |      3 |      - |
235    /// |       DFU |          0 |      4 |      5 |      6 |      X |
236    ///
237    /// The algorithm starts by copying 'backwards', and after the first step, the layout is
238    /// as follows:
239    ///
240    /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
241    /// |-----------|------------|--------|--------|--------|--------|
242    /// |    Active |          1 |      1 |      2 |      6 |      - |
243    /// |       DFU |          1 |      4 |      5 |      6 |      3 |
244    ///
245    /// The next iteration performs the same steps
246    ///
247    /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
248    /// |-----------|------------|--------|--------|--------|--------|
249    /// |    Active |          2 |      1 |      5 |      6 |      - |
250    /// |       DFU |          2 |      4 |      5 |      2 |      3 |
251    ///
252    /// And again until we're done
253    ///
254    /// | Partition | Swap Index | Page 0 | Page 1 | Page 3 | Page 4 |
255    /// |-----------|------------|--------|--------|--------|--------|
256    /// |    Active |          3 |      4 |      5 |      6 |      - |
257    /// |       DFU |          3 |      4 |      1 |      2 |      3 |
258    ///
259    /// ## REVERTING
260    ///
261    /// The reverting algorithm uses the swap index to discover that images were swapped, but that
262    /// the application failed to mark the boot successful. In this case, the revert algorithm will
263    /// run.
264    ///
265    /// The revert index is located separately from the swap index, to ensure that revert can continue
266    /// on power failure.
267    ///
268    /// The revert algorithm works forwards, by starting copying into the 'unused' DFU page at the start.
269    ///
270    /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
271    /// |-----------|--------------|--------|--------|--------|--------|
272    /// |    Active |            3 |      1 |      5 |      6 |      - |
273    /// |       DFU |            3 |      4 |      1 |      2 |      3 |
274    ///
275    ///
276    /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
277    /// |-----------|--------------|--------|--------|--------|--------|
278    /// |    Active |            3 |      1 |      2 |      6 |      - |
279    /// |       DFU |            3 |      4 |      5 |      2 |      3 |
280    ///
281    /// | Partition | Revert Index | Page 0 | Page 1 | Page 3 | Page 4 |
282    /// |-----------|--------------|--------|--------|--------|--------|
283    /// |    Active |            3 |      1 |      2 |      3 |      - |
284    /// |       DFU |            3 |      4 |      5 |      6 |      3 |
285    ///
286    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        // Ensure we have enough progress pages to store copy progress
295        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        // Ensure our partitions are able to handle boot operations
301        assert_partitions(&self.active, &self.dfu, &self.state, Self::PAGE_SIZE);
302
303        // Copy contents from partition N to active
304        let state = self.read_state(aligned_buf)?;
305        if state == State::Swap {
306            //
307            // Check if we already swapped. If we're in the swap state, this means we should revert
308            // since the app has failed to mark boot as successful
309            //
310            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                // Invalidate progress
321                state_word.fill(!STATE_ERASE_VALUE);
322                self.state.write(STATE::WRITE_SIZE as u32, state_word)?;
323
324                // Invalidate magic, so a torn erase cannot leave SWAP with partially erased progress
325                self.state.write(0, state_word)?;
326
327                // Clear magic and progress
328                self.state.erase(0, self.state.capacity() as u32)?;
329
330                // Set magic
331                state_word.fill(REVERT_MAGIC);
332                self.state.write(0, state_word)?;
333            }
334        }
335        Ok(state)
336    }
337
338    /// Read the magic state from flash.
339    ///
340    /// The buffer must hold at least `STATE::WRITE_SIZE` bytes and satisfy the
341    /// state flash's buffer alignment requirements.
342    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        // Magic, progress validity, progress records, and a trailing reserved word.
368        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            // Progress is invalid
375            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            // Copy active page to the 'next' DFU page.
446            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            //trace!("Copy active {} to dfu {}", active_from_offset, dfu_to_offset);
449            self.copy_page_once_to_dfu(progress_index, active_from_offset, dfu_to_offset, aligned_buf)?;
450
451            // Copy DFU page to the active page
452            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            //trace!("Copy dfy {} to active {}", dfu_from_offset, active_to_offset);
455            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            // Copy the bad active page to the DFU page
467            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            // Copy the DFU page back to the active page
472            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    // DFU partition has to be bigger than ACTIVE partition to handle swap algorithm
490    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        // Signing is slow in debug builds, and the torn-state tests call this tens of thousands of times.
528        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        // Fail both the signature read and a read while hashing the image.
577        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        // Reset after erasing the state but before recording Revert.
597        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                        // The candidate must be verified again at zero progress.
640                        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                    // A different key must not recheck already authenticated copying.
655                    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                // Rollback must not try to authenticate the mixed DFU contents.
663                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    // Every subset of the programmed state words surviving a torn erase must read as Boot.
676    #[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}