diff --git a/ci.sh b/ci.sh index 94bcc75ed..d21c1c97b 100755 --- a/ci.sh +++ b/ci.sh @@ -282,6 +282,7 @@ cargo batch \ --- build --release --manifest-path examples/boot/bootloader/rp/Cargo.toml --target thumbv6m-none-eabi \ --- build --release --manifest-path examples/boot/bootloader/stm32/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32l496zg \ --- build --release --manifest-path examples/boot/bootloader/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wb55rg \ + --- build --release --manifest-path examples/boot/bootloader/stm32wb-dfu/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32wb55rg,verify \ --- build --release --manifest-path examples/boot/bootloader/stm32-dual-bank/Cargo.toml --target thumbv7em-none-eabi --features embassy-stm32/stm32h743zi \ --- build --release --manifest-path examples/wasm/Cargo.toml --target wasm32-unknown-unknown --artifact-dir out/examples/wasm \ --- build --release --manifest-path tests/stm32/Cargo.toml --target thumbv7m-none-eabi --features stm32f103c8 --artifact-dir out/tests/stm32f103c8 \ diff --git a/embassy-boot/src/firmware_updater/asynch.rs b/embassy-boot/src/firmware_updater/asynch.rs index 0dc09e18d..66e311e38 100644 --- a/embassy-boot/src/firmware_updater/asynch.rs +++ b/embassy-boot/src/firmware_updater/asynch.rs @@ -161,6 +161,17 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> FirmwareUpdater<'d, DFU, STATE> { Ok(()) } + /// Read a slice of data from the DFU storage peripheral, starting the read + /// operation at the given address offset, and reading `buf.len()` bytes. + /// + /// # Errors + /// + /// Returns an error if the arguments are not aligned or out of bounds. + pub async fn read_dfu(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), FirmwareUpdaterError> { + self.dfu.read(offset, buf).await?; + Ok(()) + } + /// Mark to trigger firmware swap on next boot. #[cfg(not(feature = "_verify"))] pub async fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> { diff --git a/embassy-boot/src/firmware_updater/blocking.rs b/embassy-boot/src/firmware_updater/blocking.rs index 08062b0d0..0fedac1ea 100644 --- a/embassy-boot/src/firmware_updater/blocking.rs +++ b/embassy-boot/src/firmware_updater/blocking.rs @@ -196,6 +196,17 @@ impl<'d, DFU: NorFlash, STATE: NorFlash> BlockingFirmwareUpdater<'d, DFU, STATE> Ok(()) } + /// Read a slice of data from the DFU storage peripheral, starting the read + /// operation at the given address offset, and reading `buf.len()` bytes. + /// + /// # Errors + /// + /// Returns an error if the arguments are not aligned or out of bounds. + pub fn read_dfu(&mut self, offset: u32, buf: &mut [u8]) -> Result<(), FirmwareUpdaterError> { + self.dfu.read(offset, buf)?; + Ok(()) + } + /// Mark to trigger firmware swap on next boot. #[cfg(not(feature = "_verify"))] pub fn mark_updated(&mut self) -> Result<(), FirmwareUpdaterError> { diff --git a/embassy-usb-dfu/Cargo.toml b/embassy-usb-dfu/Cargo.toml index ca108c1a2..8b2467bca 100644 --- a/embassy-usb-dfu/Cargo.toml +++ b/embassy-usb-dfu/Cargo.toml @@ -43,3 +43,8 @@ esp32c3-hal = { version = "0.13.0", optional = true, default-features = false } dfu = [] application = [] defmt = ["dep:defmt", "embassy-boot/defmt", "embassy-usb/defmt"] +ed25519-dalek = ["embassy-boot/ed25519-dalek", "_verify"] +ed25519-salty = ["embassy-boot/ed25519-salty", "_verify"] + +# Internal features +_verify = [] diff --git a/embassy-usb-dfu/README.md b/embassy-usb-dfu/README.md index bdd5b033a..a81b98279 100644 --- a/embassy-usb-dfu/README.md +++ b/embassy-usb-dfu/README.md @@ -4,3 +4,9 @@ An implementation of the USB DFU 1.1 protocol using embassy-boot. It has 2 compo * DFU protocol mode, enabled by the `dfu` feature. This mode corresponds to the transfer phase DFU protocol described by the USB IF. It supports DFU_DNLOAD requests if marked by the user, and will automatically reset the chip once a DFU transaction has been completed. It also responds to DFU_GETSTATUS, DFU_GETSTATE, DFU_ABORT, and DFU_CLRSTATUS with no user intervention. * DFU runtime mode, enabled by the `application feature`. This mode allows users to expose a DFU interface on their USB device, informing the host of the capability to DFU over USB, and allowing the host to reset the device into its bootloader to complete a DFU operation. Supports DFU_GETSTATUS and DFU_DETACH. When detach/reset is seen by the device as described by the standard, will write a new DFU magic number into the bootloader state in flash, and reset the system. + +## Verification + +Embassy-boot provides functionality to verify that an update binary has been correctly signed using ed25519 as described in https://embassy.dev/book/#_verification. Even though the linked procedure describes the signature being concatenated to the end of the update binary, embassy-boot does not force this and is flexible in terms of how the signature for a binary is distributed. The current implementation in embassy-usb-dfu does however assume that the signature is 64 bytes long and concatenated to the end of the update binary since this is the simplest way to make it work with the usb-dfu mechanism. I.e. embassy-usb-dfu does not currently offer the same flexibility as embassy-boot. + +To enable verification, you need to enable either the `ed25519-dalek` or the `ed25519-salty` feature with `ed25519-salty` being recommended. diff --git a/embassy-usb-dfu/src/dfu.rs b/embassy-usb-dfu/src/dfu.rs index 0f39d906b..9a2f125fb 100644 --- a/embassy-usb-dfu/src/dfu.rs +++ b/embassy-usb-dfu/src/dfu.rs @@ -19,11 +19,19 @@ pub struct Control<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_S offset: usize, buf: AlignedBuffer, reset: RST, + + #[cfg(feature = "_verify")] + public_key: &'static [u8; 32], } impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Control<'d, DFU, STATE, RST, BLOCK_SIZE> { /// Create a new DFU instance to handle DFU transfers. - pub fn new(updater: BlockingFirmwareUpdater<'d, DFU, STATE>, attrs: DfuAttributes, reset: RST) -> Self { + pub fn new( + updater: BlockingFirmwareUpdater<'d, DFU, STATE>, + attrs: DfuAttributes, + reset: RST, + #[cfg(feature = "_verify")] public_key: &'static [u8; 32], + ) -> Self { Self { updater, attrs, @@ -32,6 +40,9 @@ impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Co offset: 0, buf: AlignedBuffer([0; BLOCK_SIZE]), reset, + + #[cfg(feature = "_verify")] + public_key, } } @@ -102,7 +113,23 @@ impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Ha if final_transfer { debug!("Receiving final transfer"); - match self.updater.mark_updated() { + #[cfg(feature = "_verify")] + let update_res: Result<(), FirmwareUpdaterError> = { + const SIGNATURE_LEN: usize = 64; + + let mut signature = [0; SIGNATURE_LEN]; + let update_len = (self.offset - SIGNATURE_LEN) as u32; + + self.updater.read_dfu(update_len, &mut signature).and_then(|_| { + self.updater + .verify_and_mark_updated(self.public_key, &signature, update_len) + }) + }; + + #[cfg(not(feature = "_verify"))] + let update_res = self.updater.mark_updated(); + + match update_res { Ok(_) => { self.status = Status::Ok; self.state = State::ManifestSync; @@ -168,7 +195,7 @@ impl<'d, DFU: NorFlash, STATE: NorFlash, RST: Reset, const BLOCK_SIZE: usize> Ha Some(InResponse::Accepted(&buf[0..1])) } Ok(Request::Upload) if self.attrs.contains(DfuAttributes::CAN_UPLOAD) => { - //TODO: FirmwareUpdater does not provide a way of reading the active partition, can't upload. + //TODO: FirmwareUpdater provides a way of reading the active partition so we could in theory add functionality to upload firmware. Some(InResponse::Rejected) } _ => None, diff --git a/examples/boot/application/stm32wb-dfu/memory.x b/examples/boot/application/stm32wb-dfu/memory.x index ff1b800d2..f1e6b053c 100644 --- a/examples/boot/application/stm32wb-dfu/memory.x +++ b/examples/boot/application/stm32wb-dfu/memory.x @@ -1,10 +1,10 @@ MEMORY { /* NOTE 1 K = 1 KiBi = 1024 bytes */ - BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 24K - BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - FLASH : ORIGIN = 0x08008000, LENGTH = 128K - DFU : ORIGIN = 0x08028000, LENGTH = 132K + BOOTLOADER : ORIGIN = 0x08000000, LENGTH = 48K + BOOTLOADER_STATE : ORIGIN = 0x0800C000, LENGTH = 4K + FLASH : ORIGIN = 0x0800D000, LENGTH = 120K + DFU : ORIGIN = 0x0802B000, LENGTH = 120K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 32K } diff --git a/examples/boot/application/stm32wb-dfu/secrets/key.sec b/examples/boot/application/stm32wb-dfu/secrets/key.sec new file mode 100644 index 000000000..52e7f125b --- /dev/null +++ b/examples/boot/application/stm32wb-dfu/secrets/key.sec @@ -0,0 +1,2 @@ +untrusted comment: signify secret key +RWRCSwAAAAATdHQF3B4jEIoNZrjADRp2LbjJjNdNNzKwTCe4IB6mDNq96pe53nbNxwbdCc/T4hrz7W+Kx1MwrZ0Yz5xebSK5Z0Kh/3Cdf039U5f+eoTDS2fIGbohyUbrtwKzjyE0qXI= diff --git a/examples/boot/bootloader/stm32wb-dfu/Cargo.toml b/examples/boot/bootloader/stm32wb-dfu/Cargo.toml index 738afb6ec..0bb93b12e 100644 --- a/examples/boot/bootloader/stm32wb-dfu/Cargo.toml +++ b/examples/boot/bootloader/stm32wb-dfu/Cargo.toml @@ -30,6 +30,7 @@ defmt = [ "embassy-usb/defmt", "embassy-usb-dfu/defmt" ] +verify = ["embassy-usb-dfu/ed25519-salty"] [profile.dev] debug = 2 diff --git a/examples/boot/bootloader/stm32wb-dfu/README.md b/examples/boot/bootloader/stm32wb-dfu/README.md index 3c5f268a0..99a7002c4 100644 --- a/examples/boot/bootloader/stm32wb-dfu/README.md +++ b/examples/boot/bootloader/stm32wb-dfu/README.md @@ -28,6 +28,32 @@ cargo objcopy --release -- -O binary fw.bin dfu-util -d c0de:cafe -w -D fw.bin ``` +### 3. Sign Updates Before Flashing (Optional) + +Currently, embassy-usb-dfu only supports a limited implementation of the generic support for ed25519-based update verfication in embassy-boot. This implementation assumes that a signature is simply concatenated to the end of an update binary. For more details, please see https://embassy.dev/book/#_verification and/or refer to the documentation for embassy-boot-dfu. + +To sign (and then verify) application updates, you will first need to generate a key pair: + +``` +signify-openbsd -G -n -p secrets/key.pub -s secrets/key.sec +tail -n1 secrets/key.pub | base64 -d -i - | dd ibs=10 skip=1 > secrets/key.pub.short +``` + +Then you will need to sign all you binaries with the private key: + +``` +cargo objcopy --release -- -O binary fw.bin +shasum -a 512 -b fw.bin | head -c128 | xxd -p -r > target/fw-hash.txt +signify-openbsd -S -s secrets/key.sec -m target/fw-hash.txt -x target/fw-hash.sig +cp fw.bin fw-signed.bin +tail -n1 target/fw-hash.sig | base64 -d -i - | dd ibs=10 skip=1 >> fw-signed.bin +dfu-util -d c0de:cafe -w -D fw-signed.bin +``` + +Finally, as shown in this example with the `verify` feature flag enabled, you then need to embed the public key into your bootloader so that it can verify update signatures. + +N.B. Please note that the exact steps above are NOT a good example of how to manage your keys securely. In a production environment, you should take great care to ensure that (at least the private key) is protected and not leaked into your version control system. + ## Troubleshooting - Make sure your device is in DFU mode before flashing diff --git a/examples/boot/bootloader/stm32wb-dfu/memory.x b/examples/boot/bootloader/stm32wb-dfu/memory.x index 858062631..77c4d2ee2 100644 --- a/examples/boot/bootloader/stm32wb-dfu/memory.x +++ b/examples/boot/bootloader/stm32wb-dfu/memory.x @@ -1,10 +1,10 @@ MEMORY { /* NOTE 1 K = 1 KiBi = 1024 bytes */ - FLASH : ORIGIN = 0x08000000, LENGTH = 24K - BOOTLOADER_STATE : ORIGIN = 0x08006000, LENGTH = 4K - ACTIVE : ORIGIN = 0x08008000, LENGTH = 128K - DFU : ORIGIN = 0x08028000, LENGTH = 132K + FLASH : ORIGIN = 0x08000000, LENGTH = 48K + BOOTLOADER_STATE : ORIGIN = 0x0800C000, LENGTH = 4K + ACTIVE : ORIGIN = 0x0800D000, LENGTH = 120K + DFU : ORIGIN = 0x0802B000, LENGTH = 120K RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 16K } diff --git a/examples/boot/bootloader/stm32wb-dfu/secrets/key.pub.short b/examples/boot/bootloader/stm32wb-dfu/secrets/key.pub.short new file mode 100644 index 000000000..7a4de8585 --- /dev/null +++ b/examples/boot/bootloader/stm32wb-dfu/secrets/key.pub.short @@ -0,0 +1 @@ +gBpMSzKg!F!4r \ No newline at end of file diff --git a/examples/boot/bootloader/stm32wb-dfu/src/main.rs b/examples/boot/bootloader/stm32wb-dfu/src/main.rs index 0b643079f..107f243fd 100644 --- a/examples/boot/bootloader/stm32wb-dfu/src/main.rs +++ b/examples/boot/bootloader/stm32wb-dfu/src/main.rs @@ -25,6 +25,12 @@ bind_interrupts!(struct Irqs { // N.B. update to a custom GUID for your own device! const DEVICE_INTERFACE_GUIDS: &[&str] = &["{EAA9A5DC-30BA-44BC-9232-606CDC875321}"]; +// This is a randomly generated example key. +// +// N.B. Please replace with your own! +#[cfg(feature = "verify")] +static PUBLIC_SIGNING_KEY: &[u8; 32] = include_bytes!("../secrets/key.pub.short"); + #[entry] fn main() -> ! { let mut config = embassy_stm32::Config::default(); @@ -57,7 +63,13 @@ fn main() -> ! { let mut config_descriptor = [0; 256]; let mut bos_descriptor = [0; 256]; let mut control_buf = [0; 4096]; + + #[cfg(not(feature = "verify"))] let mut state = Control::new(updater, DfuAttributes::CAN_DOWNLOAD, ResetImmediate); + + #[cfg(feature = "verify")] + let mut state = Control::new(updater, DfuAttributes::CAN_DOWNLOAD, ResetImmediate, PUBLIC_SIGNING_KEY); + let mut builder = Builder::new( driver, config,