hazard3_boot/firmware_updater/blocking.rs
1use embedded_storage::nor_flash::NorFlash;
2#[cfg(target_os = "none")]
3use hazard3_embedded_hal::flash::partition::BlockingPartition;
4#[cfg(target_os = "none")]
5use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
6
7use super::FirmwareUpdaterConfig;
8use crate::verification::blocking::{hash, verify};
9use crate::verification::{Digest, VerifyingKey};
10use crate::{BOOT_MAGIC, DFU_DETACH_MAGIC, FirmwareUpdaterError, STATE_ERASE_VALUE, SWAP_MAGIC, State};
11
12/// Blocking FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
13/// 'mess up' the internal bootloader state
14pub struct BlockingFirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> {
15 dfu: DFU,
16 state: BlockingFirmwareState<'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<BlockingPartition<'a, NoopRawMutex, DFU>, BlockingPartition<'a, NoopRawMutex, STATE>>
23{
24 /// Constructs a `FirmwareUpdaterConfig` instance from flash memory and address symbols defined in the linker file.
25 ///
26 /// This method initializes `BlockingPartition` instances for the DFU (Device Firmware Update), and state
27 /// partitions, leveraging start and end addresses specified by the linker. These partitions are critical
28 /// for managing firmware updates, application state, and boot operations within the bootloader.
29 ///
30 /// # Parameters
31 /// - `dfu_flash`: A reference to a mutex-protected `RefCell` for the DFU partition's flash interface.
32 /// - `state_flash`: A reference to a mutex-protected `RefCell` for the state partition's flash interface.
33 ///
34 /// # Safety
35 /// The method contains `unsafe` blocks for dereferencing raw pointers that represent the start and end addresses
36 /// of the bootloader's partitions in flash memory. It is crucial that these addresses are accurately defined
37 /// in the memory.x file to prevent undefined behavior.
38 ///
39 /// The caller must ensure that the memory regions defined by these symbols are valid and that the flash memory
40 /// interfaces provided are compatible with these regions.
41 ///
42 /// # Returns
43 /// A `FirmwareUpdaterConfig` instance with `BlockingPartition` instances for the DFU, and state partitions.
44 ///
45 /// # Example
46 /// ```ignore
47 /// // Assume `dfu_flash`, and `state_flash` share the same flash memory interface.
48 /// let layout = Flash::new_blocking(p.FLASH, Default::default()).into_blocking_regions();
49 /// let flash = Mutex::new(RefCell::new(layout.bank1_region));
50 ///
51 /// let config = FirmwareUpdaterConfig::from_linkerfile_blocking(&flash, &flash);
52 /// // `config` can now be used to create a `FirmwareUpdater` instance for managing boot operations.
53 /// ```
54 /// Working examples can be found in the bootloader examples folder.
55 pub fn from_linkerfile_blocking(
56 dfu_flash: &'a hazard3_sync::blocking_mutex::Mutex<NoopRawMutex, core::cell::RefCell<DFU>>,
57 state_flash: &'a hazard3_sync::blocking_mutex::Mutex<NoopRawMutex, core::cell::RefCell<STATE>>,
58 ) -> Self {
59 unsafe extern "C" {
60 static __bootloader_state_start: u32;
61 static __bootloader_state_end: u32;
62 static __bootloader_dfu_start: u32;
63 static __bootloader_dfu_end: u32;
64 }
65
66 let dfu = unsafe {
67 let start = &__bootloader_dfu_start as *const u32 as u32;
68 let end = &__bootloader_dfu_end as *const u32 as u32;
69 trace!("DFU: 0x{:x} - 0x{:x}", start, end);
70
71 BlockingPartition::new(dfu_flash, start, end - start)
72 };
73 let state = unsafe {
74 let start = &__bootloader_state_start as *const u32 as u32;
75 let end = &__bootloader_state_end as *const u32 as u32;
76 trace!("STATE: 0x{:x} - 0x{:x}", start, end);
77
78 BlockingPartition::new(state_flash, start, end - start)
79 };
80
81 Self { dfu, state }
82 }
83}
84
85impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> {
86 /// Create a firmware updater instance with partition ranges for the update and state partitions.
87 ///
88 /// # Safety
89 ///
90 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
91 /// and written to.
92 pub fn new(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
93 Self {
94 dfu: config.dfu,
95 state: BlockingFirmwareState::new(config.state, aligned),
96 last_erased_dfu_sector_index: None,
97 }
98 }
99
100 /// Obtain the current state.
101 ///
102 /// This is useful to check if the bootloader has just done a swap, in order
103 /// to do verifications and self-tests of the new image before calling
104 /// `mark_booted`.
105 pub fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
106 self.state.get_state()
107 }
108
109 /// Verify the DFU given a public key. If there is an error then DO NOT
110 /// proceed with updating the firmware as it must be signed with a
111 /// corresponding private key (otherwise it could be malicious firmware).
112 ///
113 /// Mark to trigger firmware swap on next boot if verify succeeds.
114 ///
115 /// The signature is expected to have been generated
116 /// from the firmware bytes using a digest of the provided type.
117 ///
118 /// # Buffer requirements
119 ///
120 /// `chunk_buf` must be nonempty and satisfy the flash's buffer alignment
121 /// requirements. Reads start at zero and use full chunks, so its length must
122 /// be a multiple of `DFU::READ_SIZE` and DFU must be readable through
123 /// `update_len` rounded up to that length. Only `0..update_len` is hashed.
124 /// Flash read failures are returned as errors.
125 ///
126 /// # Panics
127 ///
128 /// Panics if `chunk_buf` is empty or `update_len` exceeds dfu capacity.
129 pub fn verify_and_mark_updated<D: Digest, V: VerifyingKey>(
130 &mut self,
131 public_key: &[u8],
132 signature: &[u8],
133 chunk_buf: &mut [u8],
134 update_len: u32,
135 ) -> Result<(), FirmwareUpdaterError> {
136 assert!(update_len <= self.dfu.capacity() as u32);
137
138 self.state.verify_booted()?;
139
140 verify::<_, D, V>(&mut self.dfu, public_key, signature, update_len, chunk_buf)?;
141 self.state.mark_updated()
142 }
143
144 /// Compute a digest of the update in the DFU partition.
145 ///
146 /// # Buffer requirements
147 ///
148 /// `chunk_buf` must be nonempty and satisfy the flash's buffer alignment
149 /// requirements. Reads start at zero and use full chunks, so its length must
150 /// be a multiple of `DFU::READ_SIZE` and DFU must be readable through
151 /// `update_len` rounded up to that length. Only `0..update_len` is hashed.
152 /// Flash read failures are returned as errors.
153 ///
154 /// # Panics
155 ///
156 /// Panics if `chunk_buf` is empty.
157 pub fn hash<D: Digest>(
158 &mut self,
159 update_len: u32,
160 chunk_buf: &mut [u8],
161 ) -> Result<D::Output, FirmwareUpdaterError> {
162 Ok(hash::<_, D>(&mut self.dfu, update_len, chunk_buf)?)
163 }
164
165 /// Read a slice of data from the DFU storage peripheral, starting the read
166 /// operation at the given address offset, and reading `buf.len()` bytes.
167 ///
168 /// # Errors
169 ///
170 /// Returns an error if the arguments are not aligned or out of bounds.
171 pub fn read_dfu(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), FirmwareUpdaterError> {
172 self.dfu.read(offset, buf)?;
173 Ok(())
174 }
175
176 /// Erase data from the DFU storage peripheral, starting the erase
177 /// operation at the given address from, and erasing until to.
178 ///
179 /// # Errors
180 ///
181 /// Returns an error if the arguments are not aligned or out of bounds.
182 pub fn erase_dfu(&mut self, from: u32, to: u32) -> Result<(), FirmwareUpdaterError> {
183 self.dfu.erase(from, to)?;
184 Ok(())
185 }
186
187 /// Write a slice of data to the DFU storage peripheral, starting the write
188 /// operation at the given address offset, and writting `buf.len()` bytes.
189 ///
190 /// # Errors
191 ///
192 /// Returns an error if the arguments are not aligned or out of bounds.
193 pub fn write_dfu(&mut self, offset: u32, buf: &[u8]) -> Result<(), FirmwareUpdaterError> {
194 self.dfu.write(offset, buf)?;
195 Ok(())
196 }
197
198 /// Mark to trigger firmware swap on next boot.
199 ///
200 /// With signature support enabled, verify first or use a verifying bootloader.
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 let swap = !self.aligned.iter().any(|&b| b != SWAP_MAGIC);
365
366 // Read progress validity
367 self.state.read(STATE::WRITE_SIZE as u32, &mut self.aligned)?;
368
369 if self.aligned.iter().any(|&b| b != STATE_ERASE_VALUE) {
370 // The current progress validity marker is invalid
371 } else {
372 // Invalidate progress
373 self.aligned.fill(!STATE_ERASE_VALUE);
374 self.state.write(STATE::WRITE_SIZE as u32, &self.aligned)?;
375 }
376
377 if swap {
378 // Invalidate magic, so a torn erase cannot leave SWAP with partially erased progress
379 self.aligned.fill(!STATE_ERASE_VALUE);
380 self.state.write(0, &self.aligned)?;
381 }
382
383 // Clear magic and progress
384 self.state.erase(0, self.state.capacity() as u32)?;
385
386 // Set magic
387 self.aligned.fill(magic);
388 self.state.write(0, &self.aligned)?;
389 }
390 Ok(())
391 }
392}
393
394#[cfg(test)]
395mod tests {
396 use core::cell::RefCell;
397
398 use hazard3_crypto::Sha1;
399 use hazard3_crypto_rand as _;
400 use hazard3_crypto_rustcrypto as _;
401 use hazard3_embedded_hal::flash::partition::BlockingPartition;
402 use hazard3_sync::blocking_mutex::Mutex;
403 use hazard3_sync::blocking_mutex::raw::NoopRawMutex;
404
405 use super::*;
406 use crate::mem_flash::MemFlash;
407
408 #[test]
409 fn can_verify_sha1() {
410 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 4096, 8>::default()));
411 let state = BlockingPartition::new(&flash, 0, 4096);
412 let dfu = BlockingPartition::new(&flash, 65536, 65536);
413 let mut aligned = [0; 8];
414
415 let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
416 let mut to_write = [0; 4096];
417 to_write[..7].copy_from_slice(update.as_slice());
418
419 let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
420 updater.write_firmware(0, to_write.as_slice()).unwrap();
421 let mut chunk_buf = [0; 2];
422 let hash = updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf).unwrap();
423
424 assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
425 }
426
427 #[test]
428 fn can_verify_sha1_sector_bigger_than_chunk() {
429 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 4096, 8>::default()));
430 let state = BlockingPartition::new(&flash, 0, 4096);
431 let dfu = BlockingPartition::new(&flash, 65536, 65536);
432 let mut aligned = [0; 8];
433
434 let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
435 let mut to_write = [0; 4096];
436 to_write[..7].copy_from_slice(update.as_slice());
437
438 let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
439 let mut offset = 0;
440 for chunk in to_write.chunks(1024) {
441 updater.write_firmware(offset, chunk).unwrap();
442 offset += chunk.len();
443 }
444 let mut chunk_buf = [0; 2];
445 let hash = updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf).unwrap();
446
447 assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
448 }
449
450 #[test]
451 fn can_verify_sha1_sector_smaller_than_chunk() {
452 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 1024, 8>::default()));
453 let state = BlockingPartition::new(&flash, 0, 4096);
454 let dfu = BlockingPartition::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 = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
462 let mut offset = 0;
463 for chunk in to_write.chunks(2048) {
464 updater.write_firmware(offset, chunk).unwrap();
465 offset += chunk.len();
466 }
467 let mut chunk_buf = [0; 2];
468 let hash = updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf).unwrap();
469
470 assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
471 }
472
473 #[test]
474 fn can_verify_sha1_cross_sector_boundary() {
475 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 1024, 8>::default()));
476 let state = BlockingPartition::new(&flash, 0, 4096);
477 let dfu = BlockingPartition::new(&flash, 65536, 65536);
478 let mut aligned = [0; 8];
479
480 let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
481 let mut to_write = [0; 4096];
482 to_write[..7].copy_from_slice(update.as_slice());
483
484 let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
485 let mut offset = 0;
486 for chunk in to_write.chunks(896) {
487 updater.write_firmware(offset, chunk).unwrap();
488 offset += chunk.len();
489 }
490 let mut chunk_buf = [0; 2];
491 let hash = updater.hash::<Sha1>(update.len() as u32, &mut chunk_buf).unwrap();
492
493 assert_eq!(Sha1::digest(&update).as_slice(), hash.as_ref());
494 }
495}