Skip to main content

hazard3_boot/firmware_updater/
asynch.rs

1use embedded_storage_async::nor_flash::NorFlash;
2#[cfg(target_os = "none")]
3use hazard3_embedded_hal::flash::partition::Partition;
4#[cfg(target_os = "none")]
5use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
6
7use super::FirmwareUpdaterConfig;
8use crate::verification::asynch::{hash, verify};
9use crate::verification::{Digest, VerifyingKey};
10use crate::{BOOT_MAGIC, DFU_DETACH_MAGIC, FirmwareUpdaterError, STATE_ERASE_VALUE, SWAP_MAGIC, State};
11
12/// FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
13/// 'mess up' the internal bootloader state
14pub struct FirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> {
15    dfu: DFU,
16    state: FirmwareState<'d, STATE>,
17    last_erased_dfu_sector_index: Option<usize>,
18}
19
20#[cfg(target_os = "none")]
21impl<'a, DFU: NorFlash, STATE: NorFlash>
22    FirmwareUpdaterConfig<Partition<'a, NoopRawMutex, DFU>, Partition<'a, NoopRawMutex, STATE>>
23{
24    /// Create a firmware updater config from the flash and address symbols defined in the linkerfile
25    pub fn from_linkerfile(
26        dfu_flash: &'a hazard3_sync::mutex::Mutex<NoopRawMutex, DFU>,
27        state_flash: &'a hazard3_sync::mutex::Mutex<NoopRawMutex, STATE>,
28    ) -> Self {
29        unsafe extern "C" {
30            static __bootloader_state_start: u32;
31            static __bootloader_state_end: u32;
32            static __bootloader_dfu_start: u32;
33            static __bootloader_dfu_end: u32;
34        }
35
36        let dfu = unsafe {
37            let start = &__bootloader_dfu_start as *const u32 as u32;
38            let end = &__bootloader_dfu_end as *const u32 as u32;
39            trace!("DFU: 0x{:x} - 0x{:x}", start, end);
40
41            Partition::new(dfu_flash, start, end - start)
42        };
43        let state = unsafe {
44            let start = &__bootloader_state_start as *const u32 as u32;
45            let end = &__bootloader_state_end as *const u32 as u32;
46            trace!("STATE: 0x{:x} - 0x{:x}", start, end);
47
48            Partition::new(state_flash, start, end - start)
49        };
50
51        Self { dfu, state }
52    }
53}
54
55impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> {
56    /// Create a firmware updater instance with partition ranges for the update and state partitions.
57    pub fn new(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
58        Self {
59            dfu: config.dfu,
60            state: FirmwareState::new(config.state, aligned),
61            last_erased_dfu_sector_index: None,
62        }
63    }
64
65    /// Obtain the current state.
66    ///
67    /// This is useful to check if the bootloader has just done a swap, in order
68    /// to do verifications and self-tests of the new image before calling
69    /// `mark_booted`.
70    pub async fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
71        self.state.get_state().await
72    }
73
74    /// Verify the DFU given a public key. If there is an error then DO NOT
75    /// proceed with updating the firmware as it must be signed with a
76    /// corresponding private key (otherwise it could be malicious firmware).
77    ///
78    /// Mark to trigger firmware swap on next boot if verify succeeds.
79    ///
80    /// The signature is expected to have been generated
81    /// from the firmware bytes using a digest of the provided type.
82    ///
83    /// See [`super::BlockingFirmwareUpdater::verify_and_mark_updated`]
84    /// for buffer requirements, errors, and panics.
85    pub async fn verify_and_mark_updated<D: Digest, V: VerifyingKey>(
86        &mut self,
87        public_key: &[u8],
88        signature: &[u8],
89        chunk_buf: &mut [u8],
90        update_len: u32,
91    ) -> Result<(), FirmwareUpdaterError> {
92        assert!(update_len <= self.dfu.capacity() as u32);
93
94        self.state.verify_booted().await?;
95
96        verify::<_, D, V>(&mut self.dfu, public_key, signature, update_len, chunk_buf).await?;
97        return self.state.mark_updated().await;
98    }
99
100    /// Compute a digest of the update in the DFU partition.
101    ///
102    /// See [`super::BlockingFirmwareUpdater::hash`] for buffer requirements,
103    /// errors, and panics.
104    pub async fn hash<D: Digest>(
105        &mut self,
106        update_len: u32,
107        chunk_buf: &mut [u8],
108    ) -> Result<D::Output, FirmwareUpdaterError> {
109        Ok(hash::<_, D>(&mut self.dfu, update_len, chunk_buf).await?)
110    }
111
112    /// Read a slice of data from the DFU storage peripheral, starting the read
113    /// operation at the given address offset, and reading `buf.len()` bytes.
114    ///
115    /// # Errors
116    ///
117    /// Returns an error if the arguments are not aligned or out of bounds.
118    pub async fn read_dfu(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), FirmwareUpdaterError> {
119        self.dfu.read(offset, buf).await?;
120        Ok(())
121    }
122
123    /// Erase data from the DFU storage peripheral, starting the erase
124    /// operation at the given address from, and erasing until to.
125    ///
126    /// # Errors
127    ///
128    /// Returns an error if the arguments are not aligned or out of bounds.
129    pub async fn erase_dfu(&mut self, from: u32, to: u32) -> Result<(), FirmwareUpdaterError> {
130        self.dfu.erase(from, to).await?;
131        Ok(())
132    }
133
134    /// Write a slice of data to the DFU storage peripheral, starting the write
135    /// operation at the given address offset, and writting `buf.len()` bytes.
136    ///
137    /// # Errors
138    ///
139    /// Returns an error if the arguments are not aligned or out of bounds.
140    pub async fn write_dfu(&mut self, offset: u32, buf: &[u8]) -> Result<(), FirmwareUpdaterError> {
141        self.dfu.write(offset, buf).await?;
142        Ok(())
143    }
144
145    /// Mark to trigger firmware swap on next boot.
146    ///
147    /// With signature support enabled, verify first or use a verifying bootloader.
148    pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
149        self.state.mark_updated().await
150    }
151
152    /// Mark to trigger USB DFU on next boot.
153    pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
154        self.state.verify_booted().await?;
155        self.state.mark_dfu().await
156    }
157
158    /// Mark firmware boot successful and stop rollback on reset.
159    pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
160        self.state.mark_booted().await
161    }
162
163    /// Writes firmware data to the device.
164    ///
165    /// This function writes the given data to the firmware area starting at the specified offset.
166    /// It handles sector erasures and data writes while verifying the device is in a proper state
167    /// for firmware updates. The function ensures that only unerased sectors are erased before
168    /// writing and efficiently handles the writing process across sector boundaries and in
169    /// various configurations (data size, sector size, etc.).
170    ///
171    /// # Arguments
172    ///
173    /// * `offset` - The starting offset within the firmware area where data writing should begin.
174    /// * `data` - A slice of bytes representing the firmware data to be written. It must be a
175    /// multiple of NorFlash WRITE_SIZE.
176    ///
177    /// # Returns
178    ///
179    /// A `Result<(), FirmwareUpdaterError>` indicating the success or failure of the write operation.
180    ///
181    /// # Errors
182    ///
183    /// This function will return an error if:
184    ///
185    /// - The device is not in a proper state to receive firmware updates (e.g., not booted).
186    /// - There is a failure erasing a sector before writing.
187    /// - There is a failure writing data to the device.
188    pub async fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> {
189        // Make sure we are running a booted firmware to avoid reverting to a bad state.
190        self.state.verify_booted().await?;
191
192        // Initialize variables to keep track of the remaining data and the current offset.
193        let mut remaining_data = data;
194        let mut offset = offset;
195
196        // Continue writing as long as there is data left to write.
197        while !remaining_data.is_empty() {
198            // Compute the current sector and its boundaries.
199            let current_sector = offset / DFU::ERASE_SIZE;
200            let sector_start = current_sector * DFU::ERASE_SIZE;
201            let sector_end = sector_start + DFU::ERASE_SIZE;
202            // Determine if the current sector needs to be erased before writing.
203            let need_erase = self
204                .last_erased_dfu_sector_index
205                .map_or(true, |last_erased_sector| current_sector != last_erased_sector);
206
207            // If the sector needs to be erased, erase it and update the last erased sector index.
208            if need_erase {
209                self.dfu.erase(sector_start as u32, sector_end as u32).await?;
210                self.last_erased_dfu_sector_index = Some(current_sector);
211            }
212
213            // Calculate the size of the data chunk that can be written in the current iteration.
214            let write_size = core::cmp::min(remaining_data.len(), sector_end - offset);
215            // Split the data to get the current chunk to be written and the remaining data.
216            let (data_chunk, rest) = remaining_data.split_at(write_size);
217
218            // Write the current data chunk.
219            self.dfu.write(offset as u32, data_chunk).await?;
220
221            // Update the offset and remaining data for the next iteration.
222            remaining_data = rest;
223            offset += write_size;
224        }
225
226        Ok(())
227    }
228
229    /// Prepare for an incoming DFU update by erasing the entire DFU area and
230    /// returning its `Partition`.
231    ///
232    /// Using this instead of `write_firmware` allows for an optimized API in
233    /// exchange for added complexity.
234    pub async fn prepare_update(&mut self) -> Result<&mut DFU, FirmwareUpdaterError> {
235        self.state.verify_booted().await?;
236        self.dfu.erase(0, self.dfu.capacity() as u32).await?;
237
238        Ok(&mut self.dfu)
239    }
240
241    /// Reset to initial/uninitialised state.
242    ///
243    /// After reset, the updater will behave as if no writes had
244    /// occurred, with writes beginning at offset 0 again.
245    pub async fn reset(&mut self) -> Result<(), FirmwareUpdaterError> {
246        self.state.verify_booted().await?;
247        self.last_erased_dfu_sector_index = None;
248        Ok(())
249    }
250}
251
252/// Manages the state partition of the firmware update.
253///
254/// Can be used standalone for more fine grained control, or as part of the updater.
255pub struct FirmwareState<'d, STATE> {
256    state: STATE,
257    aligned: &'d mut [u8],
258}
259
260impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> {
261    /// Create a firmware state instance from a FirmwareUpdaterConfig with a buffer for magic content and state partition.
262    ///
263    /// # Safety
264    ///
265    /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
266    /// and written to.
267    pub fn from_config<DFU: NorFlash>(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
268        Self::new(config.state, aligned)
269    }
270
271    /// Create a firmware state instance with a buffer for magic content and state partition.
272    ///
273    /// # Safety
274    ///
275    /// The `aligned` buffer must have a size of maximum of STATE::WRITE_SIZE and STATE::READ_SIZE,
276    /// and follow the alignment rules for the flash being read from and written to.
277    pub fn new(state: STATE, aligned: &'d mut [u8]) -> Self {
278        assert_eq!(aligned.len(), STATE::WRITE_SIZE.max(STATE::READ_SIZE));
279        Self { state, aligned }
280    }
281
282    // Make sure we are running a booted firmware to avoid reverting to a bad state.
283    async fn verify_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
284        let state = self.get_state().await?;
285        if state == State::Boot || state == State::DfuDetach || state == State::Revert {
286            Ok(())
287        } else {
288            Err(FirmwareUpdaterError::BadState)
289        }
290    }
291
292    /// Obtain the current state.
293    ///
294    /// This is useful to check if the bootloader has just done a swap, in order
295    /// to do verifications and self-tests of the new image before calling
296    /// `mark_booted`.
297    pub async fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
298        self.state.read(0, &mut self.aligned).await?;
299        Ok(State::from(&self.aligned[..STATE::WRITE_SIZE]))
300    }
301
302    /// Mark to trigger firmware swap on next boot.
303    pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
304        self.set_magic(SWAP_MAGIC).await
305    }
306
307    /// Mark to trigger USB DFU on next boot.
308    pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
309        self.set_magic(DFU_DETACH_MAGIC).await
310    }
311
312    /// Mark firmware boot successful and stop rollback on reset.
313    pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
314        self.set_magic(BOOT_MAGIC).await
315    }
316
317    async fn set_magic(&mut self, magic: u8) -> Result<(), FirmwareUpdaterError> {
318        self.state.read(0, &mut self.aligned).await?;
319
320        if self.aligned[..STATE::WRITE_SIZE].iter().any(|&b| b != magic) {
321            let swap = !self.aligned[..STATE::WRITE_SIZE].iter().any(|&b| b != SWAP_MAGIC);
322
323            // Read progress validity
324            if STATE::READ_SIZE <= 2 * STATE::WRITE_SIZE {
325                self.state.read(STATE::WRITE_SIZE as u32, &mut self.aligned).await?;
326            } else {
327                self.aligned.rotate_left(STATE::WRITE_SIZE);
328            }
329
330            if self.aligned[..STATE::WRITE_SIZE]
331                .iter()
332                .any(|&b| b != STATE_ERASE_VALUE)
333            {
334                // The current progress validity marker is invalid
335            } else {
336                // Invalidate progress
337                self.aligned.fill(!STATE_ERASE_VALUE);
338                self.state
339                    .write(STATE::WRITE_SIZE as u32, &self.aligned[..STATE::WRITE_SIZE])
340                    .await?;
341            }
342
343            if swap {
344                // Invalidate magic, so a torn erase cannot leave SWAP with partially erased progress
345                self.aligned.fill(!STATE_ERASE_VALUE);
346                self.state.write(0, &self.aligned[..STATE::WRITE_SIZE]).await?;
347            }
348
349            // Clear magic and progress
350            self.state.erase(0, self.state.capacity() as u32).await?;
351
352            // Set magic
353            self.aligned.fill(magic);
354            self.state.write(0, &self.aligned[..STATE::WRITE_SIZE]).await?;
355        }
356        Ok(())
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use hazard3_crypto::Sha1;
363    use hazard3_crypto_rand as _;
364    use hazard3_crypto_rustcrypto as _;
365    use hazard3_embedded_hal::flash::partition::Partition;
366    use hazard3_futures::block_on;
367    use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
368    use hazard3_sync::mutex::Mutex;
369
370    use super::*;
371    use crate::mem_flash::MemFlash;
372
373    #[test]
374    fn can_verify_sha1() {
375        let flash = Mutex::<NoopRawMutex, _>::new(MemFlash::<131072, 4096, 8>::default());
376        let state = Partition::new(&flash, 0, 4096);
377        let dfu = Partition::new(&flash, 65536, 65536);
378        let mut aligned = [0; 8];
379
380        let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
381        let mut to_write = [0; 4096];
382        to_write[..7].copy_from_slice(update.as_slice());
383
384        let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
385        block_on(updater.write_firmware(0, to_write.as_slice())).unwrap();
386        let mut chunk_buf = [0; 2];
387        let hash = block_on(updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf)).unwrap();
388
389        assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
390    }
391
392    #[test]
393    fn can_verify_sha1_sector_bigger_than_chunk() {
394        let flash = Mutex::<NoopRawMutex, _>::new(MemFlash::<131072, 4096, 8>::default());
395        let state = Partition::new(&flash, 0, 4096);
396        let dfu = Partition::new(&flash, 65536, 65536);
397        let mut aligned = [0; 8];
398
399        let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
400        let mut to_write = [0; 4096];
401        to_write[..7].copy_from_slice(update.as_slice());
402
403        let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
404        let mut offset = 0;
405        for chunk in to_write.chunks(1024) {
406            block_on(updater.write_firmware(offset, chunk)).unwrap();
407            offset += chunk.len();
408        }
409        let mut chunk_buf = [0; 2];
410        let hash = block_on(updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf)).unwrap();
411
412        assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
413    }
414
415    #[test]
416    fn can_verify_sha1_sector_smaller_than_chunk() {
417        let flash = Mutex::<NoopRawMutex, _>::new(MemFlash::<131072, 1024, 8>::default());
418        let state = Partition::new(&flash, 0, 4096);
419        let dfu = Partition::new(&flash, 65536, 65536);
420        let mut aligned = [0; 8];
421
422        let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
423        let mut to_write = [0; 4096];
424        to_write[..7].copy_from_slice(update.as_slice());
425
426        let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
427        let mut offset = 0;
428        for chunk in to_write.chunks(2048) {
429            block_on(updater.write_firmware(offset, chunk)).unwrap();
430            offset += chunk.len();
431        }
432        let mut chunk_buf = [0; 2];
433        let hash = block_on(updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf)).unwrap();
434
435        assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
436    }
437
438    #[test]
439    fn can_verify_sha1_cross_sector_boundary() {
440        let flash = Mutex::<NoopRawMutex, _>::new(MemFlash::<131072, 1024, 8>::default());
441        let state = Partition::new(&flash, 0, 4096);
442        let dfu = Partition::new(&flash, 65536, 65536);
443        let mut aligned = [0; 8];
444
445        let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
446        let mut to_write = [0; 4096];
447        to_write[..7].copy_from_slice(update.as_slice());
448
449        let mut updater = FirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
450        let mut offset = 0;
451        for chunk in to_write.chunks(896) {
452            block_on(updater.write_firmware(offset, chunk)).unwrap();
453            offset += chunk.len();
454        }
455        let mut chunk_buf = [0; 2];
456        let hash = block_on(updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf)).unwrap();
457
458        assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
459    }
460}