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
12pub 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 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 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 pub async fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
71 self.state.get_state().await
72 }
73
74 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 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 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 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 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 pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
149 self.state.mark_updated().await
150 }
151
152 pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
154 self.state.verify_booted().await?;
155 self.state.mark_dfu().await
156 }
157
158 pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
160 self.state.mark_booted().await
161 }
162
163 pub async fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> {
189 self.state.verify_booted().await?;
191
192 let mut remaining_data = data;
194 let mut offset = offset;
195
196 while !remaining_data.is_empty() {
198 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 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 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 let write_size = core::cmp::min(remaining_data.len(), sector_end - offset);
215 let (data_chunk, rest) = remaining_data.split_at(write_size);
217
218 self.dfu.write(offset as u32, data_chunk).await?;
220
221 remaining_data = rest;
223 offset += write_size;
224 }
225
226 Ok(())
227 }
228
229 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 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
252pub struct FirmwareState<'d, STATE> {
256 state: STATE,
257 aligned: &'d mut [u8],
258}
259
260impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> {
261 pub fn from_config<DFU: NorFlash>(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
268 Self::new(config.state, aligned)
269 }
270
271 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 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 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 pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
304 self.set_magic(SWAP_MAGIC).await
305 }
306
307 pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
309 self.set_magic(DFU_DETACH_MAGIC).await
310 }
311
312 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 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 } else {
336 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 self.aligned.fill(!STATE_ERASE_VALUE);
346 self.state.write(0, &self.aligned[..STATE::WRITE_SIZE]).await?;
347 }
348
349 self.state.erase(0, self.state.capacity() as u32).await?;
351
352 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}