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
11pub 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 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 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 pub async fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
70 self.state.get_state().await
71 }
72
73 #[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 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 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 #[cfg(not(feature = "_verify"))]
177 pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
178 self.state.mark_updated().await
179 }
180
181 pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
183 self.state.verify_booted().await?;
184 self.state.mark_dfu().await
185 }
186
187 pub async fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
189 self.state.mark_booted().await
190 }
191
192 pub async fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> {
218 self.state.verify_booted().await?;
220
221 let mut remaining_data = data;
223 let mut offset = offset;
224
225 while !remaining_data.is_empty() {
227 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 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 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 let write_size = core::cmp::min(remaining_data.len(), sector_end - offset);
244 let (data_chunk, rest) = remaining_data.split_at(write_size);
246
247 self.dfu.write(offset as u32, data_chunk).await?;
249
250 remaining_data = rest;
252 offset += write_size;
253 }
254
255 Ok(())
256 }
257
258 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
271pub struct FirmwareState<'d, STATE> {
275 state: STATE,
276 aligned: &'d mut [u8],
277}
278
279impl<'d, STATE: NorFlash> FirmwareState<'d, STATE> {
280 pub fn from_config<DFU: NorFlash>(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
287 Self::new(config.state, aligned)
288 }
289
290 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 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 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 pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
323 self.set_magic(SWAP_MAGIC).await
324 }
325
326 pub async fn mark_dfu(&mut self) -> Result<(), FirmwareUpdaterError> {
328 self.set_magic(DFU_DETACH_MAGIC).await
329 }
330
331 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 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 } else {
353 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 self.state.erase(0, self.state.capacity() as u32).await?;
362
363 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}