Skip to main content

hazard3_boot/
lib.rs

1#![no_std]
2#![allow(async_fn_in_trait)]
3#![allow(unsafe_op_in_unsafe_fn)]
4#![warn(missing_docs)]
5#![doc = include_str!("../README.md")]
6
7//! ## Feature flags
8#![doc = document_features::document_features!(feature_label = r#"<span class="stab portability"><code>{feature}</code></span>"#)]
9
10mod fmt;
11
12mod boot_loader;
13mod firmware_updater;
14#[cfg(test)]
15mod mem_flash;
16#[cfg(test)]
17mod test_flash;
18mod verification;
19
20// The expected value of the flash after an erase
21// TODO: Use the value provided by NorFlash when available
22#[cfg(not(feature = "flash-erase-zero"))]
23pub(crate) const STATE_ERASE_VALUE: u8 = 0xFF;
24#[cfg(feature = "flash-erase-zero")]
25pub(crate) const STATE_ERASE_VALUE: u8 = 0x00;
26
27pub use boot_loader::{BootError, BootLoader, BootLoaderConfig};
28pub use firmware_updater::{
29    BlockingFirmwareState, BlockingFirmwareUpdater, FirmwareState, FirmwareUpdater, FirmwareUpdaterConfig,
30    FirmwareUpdaterError,
31};
32pub use verification::{Digest, VerifyingKey};
33
34pub(crate) const REVERT_MAGIC: u8 = 0xC0;
35pub(crate) const BOOT_MAGIC: u8 = 0xD0;
36pub(crate) const SWAP_MAGIC: u8 = 0xF0;
37pub(crate) const DFU_DETACH_MAGIC: u8 = 0xE0;
38
39/// The state of the bootloader after running prepare.
40#[derive(PartialEq, Eq, Debug)]
41#[cfg_attr(feature = "defmt", derive(defmt::Format))]
42pub enum State {
43    /// Bootloader is ready to boot the active partition.
44    Boot,
45    /// Bootloader has swapped the active partition with the dfu partition and will attempt boot.
46    Swap,
47    /// Bootloader rejected an update or reverted a failed trial and will boot the previous image.
48    Revert,
49    /// Application has received a request to reboot into DFU mode to apply an update.
50    DfuDetach,
51}
52
53impl<T> From<T> for State
54where
55    T: AsRef<[u8]>,
56{
57    fn from(magic: T) -> State {
58        let magic = magic.as_ref();
59        if !magic.iter().any(|&b| b != SWAP_MAGIC) {
60            State::Swap
61        } else if !magic.iter().any(|&b| b != REVERT_MAGIC) {
62            State::Revert
63        } else if !magic.iter().any(|&b| b != DFU_DETACH_MAGIC) {
64            State::DfuDetach
65        } else {
66            State::Boot
67        }
68    }
69}
70
71/// Buffer aligned to 32 byte boundary, largest known alignment requirement for hazard3-boot.
72#[repr(align(32))]
73pub struct AlignedBuffer<const N: usize>(pub [u8; N]);
74
75impl<const N: usize> AsRef<[u8]> for AlignedBuffer<N> {
76    fn as_ref(&self) -> &[u8] {
77        &self.0
78    }
79}
80
81impl<const N: usize> AsMut<[u8]> for AlignedBuffer<N> {
82    fn as_mut(&mut self) -> &mut [u8] {
83        &mut self.0
84    }
85}
86
87#[cfg(test)]
88mod tests {
89    #![allow(unused_imports)]
90
91    extern crate std;
92
93    use embedded_storage::nor_flash::{NorFlash, ReadNorFlash};
94    use embedded_storage_async::nor_flash::NorFlash as AsyncNorFlash;
95    use hazard3_futures::block_on;
96
97    use super::*;
98    use crate::boot_loader::BootLoaderConfig;
99    use crate::firmware_updater::FirmwareUpdaterConfig;
100    use crate::mem_flash::MemFlash;
101    use crate::test_flash::{AsyncTestFlash, BlockingTestFlash};
102    use crate::verification::VerifyingKey;
103
104    /*
105    #[test]
106    fn test_bad_magic() {
107        let mut flash = MemFlash([0xff; 131072]);
108        let mut flash = SingleFlashConfig::new(&mut flash);
109
110        let mut bootloader = BootLoader::<4096>::new(ACTIVE, DFU, STATE);
111
112        assert_eq!(
113            bootloader.prepare_boot(&mut flash),
114            Err(BootError::BadMagic)
115        );
116    }
117    */
118
119    #[test]
120    fn test_boot_state() {
121        let flash = BlockingTestFlash::new(BootLoaderConfig {
122            active: MemFlash::<57344, 4096, 4>::default(),
123            dfu: MemFlash::<61440, 4096, 4>::default(),
124            state: MemFlash::<4096, 4096, 4>::default(),
125        });
126
127        flash.state().write(0, &[BOOT_MAGIC; 4]).unwrap();
128
129        let mut bootloader = BootLoader::new(BootLoaderConfig {
130            active: flash.active(),
131            dfu: flash.dfu(),
132            state: flash.state(),
133        });
134
135        let mut page = [0; 4096];
136        assert_eq!(State::Boot, bootloader.prepare_boot(&mut page).unwrap());
137    }
138
139    #[test]
140    fn test_swap_state() {
141        // The flashes and buffers used here are large, run on a thread with a bigger stack.
142        std::thread::Builder::new()
143            .stack_size(16 * 1024 * 1024)
144            .spawn(test_swap_state_inner)
145            .unwrap()
146            .join()
147            .unwrap();
148    }
149
150    fn test_swap_state_inner() {
151        const FIRMWARE_SIZE: usize = 57344;
152        let flash = AsyncTestFlash::new(BootLoaderConfig {
153            active: MemFlash::<FIRMWARE_SIZE, 4096, 4>::default(),
154            dfu: MemFlash::<61440, 4096, 4>::default(),
155            state: MemFlash::<4096, 4096, 4>::default(),
156        });
157
158        const ORIGINAL: [u8; FIRMWARE_SIZE] = [0x55; FIRMWARE_SIZE];
159        const UPDATE: [u8; FIRMWARE_SIZE] = [0xAA; FIRMWARE_SIZE];
160        let mut aligned = [0; 4];
161
162        block_on(flash.active().erase(0, ORIGINAL.len() as u32)).unwrap();
163        block_on(flash.active().write(0, &ORIGINAL)).unwrap();
164
165        let mut updater = FirmwareUpdater::new(
166            FirmwareUpdaterConfig {
167                dfu: flash.dfu(),
168                state: flash.state(),
169            },
170            &mut aligned,
171        );
172        block_on(updater.write_firmware(0, &UPDATE)).unwrap();
173        block_on(updater.mark_updated()).unwrap();
174
175        // Writing after marking updated is not allowed until marked as booted.
176        let res: Result<(), FirmwareUpdaterError> = block_on(updater.write_firmware(0, &UPDATE));
177        assert!(matches!(res, Err::<(), _>(FirmwareUpdaterError::BadState)));
178
179        let flash = flash.into_blocking();
180        let mut bootloader = BootLoader::new(BootLoaderConfig {
181            active: flash.active(),
182            dfu: flash.dfu(),
183            state: flash.state(),
184        });
185
186        let mut page = [0; 1024];
187        assert_eq!(State::Swap, bootloader.prepare_boot(&mut page).unwrap());
188
189        let mut read_buf = [0; FIRMWARE_SIZE];
190        flash.active().read(0, &mut read_buf).unwrap();
191        assert_eq!(UPDATE, read_buf);
192        // First DFU page is untouched
193        flash.dfu().read(4096, &mut read_buf).unwrap();
194        assert_eq!(ORIGINAL, read_buf);
195
196        // Running again should cause a revert
197        assert_eq!(State::Swap, bootloader.prepare_boot(&mut page).unwrap());
198
199        // Next time we know it was reverted
200        assert_eq!(State::Revert, bootloader.prepare_boot(&mut page).unwrap());
201
202        let mut read_buf = [0; FIRMWARE_SIZE];
203        flash.active().read(0, &mut read_buf).unwrap();
204        assert_eq!(ORIGINAL, read_buf);
205        // Last DFU page is untouched
206        flash.dfu().read(0, &mut read_buf).unwrap();
207        assert_eq!(UPDATE, read_buf);
208
209        // Mark as booted
210        let flash = flash.into_async();
211        let mut updater = FirmwareUpdater::new(
212            FirmwareUpdaterConfig {
213                dfu: flash.dfu(),
214                state: flash.state(),
215            },
216            &mut aligned,
217        );
218        block_on(updater.mark_booted()).unwrap();
219
220        let flash = flash.into_blocking();
221        let mut bootloader = BootLoader::new(BootLoaderConfig {
222            active: flash.active(),
223            dfu: flash.dfu(),
224            state: flash.state(),
225        });
226        assert_eq!(State::Boot, bootloader.prepare_boot(&mut page).unwrap());
227    }
228
229    #[test]
230    fn test_swap_state_active_page_biggest() {
231        const FIRMWARE_SIZE: usize = 12288;
232        let flash = AsyncTestFlash::new(BootLoaderConfig {
233            active: MemFlash::<12288, 4096, 8>::random(),
234            dfu: MemFlash::<16384, 2048, 8>::random(),
235            state: MemFlash::<2048, 128, 4>::random(),
236        });
237
238        const ORIGINAL: [u8; FIRMWARE_SIZE] = [0x55; FIRMWARE_SIZE];
239        const UPDATE: [u8; FIRMWARE_SIZE] = [0xAA; FIRMWARE_SIZE];
240        let mut aligned = [0; 4];
241
242        block_on(flash.active().erase(0, ORIGINAL.len() as u32)).unwrap();
243        block_on(flash.active().write(0, &ORIGINAL)).unwrap();
244
245        let mut updater = FirmwareUpdater::new(
246            FirmwareUpdaterConfig {
247                dfu: flash.dfu(),
248                state: flash.state(),
249            },
250            &mut aligned,
251        );
252        block_on(updater.write_firmware(0, &UPDATE)).unwrap();
253        block_on(updater.mark_updated()).unwrap();
254
255        let flash = flash.into_blocking();
256        let mut bootloader = BootLoader::new(BootLoaderConfig {
257            active: flash.active(),
258            dfu: flash.dfu(),
259            state: flash.state(),
260        });
261
262        let mut page = [0; 4096];
263        assert_eq!(State::Swap, bootloader.prepare_boot(&mut page).unwrap());
264
265        let mut read_buf = [0; FIRMWARE_SIZE];
266        flash.active().read(0, &mut read_buf).unwrap();
267        assert_eq!(UPDATE, read_buf);
268        // First DFU page is untouched
269        flash.dfu().read(4096, &mut read_buf).unwrap();
270        assert_eq!(ORIGINAL, read_buf);
271    }
272
273    #[test]
274    fn test_swap_state_dfu_page_biggest() {
275        const FIRMWARE_SIZE: usize = 12288;
276        let flash = AsyncTestFlash::new(BootLoaderConfig {
277            active: MemFlash::<FIRMWARE_SIZE, 2048, 4>::random(),
278            dfu: MemFlash::<16384, 4096, 8>::random(),
279            state: MemFlash::<2048, 128, 4>::random(),
280        });
281
282        const ORIGINAL: [u8; FIRMWARE_SIZE] = [0x55; FIRMWARE_SIZE];
283        const UPDATE: [u8; FIRMWARE_SIZE] = [0xAA; FIRMWARE_SIZE];
284        let mut aligned = [0; 4];
285
286        block_on(flash.active().erase(0, ORIGINAL.len() as u32)).unwrap();
287        block_on(flash.active().write(0, &ORIGINAL)).unwrap();
288
289        let mut updater = FirmwareUpdater::new(
290            FirmwareUpdaterConfig {
291                dfu: flash.dfu(),
292                state: flash.state(),
293            },
294            &mut aligned,
295        );
296        block_on(updater.write_firmware(0, &UPDATE)).unwrap();
297        block_on(updater.mark_updated()).unwrap();
298
299        let flash = flash.into_blocking();
300        let mut bootloader = BootLoader::new(BootLoaderConfig {
301            active: flash.active(),
302            dfu: flash.dfu(),
303            state: flash.state(),
304        });
305        let mut page = [0; 4096];
306        assert_eq!(State::Swap, bootloader.prepare_boot(&mut page).unwrap());
307
308        let mut read_buf = [0; FIRMWARE_SIZE];
309        flash.active().read(0, &mut read_buf).unwrap();
310        assert_eq!(UPDATE, read_buf);
311        // First DFU page is untouched
312        flash.dfu().read(4096, &mut read_buf).unwrap();
313        assert_eq!(ORIGINAL, read_buf);
314    }
315
316    #[test]
317    fn test_verify() {
318        use hazard3_crypto::Sha512;
319        use hazard3_crypto::ed25519::{Signature, SigningKey, VerifyingKey};
320        use hazard3_crypto_rand as _;
321        use hazard3_crypto_rustcrypto as _;
322
323        let keypair = SigningKey::generate().unwrap();
324
325        let firmware: &[u8] = b"This are bytes that would otherwise be firmware bytes for DFU.";
326        let mut digest = Sha512::new();
327        digest.update(&firmware);
328        let message = digest.finalize();
329        let signature = keypair.sign(&message).unwrap();
330
331        let public_key = keypair.verifying_key().unwrap();
332
333        // Setup flash
334        let flash = BlockingTestFlash::new(BootLoaderConfig {
335            active: MemFlash::<0, 0, 0>::default(),
336            dfu: MemFlash::<4096, 4096, 4>::default(),
337            state: MemFlash::<4096, 4096, 4>::default(),
338        });
339
340        let firmware_len = firmware.len();
341
342        let mut write_buf = [0; 4096];
343        write_buf[0..firmware_len].copy_from_slice(firmware);
344        flash.dfu().write(0, &write_buf).unwrap();
345
346        // On with the test
347        let flash = flash.into_async();
348        let mut aligned = [0; 4];
349        let mut updater = FirmwareUpdater::new(
350            FirmwareUpdaterConfig {
351                dfu: flash.dfu(),
352                state: flash.state(),
353            },
354            &mut aligned,
355        );
356
357        assert!(
358            block_on(updater.verify_and_mark_updated::<Sha512, VerifyingKey>(
359                &public_key.to_bytes(),
360                &signature.to_bytes(),
361                &mut [0; 64],
362                firmware_len as u32,
363            ))
364            .is_ok()
365        );
366    }
367}