embassy_boot/firmware_updater/
asynch.rs

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