aboutsummaryrefslogtreecommitdiff
path: root/embassy-boot/boot/src/firmware_updater/blocking.rs
diff options
context:
space:
mode:
authorUlf Lilleengen <[email protected]>2023-08-03 20:56:04 +0200
committerUlf Lilleengen <[email protected]>2023-08-06 19:46:53 +0200
commita34331ae5fbf76a61bb2f65dbb13af4d34fcb176 (patch)
treeeddfa2b200b206923a91b9aae1474156c04e40fa /embassy-boot/boot/src/firmware_updater/blocking.rs
parenta40daa923ba031b543ce402f8bd83c2ec41329d8 (diff)
Refactor firmware updater
* Allow manipulating state without accessing DFU partition. * Provide aligned buffer when creating updater to reduce potential wrong parameters passed.
Diffstat (limited to 'embassy-boot/boot/src/firmware_updater/blocking.rs')
-rw-r--r--embassy-boot/boot/src/firmware_updater/blocking.rs196
1 files changed, 107 insertions, 89 deletions
diff --git a/embassy-boot/boot/src/firmware_updater/blocking.rs b/embassy-boot/boot/src/firmware_updater/blocking.rs
index f03f53e4d..76e4264a0 100644
--- a/embassy-boot/boot/src/firmware_updater/blocking.rs
+++ b/embassy-boot/boot/src/firmware_updater/blocking.rs
@@ -10,9 +10,9 @@ use crate::{FirmwareUpdaterError, State, BOOT_MAGIC, STATE_ERASE_VALUE, SWAP_MAG
10 10
11/// Blocking FirmwareUpdater is an application API for interacting with the BootLoader without the ability to 11/// Blocking FirmwareUpdater is an application API for interacting with the BootLoader without the ability to
12/// 'mess up' the internal bootloader state 12/// 'mess up' the internal bootloader state
13pub struct BlockingFirmwareUpdater<DFU: NorFlash, STATE: NorFlash> { 13pub struct BlockingFirmwareUpdater<'d, DFU: NorFlash, STATE: NorFlash> {
14 dfu: DFU, 14 dfu: DFU,
15 state: STATE, 15 state: BlockingFirmwareState<'d, STATE>,
16} 16}
17 17
18#[cfg(target_os = "none")] 18#[cfg(target_os = "none")]
@@ -49,22 +49,17 @@ impl<'a, FLASH: NorFlash>
49 } 49 }
50} 50}
51 51
52impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> { 52impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> {
53 /// Create a firmware updater instance with partition ranges for the update and state partitions. 53 /// Create a firmware updater instance with partition ranges for the update and state partitions.
54 pub fn new(config: FirmwareUpdaterConfig<DFU, STATE>) -> Self { 54 ///
55 /// # Safety
56 ///
57 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
58 /// and written to.
59 pub fn new(config: FirmwareUpdaterConfig<DFU, STATE>, aligned: &'d mut [u8]) -> Self {
55 Self { 60 Self {
56 dfu: config.dfu, 61 dfu: config.dfu,
57 state: config.state, 62 state: BlockingFirmwareState::new(config.state, aligned),
58 }
59 }
60
61 // Make sure we are running a booted firmware to avoid reverting to a bad state.
62 fn verify_booted(&mut self, aligned: &mut [u8]) -> Result<(), FirmwareUpdaterError> {
63 assert_eq!(aligned.len(), STATE::WRITE_SIZE);
64 if self.get_state(aligned)? == State::Boot {
65 Ok(())
66 } else {
67 Err(FirmwareUpdaterError::BadState)
68 } 63 }
69 } 64 }
70 65
@@ -73,14 +68,8 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
73 /// This is useful to check if the bootloader has just done a swap, in order 68 /// This is useful to check if the bootloader has just done a swap, in order
74 /// to do verifications and self-tests of the new image before calling 69 /// to do verifications and self-tests of the new image before calling
75 /// `mark_booted`. 70 /// `mark_booted`.
76 pub fn get_state(&mut self, aligned: &mut [u8]) -> Result<State, FirmwareUpdaterError> { 71 pub fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
77 self.state.read(0, aligned)?; 72 self.state.get_state()
78
79 if !aligned.iter().any(|&b| b != SWAP_MAGIC) {
80 Ok(State::Swap)
81 } else {
82 Ok(State::Boot)
83 }
84 } 73 }
85 74
86 /// Verify the DFU given a public key. If there is an error then DO NOT 75 /// Verify the DFU given a public key. If there is an error then DO NOT
@@ -94,23 +83,16 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
94 /// 83 ///
95 /// If no signature feature is set then this method will always return a 84 /// If no signature feature is set then this method will always return a
96 /// signature error. 85 /// signature error.
97 ///
98 /// # Safety
99 ///
100 /// The `_aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
101 /// and written to.
102 #[cfg(feature = "_verify")] 86 #[cfg(feature = "_verify")]
103 pub fn verify_and_mark_updated( 87 pub fn verify_and_mark_updated(
104 &mut self, 88 &mut self,
105 _public_key: &[u8], 89 _public_key: &[u8],
106 _signature: &[u8], 90 _signature: &[u8],
107 _update_len: u32, 91 _update_len: u32,
108 _aligned: &mut [u8],
109 ) -> Result<(), FirmwareUpdaterError> { 92 ) -> Result<(), FirmwareUpdaterError> {
110 assert_eq!(_aligned.len(), STATE::WRITE_SIZE);
111 assert!(_update_len <= self.dfu.capacity() as u32); 93 assert!(_update_len <= self.dfu.capacity() as u32);
112 94
113 self.verify_booted(_aligned)?; 95 self.state.verify_booted()?;
114 96
115 #[cfg(feature = "ed25519-dalek")] 97 #[cfg(feature = "ed25519-dalek")]
116 { 98 {
@@ -124,7 +106,8 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
124 let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?; 106 let signature = Signature::from_bytes(_signature).map_err(into_signature_error)?;
125 107
126 let mut message = [0; 64]; 108 let mut message = [0; 64];
127 self.hash::<Sha512>(_update_len, _aligned, &mut message)?; 109 let mut chunk_buf = [0; 2];
110 self.hash::<Sha512>(_update_len, &mut chunk_buf, &mut message)?;
128 111
129 public_key.verify(&message, &signature).map_err(into_signature_error)? 112 public_key.verify(&message, &signature).map_err(into_signature_error)?
130 } 113 }
@@ -145,7 +128,8 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
145 let signature = Signature::try_from(&signature).map_err(into_signature_error)?; 128 let signature = Signature::try_from(&signature).map_err(into_signature_error)?;
146 129
147 let mut message = [0; 64]; 130 let mut message = [0; 64];
148 self.hash::<Sha512>(_update_len, _aligned, &mut message)?; 131 let mut chunk_buf = [0; 2];
132 self.hash::<Sha512>(_update_len, &mut chunk_buf, &mut message)?;
149 133
150 let r = public_key.verify(&message, &signature); 134 let r = public_key.verify(&message, &signature);
151 trace!( 135 trace!(
@@ -158,7 +142,7 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
158 r.map_err(into_signature_error)? 142 r.map_err(into_signature_error)?
159 } 143 }
160 144
161 self.set_magic(_aligned, SWAP_MAGIC) 145 self.state.mark_updated()
162 } 146 }
163 147
164 /// Verify the update in DFU with any digest. 148 /// Verify the update in DFU with any digest.
@@ -179,49 +163,14 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
179 } 163 }
180 164
181 /// Mark to trigger firmware swap on next boot. 165 /// Mark to trigger firmware swap on next boot.
182 ///
183 /// # Safety
184 ///
185 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being written to.
186 #[cfg(not(feature = "_verify"))] 166 #[cfg(not(feature = "_verify"))]
187 pub fn mark_updated(&mut self, aligned: &mut [u8]) -> Result<(), FirmwareUpdaterError> { 167 pub fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
188 assert_eq!(aligned.len(), STATE::WRITE_SIZE); 168 self.state.mark_updated()
189 self.set_magic(aligned, SWAP_MAGIC)
190 } 169 }
191 170
192 /// Mark firmware boot successful and stop rollback on reset. 171 /// Mark firmware boot successful and stop rollback on reset.
193 /// 172 pub fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
194 /// # Safety 173 self.state.mark_booted()
195 ///
196 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being written to.
197 pub fn mark_booted(&mut self, aligned: &mut [u8]) -> Result<(), FirmwareUpdaterError> {
198 assert_eq!(aligned.len(), STATE::WRITE_SIZE);
199 self.set_magic(aligned, BOOT_MAGIC)
200 }
201
202 fn set_magic(&mut self, aligned: &mut [u8], magic: u8) -> Result<(), FirmwareUpdaterError> {
203 self.state.read(0, aligned)?;
204
205 if aligned.iter().any(|&b| b != magic) {
206 // Read progress validity
207 self.state.read(STATE::WRITE_SIZE as u32, aligned)?;
208
209 if aligned.iter().any(|&b| b != STATE_ERASE_VALUE) {
210 // The current progress validity marker is invalid
211 } else {
212 // Invalidate progress
213 aligned.fill(!STATE_ERASE_VALUE);
214 self.state.write(STATE::WRITE_SIZE as u32, aligned)?;
215 }
216
217 // Clear magic and progress
218 self.state.erase(0, self.state.capacity() as u32)?;
219
220 // Set magic
221 aligned.fill(magic);
222 self.state.write(0, aligned)?;
223 }
224 Ok(())
225 } 174 }
226 175
227 /// Write data to a flash page. 176 /// Write data to a flash page.
@@ -231,15 +180,9 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
231 /// # Safety 180 /// # Safety
232 /// 181 ///
233 /// Failing to meet alignment and size requirements may result in a panic. 182 /// Failing to meet alignment and size requirements may result in a panic.
234 pub fn write_firmware( 183 pub fn write_firmware(&mut self, offset: usize, data: &[u8]) -> Result<(), FirmwareUpdaterError> {
235 &mut self,
236 aligned: &mut [u8],
237 offset: usize,
238 data: &[u8],
239 ) -> Result<(), FirmwareUpdaterError> {
240 assert!(data.len() >= DFU::ERASE_SIZE); 184 assert!(data.len() >= DFU::ERASE_SIZE);
241 assert_eq!(aligned.len(), STATE::WRITE_SIZE); 185 self.state.verify_booted()?;
242 self.verify_booted(aligned)?;
243 186
244 self.dfu.erase(offset as u32, (offset + data.len()) as u32)?; 187 self.dfu.erase(offset as u32, (offset + data.len()) as u32)?;
245 188
@@ -253,16 +196,91 @@ impl<DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<DFU, STATE> {
253 /// 196 ///
254 /// Using this instead of `write_firmware` allows for an optimized API in 197 /// Using this instead of `write_firmware` allows for an optimized API in
255 /// exchange for added complexity. 198 /// exchange for added complexity.
199 pub fn prepare_update(&mut self) -> Result<&mut DFU, FirmwareUpdaterError> {
200 self.state.verify_booted()?;
201 self.dfu.erase(0, self.dfu.capacity() as u32)?;
202
203 Ok(&mut self.dfu)
204 }
205}
206
207/// Manages the state partition of the firmware update.
208///
209/// Can be used standalone for more fine grained control, or as part of the updater.
210pub struct BlockingFirmwareState<'d, STATE> {
211 state: STATE,
212 aligned: &'d mut [u8],
213}
214
215impl<'d, STATE: NorFlash> BlockingFirmwareState<'d, STATE> {
216 /// Create a firmware state instance with a buffer for magic content and state partition.
256 /// 217 ///
257 /// # Safety 218 /// # Safety
258 /// 219 ///
259 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being written to. 220 /// The `aligned` buffer must have a size of STATE::WRITE_SIZE, and follow the alignment rules for the flash being read from
260 pub fn prepare_update(&mut self, aligned: &mut [u8]) -> Result<&mut DFU, FirmwareUpdaterError> { 221 /// and written to.
222 pub fn new(state: STATE, aligned: &'d mut [u8]) -> Self {
261 assert_eq!(aligned.len(), STATE::WRITE_SIZE); 223 assert_eq!(aligned.len(), STATE::WRITE_SIZE);
262 self.verify_booted(aligned)?; 224 Self { state, aligned }
263 self.dfu.erase(0, self.dfu.capacity() as u32)?; 225 }
264 226
265 Ok(&mut self.dfu) 227 // Make sure we are running a booted firmware to avoid reverting to a bad state.
228 fn verify_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
229 if self.get_state()? == State::Boot {
230 Ok(())
231 } else {
232 Err(FirmwareUpdaterError::BadState)
233 }
234 }
235
236 /// Obtain the current state.
237 ///
238 /// This is useful to check if the bootloader has just done a swap, in order
239 /// to do verifications and self-tests of the new image before calling
240 /// `mark_booted`.
241 pub fn get_state(&mut self) -> Result<State, FirmwareUpdaterError> {
242 self.state.read(0, &mut self.aligned)?;
243
244 if !self.aligned.iter().any(|&b| b != SWAP_MAGIC) {
245 Ok(State::Swap)
246 } else {
247 Ok(State::Boot)
248 }
249 }
250
251 /// Mark to trigger firmware swap on next boot.
252 pub fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> {
253 self.set_magic(SWAP_MAGIC)
254 }
255
256 /// Mark firmware boot successful and stop rollback on reset.
257 pub fn mark_booted(&mut self) -> Result<(), FirmwareUpdaterError> {
258 self.set_magic(BOOT_MAGIC)
259 }
260
261 fn set_magic(&mut self, magic: u8) -> Result<(), FirmwareUpdaterError> {
262 self.state.read(0, &mut self.aligned)?;
263
264 if self.aligned.iter().any(|&b| b != magic) {
265 // Read progress validity
266 self.state.read(STATE::WRITE_SIZE as u32, &mut self.aligned)?;
267
268 if self.aligned.iter().any(|&b| b != STATE_ERASE_VALUE) {
269 // The current progress validity marker is invalid
270 } else {
271 // Invalidate progress
272 self.aligned.fill(!STATE_ERASE_VALUE);
273 self.state.write(STATE::WRITE_SIZE as u32, &self.aligned)?;
274 }
275
276 // Clear magic and progress
277 self.state.erase(0, self.state.capacity() as u32)?;
278
279 // Set magic
280 self.aligned.fill(magic);
281 self.state.write(0, &self.aligned)?;
282 }
283 Ok(())
266 } 284 }
267} 285}
268 286
@@ -283,14 +301,14 @@ mod tests {
283 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 4096, 8>::default())); 301 let flash = Mutex::<NoopRawMutex, _>::new(RefCell::new(MemFlash::<131072, 4096, 8>::default()));
284 let state = BlockingPartition::new(&flash, 0, 4096); 302 let state = BlockingPartition::new(&flash, 0, 4096);
285 let dfu = BlockingPartition::new(&flash, 65536, 65536); 303 let dfu = BlockingPartition::new(&flash, 65536, 65536);
304 let mut aligned = [0; 8];
286 305
287 let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66]; 306 let update = [0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66];
288 let mut to_write = [0; 4096]; 307 let mut to_write = [0; 4096];
289 to_write[..7].copy_from_slice(update.as_slice()); 308 to_write[..7].copy_from_slice(update.as_slice());
290 309
291 let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }); 310 let mut updater = BlockingFirmwareUpdater::new(FirmwareUpdaterConfig { dfu, state }, &mut aligned);
292 let mut aligned = [0; 8]; 311 updater.write_firmware(0, to_write.as_slice()).unwrap();
293 updater.write_firmware(&mut aligned, 0, to_write.as_slice()).unwrap();
294 let mut chunk_buf = [0; 2]; 312 let mut chunk_buf = [0; 2];
295 let mut hash = [0; 20]; 313 let mut hash = [0; 20];
296 updater 314 updater