embassy_boot/firmware_updater/
blocking.rs

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