1<!-- 2 - SPDX-License-Identifier: Apache-2.0 3 4 - Copyright (c) 2017-2020 Linaro LTD 5 - Copyright (c) 2017-2019 JUUL Labs 6 - Copyright (c) 2019-2024 Arm Limited 7 8 - Original license: 9 10 - Licensed to the Apache Software Foundation (ASF) under one 11 - or more contributor license agreements. See the NOTICE file 12 - distributed with this work for additional information 13 - regarding copyright ownership. The ASF licenses this file 14 - to you under the Apache License, Version 2.0 (the 15 - "License"); you may not use this file except in compliance 16 - with the License. You may obtain a copy of the License at 17 18 - http://www.apache.org/licenses/LICENSE-2.0 19 20 - Unless required by applicable law or agreed to in writing, 21 - software distributed under the License is distributed on an 22 - "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 23 - KIND, either express or implied. See the License for the 24 - specific language governing permissions and limitations 25 - under the License. 26--> 27 28# Bootloader 29 30## [Summary](#summary) 31 32MCUboot comprises two packages: 33 34* The bootutil library (boot/bootutil) 35* The boot application (each port has its own at boot/<port>) 36 37The bootutil library performs most of the functions of a bootloader. In 38particular, the piece that is missing is the final step of actually jumping to 39the main image. This last step is instead implemented by the boot application. 40Bootloader functionality is separated in this manner to enable unit testing of 41the bootloader. A library can be unit tested, but an application can't. 42Therefore, functionality is delegated to the bootutil library when possible. 43 44## [Limitations](#limitations) 45 46The bootloader currently only supports images with the following 47characteristics: 48* Built to run from flash. 49* Built to run from a fixed location (i.e., not position-independent). 50 51## [Image format](#image-format) 52 53The following definitions describe the image format. 54 55``` c 56#define IMAGE_MAGIC 0x96f3b83d 57 58#define IMAGE_HEADER_SIZE 32 59 60struct image_version { 61 uint8_t iv_major; 62 uint8_t iv_minor; 63 uint16_t iv_revision; 64 uint32_t iv_build_num; 65}; 66 67/** Image header. All fields are in little endian byte order. */ 68struct image_header { 69 uint32_t ih_magic; 70 uint32_t ih_load_addr; 71 uint16_t ih_hdr_size; /* Size of image header (bytes). */ 72 uint16_t ih_protect_tlv_size; /* Size of protected TLV area (bytes). */ 73 uint32_t ih_img_size; /* Does not include header. */ 74 uint32_t ih_flags; /* IMAGE_F_[...]. */ 75 struct image_version ih_ver; 76 uint32_t _pad1; 77}; 78 79#define IMAGE_TLV_INFO_MAGIC 0x6907 80#define IMAGE_TLV_PROT_INFO_MAGIC 0x6908 81 82/** Image TLV header. All fields in little endian. */ 83struct image_tlv_info { 84 uint16_t it_magic; 85 uint16_t it_tlv_tot; /* size of TLV area (including tlv_info header) */ 86}; 87 88/** Image trailer TLV format. All fields in little endian. */ 89struct image_tlv { 90 uint8_t it_type; /* IMAGE_TLV_[...]. */ 91 uint8_t _pad; 92 uint16_t it_len; /* Data length (not including TLV header). */ 93}; 94 95/* 96 * Image header flags. 97 */ 98#define IMAGE_F_PIC 0x00000001 /* Not supported. */ 99#define IMAGE_F_ENCRYPTED_AES128 0x00000004 /* Encrypted using AES128. */ 100#define IMAGE_F_ENCRYPTED_AES256 0x00000008 /* Encrypted using AES256. */ 101#define IMAGE_F_NON_BOOTABLE 0x00000010 /* Split image app. */ 102#define IMAGE_F_RAM_LOAD 0x00000020 103 104/* 105 * Image trailer TLV types. 106 */ 107#define IMAGE_TLV_KEYHASH 0x01 /* hash of the public key */ 108#define IMAGE_TLV_SHA256 0x10 /* SHA256 of image hdr and body */ 109#define IMAGE_TLV_RSA2048_PSS 0x20 /* RSA2048 of hash output */ 110#define IMAGE_TLV_ECDSA224 0x21 /* ECDSA of hash output - Not supported anymore */ 111#define IMAGE_TLV_ECDSA_SIG 0x22 /* ECDSA of hash output */ 112#define IMAGE_TLV_RSA3072_PSS 0x23 /* RSA3072 of hash output */ 113#define IMAGE_TLV_ED25519 0x24 /* ED25519 of hash output */ 114#define IMAGE_TLV_SIG_PURE 0x25 /* If true then any signature found has been 115 calculated over image directly. */ 116#define IMAGE_TLV_ENC_RSA2048 0x30 /* Key encrypted with RSA-OAEP-2048 */ 117#define IMAGE_TLV_ENC_KW 0x31 /* Key encrypted with AES-KW-128 or 118 256 */ 119#define IMAGE_TLV_ENC_EC256 0x32 /* Key encrypted with ECIES-P256 */ 120#define IMAGE_TLV_ENC_X25519 0x33 /* Key encrypted with ECIES-X25519 */ 121#define IMAGE_TLV_DEPENDENCY 0x40 /* Image depends on other image */ 122#define IMAGE_TLV_SEC_CNT 0x50 /* security counter */ 123``` 124 125Optional type-length-value records (TLVs) containing image metadata are placed 126after the end of the image. 127 128The `ih_protect_tlv_size` field indicates the length of the protected TLV area. 129If protected TLVs are present then a TLV info header with magic equal to 130`IMAGE_TLV_PROT_INFO_MAGIC` must be present and the protected TLVs (plus the 131info header itself) have to be included in the hash calculation. Otherwise the 132hash is only calculated over the image header and the image itself. In this 133case the value of the `ih_protect_tlv_size` field is 0. 134 135The `ih_hdr_size` field indicates the length of the header, and therefore the 136offset of the image itself. This field provides for backwards compatibility in 137case of changes to the format of the image header. 138 139## [Flash map](#flash-map) 140 141A device's flash is partitioned according to its _flash map_. At a high 142level, the flash map maps numeric IDs to _flash areas_. A flash area is a 143region of disk with the following properties: 1441. An area can be fully erased without affecting any other areas. 1452. A write to one area does not restrict writes to other areas. 146 147The bootloader uses the following flash area IDs: 148```c 149/* Independent from multiple image boot */ 150#define FLASH_AREA_BOOTLOADER 0 151#define FLASH_AREA_IMAGE_SCRATCH 3 152``` 153```c 154/* If the bootloader is working with the first image */ 155#define FLASH_AREA_IMAGE_PRIMARY 1 156#define FLASH_AREA_IMAGE_SECONDARY 2 157``` 158```c 159/* If the bootloader is working with the second image */ 160#define FLASH_AREA_IMAGE_PRIMARY 5 161#define FLASH_AREA_IMAGE_SECONDARY 6 162``` 163 164The bootloader area contains the bootloader image itself. The other areas are 165described in subsequent sections. The flash could contain multiple executable 166images therefore the flash area IDs of primary and secondary areas are mapped 167based on the number of the active image (on which the bootloader is currently 168working). 169 170## [Image slots](#image-slots) 171 172A portion of the flash memory can be partitioned into multiple image areas, each 173contains two image slots: a primary slot and a secondary slot. 174Normally, the bootloader will only run an image from the primary slot, so 175images must be built such that they can run from that fixed location in flash 176(the exception to this is the [direct-xip](#direct-xip) and the 177[ram-load](#ram-load) upgrade mode). If the bootloader needs to run the 178image resident in the secondary slot, it must copy its contents into the primary 179slot before doing so, either by swapping the two images or by overwriting the 180contents of the primary slot. The bootloader supports either swap- or 181overwrite-based image upgrades, but must be configured at build time to choose 182one of these two strategies. 183 184### [Swap using scratch](#image-swap-using-scratch) 185 186When swap-using-scratch algorithm is used, in addition to the slots of 187image areas, the bootloader requires a scratch area to allow for reliable 188image swapping. The scratch area must have a size 189that is enough to store at least the largest sector that is going to be swapped. 190Many devices have small equally sized flash sectors, eg 4K, while others have 191variable sized sectors where the largest sectors might be 128K or 256K, so the 192scratch must be big enough to store that. The scratch is only ever used when 193swapping firmware, which means only when doing an upgrade. Given that, the main 194reason for using a larger size for the scratch is that flash wear will be more 195evenly distributed, because a single sector would be written twice the number of 196times than using two sectors, for example. To evaluate the ideal size of the 197scratch for your use case the following parameters are relevant: 198 199* the ratio of image size / scratch size 200* the number of erase cycles supported by the flash hardware 201 202The image size is used (instead of slot size) because only the slot's sectors 203that are actually used for storing the image are copied. The image/scratch ratio 204is the number of times the scratch will be erased on every upgrade. The number 205of erase cycles divided by the image/scratch ratio will give you the number of 206times an upgrade can be performed before the device goes out of spec. 207 208``` 209num_upgrades = number_of_erase_cycles / (image_size / scratch_size) 210``` 211 212Let's assume, for example, a device with 10000 erase cycles, an image size of 213150K and a scratch of 4K (usual minimum size of 4K sector devices). This would 214result in a total of: 215 216`10000 / (150 / 4) ~ 267` 217 218Increasing the scratch to 16K would give us: 219 220`10000 / (150 / 16) ~ 1067` 221 222There is no *best* ratio, as the right size is use-case dependent. Factors to 223consider include the number of times a device will be upgraded both in the field 224and during development, as well as any desired safety margin on the 225manufacturer's specified number of erase cycles. In general, using a ratio that 226allows hundreds to thousands of field upgrades in production is recommended. 227 228swap-using scratch algorithm assumes that the primary and the secondary image 229slot areas sizes are equal. 230The maximum image size available for the application 231will be: 232``` 233maximum-image-size = image-slot-size - image-trailer-size 234``` 235 236Where: 237 `image-slot-size` is the size of the image slot. 238 `image-trailer-size` is the size of the image trailer. 239 240### [Swap using offset (without using scratch)](#image-swap-offset-no-scratch) 241 242This algorithm is an alternative to the swap-using-scratch algorithm and an 243enhancement of the swap using move algorithm. 244It uses an additional sector in the secondary slot to make swap possible. 245The algorithm works as follows: 246 247 1. Update image must be placed starting at the second sector in the secondary slot 248 2. Copies the N-th sector from the primary slot to the N-th sector of the 249 secondary slot. 250 3. Copies the (N+1)-th sector from the secondary slot to the N-th sector of the 251 primary slot. 252 4. Repeats steps 2. and 3. until all the slots' sectors are swapped. 253 254This algorithm is designed so that the lower sector of the secondary slot is 255used only for allowing sectors to move down during a swap. Therefore the most 256memory-size-effective slot layout is when the secondary slot is larger than 257the primary slot by exactly one sector, although same-sized slots are allowed 258as well. The algorithm is limited to support sectors of the same sector layout. 259All slot's sectors should be of the same size. This algorithm uses 2 flags per 260sector update rather than the 3 flags used by swap using move, which requires 261a smaller swap status area size. 262 263When using this algorithm the maximum image size available for the application 264will be: 265``` 266maximum-image-size1 = N * slot-sector-size - image-trailer-sectors-size 267``` 268 269Where: 270 `N` is the number of sectors in the primary slot. 271 `image-trailer-sectors-size` is the size of the image trailer rounded up to 272 the total size of sectors its occupied. For instance if the image-trailer-size 273 is equal to 1056 B and the sector size is equal to 1024 B, then 274 `image-trailer-sectors-size` will be equal to 2048 B. 275 276The algorithm does one erase cycle on both the primary and secondary slots 277during each swap. 278 279The algorithm is enabled using the `MCUBOOT_SWAP_USING_OFFSET` option. 280 281### [Swap using move (without using scratch)](#image-swap-no-scratch) 282 283This algorithm is an alternative to the swap-using-scratch algorithm. 284It uses an additional sector in the primary slot to make swap possible. 285The algorithm works as follows: 286 287 1. Moves all sectors of the primary slot up by one sector. 288 Beginning from N=0: 289 2. Copies the N-th sector from the secondary slot to the N-th sector of the 290 primary slot. 291 3. Copies the (N+1)-th sector from the primary slot to the N-th sector of the 292 secondary slot. 293 4. Repeats steps 2. and 3. until all the slots' sectors are swapped. 294 295This algorithm is designed so that the higher sector of the primary slot is 296used only for allowing sectors to move up. Therefore the most 297memory-size-effective slot layout is when the primary slot is larger than 298the secondary slot by exactly one sector plus the size of the swap status area, 299rounded up to the total size of the sectors it occupies, 300although same-sized slots are allowed as well. 301The algorithm is limited to support sectors of the same 302sector layout. All slot's sectors should be of the same size. 303 304When using this algorithm the maximum image size available for the application 305will be: 306``` 307maximum-image-size = (N-1) * slot-sector-size - image-trailer-sectors-size 308``` 309 310Where: 311 `N` is the number of sectors in the primary slot. 312 `image-trailer-sectors-size` is the size of the image trailer rounded up to 313 the total size of sectors its occupied. For instance if the image-trailer-size 314 is equal to 1056 B and the sector size is equal to 1024 B, then 315 `image-trailer-sectors-size` will be equal to 2048 B. 316 317The algorithm does two erase cycles on the primary slot and one on the secondary 318slot during each swap. Assuming that receiving a new image by the DFU 319application requires 1 erase cycle on the secondary slot, this should result in 320leveling the flash wear between the slots. 321 322The algorithm is enabled using the `MCUBOOT_SWAP_USING_MOVE` option. 323 324### [Equal slots (direct-xip)](#direct-xip) 325 326When the direct-xip mode is enabled the active image flag is "moved" between the 327slots during image upgrade and in contrast to the above, the bootloader can 328run an image directly from either the primary or the secondary slot (without 329having to move/copy it into the primary slot). Therefore the image update 330client, which downloads the new images must be aware, which slot contains the 331active image and which acts as a staging area and it is responsible for loading 332the proper images into the proper slot. All this requires that the images be 333built to be executed from the corresponding slot. At boot time the bootloader 334first looks for images in the slots and then inspects the version numbers in the 335image headers. It selects the newest image (with the highest version number) and 336then checks its validity (integrity check, signature verification etc.). If the 337image is invalid MCUboot erases its memory slot and starts to validate the other 338image. After a successful validation of the selected image the bootloader 339chain-loads it. 340 341An additional "revert" mechanism is also supported. For more information, please 342read the [corresponding section](#direct-xip-revert). 343Handling the primary and secondary slots as equals has its drawbacks. Since the 344images are not moved between the slots, the on-the-fly image 345encryption/decryption can't be supported (it only applies to storing the image 346in an external flash on the device, the transport of encrypted image data is 347still feasible). 348 349The overwrite and the direct-xip upgrade strategies are substantially simpler to 350implement than the image swapping strategy, especially since the bootloader must 351work properly even when it is reset during the middle of an image swap. For this 352reason, the rest of the document describes its behavior when configured to swap 353images during an upgrade. 354 355### [RAM loading](#ram-load) 356 357In ram-load mode the slots are equal. Like the direct-xip mode, this mode 358also selects the newest image by reading the image version numbers in the image 359headers. But instead of executing it in place, the newest image is copied to the 360RAM for execution. The load address, the location in RAM where the image is 361copied to, is stored in the image header. The ram-load upgrade mode can be 362useful when there is no internal flash in the SoC, but there is a big enough 363internal RAM to hold the images. Usually in this case the images are stored 364in an external storage device. Execution from external storage has some 365drawbacks (lower execution speed, image is exposed to attacks) therefore the 366image is always copied to the internal RAM before the authentication and 367execution. Ram-load mode requires the image to be built to be executed from 368the RAM address range instead of the storage device address range. If 369ram-load is enabled then platform must define the following parameters: 370 371```c 372#define IMAGE_EXECUTABLE_RAM_START <area_base_addr> 373#define IMAGE_EXECUTABLE_RAM_SIZE <area_size_in_bytes> 374``` 375 376For multiple image load if multiple ram regions are used platform must define 377the `MULTIPLE_EXECUTABLE_RAM_REGIONS` flag instead and implement the following 378function: 379 380```c 381int boot_get_image_exec_ram_info(uint32_t image_id, 382 uint32_t *exec_ram_start, 383 uint32_t *exec_ram_size) 384``` 385 386When ram-load is enabled, the `--load-addr <addr>` option of the `imgtool` 387script must also be used when signing the images. This option set the `RAM_LOAD` 388flag in the image header which indicates that the image should be loaded to the 389RAM and also set the load address in the image header. 390 391When the encryption option is enabled (`MCUBOOT_ENC_IMAGES`) along with ram-load 392the image is checked for encryption. If the image is not encrypted, RAM loading 393happens as described above. If the image is encrypted, it is copied in RAM at 394the provided address and then decrypted. Finally, the decrypted image is 395authenticated in RAM and executed. 396 397## [Boot swap types](#boot-swap-types) 398 399When the device first boots under normal circumstances, there is an up-to-date 400firmware image in each primary slot, which MCUboot can validate and then 401chain-load. In this case, no image swaps are necessary. During device upgrades, 402however, new candidate image(s) is present in the secondary slot(s), which 403MCUboot must swap into the primary slot(s) before booting as discussed above. 404 405Upgrading an old image with a new one by swapping can be a two-step process. In 406this process, MCUboot performs a "test" swap of image data in flash and boots 407the new image or it will be executed during operation. The new image can then 408update the contents of flash at runtime to mark itself "OK", and MCUboot will 409then still choose to run it during the next boot. When this happens, the swap is 410made "permanent". If this doesn't happen, MCUboot will perform a "revert" swap 411during the next boot by swapping the image(s) back into its original location(s) 412, and attempting to boot the old image(s). 413 414Depending on the use case, the first swap can also be made permanent directly. 415In this case, MCUboot will never attempt to revert the images on the next reset. 416 417Test swaps are supported to provide a rollback mechanism to prevent devices 418from becoming "bricked" by bad firmware. If the device crashes immediately 419upon booting a new (bad) image, MCUboot will revert to the old (working) image 420at the next device reset, rather than booting the bad image again. This allows 421device firmware to make test swaps permanent only after performing a self-test 422routine. 423 424On startup, MCUboot inspects the contents of flash to decide for each images 425which of these "swap types" to perform; this decision determines how it 426proceeds. 427 428The possible swap types, and their meanings, are: 429 430- `BOOT_SWAP_TYPE_NONE`: The "usual" or "no upgrade" case; attempt to boot the 431 contents of the primary slot. 432 433- `BOOT_SWAP_TYPE_TEST`: Boot the contents of the secondary slot by swapping 434 images. Unless the swap is made permanent, revert back on the next boot. 435 436- `BOOT_SWAP_TYPE_PERM`: Permanently swap images, and boot the upgraded image 437 firmware. 438 439- `BOOT_SWAP_TYPE_REVERT`: A previous test swap was not made permanent; 440 swap back to the old image whose data are now in the secondary slot. If the 441 old image marks itself "OK" when it boots, the next boot will have swap type 442 `BOOT_SWAP_TYPE_NONE`. 443 444- `BOOT_SWAP_TYPE_FAIL`: Swap failed because image to be run is not valid. 445 446- `BOOT_SWAP_TYPE_PANIC`: Swapping encountered an unrecoverable error. 447 448The "swap type" is a high-level representation of the outcome of the 449boot. Subsequent sections describe how MCUboot determines the swap type from 450the bit-level contents of flash. 451 452### [Revert mechanism in direct-xip mode](#direct-xip-revert) 453 454The direct-xip mode also supports a "revert" mechanism which is the equivalent 455of the swap mode's "revert" swap. When the direct-xip mode is selected it can be 456enabled with the MCUBOOT_DIRECT_XIP_REVERT config option and an image trailer 457must also be added to the signed images (the "--pad" option of the `imgtool` 458script must be used). For more information on this please read the 459[Image Trailer](#image-trailer) section and the [imgtool](imgtool.md) 460documentation. Making the images permanent (marking them as confirmed in 461advance) is also supported just like in swap mode. The individual steps of the 462direct-xip mode's "revert" mechanism are the following: 463 4641. Select the slot which holds the newest potential image. 4652. Was the image previously selected to run (during a previous boot)? 466 + Yes: Did the image mark itself "OK" (was the self-test successful)? 467 + Yes. 468 - Proceed to step 3. 469 + No. 470 - Erase the image from the slot to prevent it from being selected 471 again during the next boot. 472 - Return to step 1 (the bootloader will attempt to select and 473 possibly boot the previous image if there is one). 474 + No. 475 - Mark the image as "selected" (set the copy_done flag in the trailer). 476 - Proceed to step 3. 4773. Proceed to image validation ... 478 479## [Image trailer](#image-trailer) 480 481For the bootloader to be able to determine the current state and what actions 482should be taken during the current boot operation, it uses metadata stored in 483the image flash areas. While swapping, some of this metadata is temporarily 484copied into and out of the scratch area. 485 486This metadata is located at the end of the image flash areas, and is called an 487image trailer. An image trailer has the following structure: 488 489``` 490 0 1 2 3 491 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 492 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 493 ~ ~ 494 ~ Swap status (BOOT_MAX_IMG_SECTORS * min-write-size * 3) ~ 495 ~ ~ 496 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 497 | Encryption key 0 (16 octets) [*] | 498 | | 499 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 500 | 0xff padding as needed | 501 | (BOOT_MAX_ALIGN minus 16 octets from Encryption key 0) [*] | 502 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 503 | Encryption key 1 (16 octets) [*] | 504 | | 505 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 506 | 0xff padding as needed | 507 | (BOOT_MAX_ALIGN minus 16 octets from Encryption key 1) [*] | 508 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 509 | Swap size (4 octets) | 510 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 511 | 0xff padding as needed | 512 | (BOOT_MAX_ALIGN minus 4 octets from Swap size) | 513 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 514 | Swap info | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) | 515 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 516 | Copy done | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) | 517 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 518 | Image OK | 0xff padding (BOOT_MAX_ALIGN minus 1 octet) | 519 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 520 | 0xff padding as needed | 521 | (BOOT_MAX_ALIGN minus 16 octets from MAGIC) | 522 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 523 | MAGIC (16 octets) | 524 | | 525 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 526``` 527 528[*]: Only present if the encryption option is enabled (`MCUBOOT_ENC_IMAGES`). 529 530The offset immediately following such a record represents the start of the next 531flash area. 532 533--- 534***Note*** 535 536*"min-write-size" is a property of the flash hardware. If the hardware* 537*allows individual bytes to be written at arbitrary addresses, then* 538*min-write-size is 1. If the hardware only allows writes at even addresses,* 539*then min-write-size is 2, and so on.* 540 541--- 542 543An image trailer contains the following fields: 544 5451. Swap status: A series of records which records the progress of an image 546 swap. To swap entire images, data are swapped between the two image areas 547 one or more sectors at a time, like this: 548 549 - sector data in the primary slot is copied into scratch, then erased 550 - sector data in the secondary slot is copied into the primary slot, 551 then erased 552 - sector data in scratch is copied into the secondary slot 553 554As it swaps images, the bootloader updates the swap status field in a way that 555allows it to compute how far this swap operation has progressed for each 556sector. The swap status field can thus used to resume a swap operation if the 557bootloader is halted while a swap operation is ongoing and later reset. The 558`BOOT_MAX_IMG_SECTORS` value is the configurable maximum number of sectors 559MCUboot supports for each image; its value defaults to 128, but allows for 560either decreasing this size, to limit RAM usage, or to increase it in devices 561that have massive amounts of Flash or very small sized sectors and thus require 562a bigger configuration to allow for the handling of all slot's sectors. 563The factor of min-write-size is due to the behavior of flash hardware. The factor 564of 3 is explained below. 565 5662. Encryption keys: key-encrypting keys (KEKs). These keys are needed for 567 image encryption and decryption. See the 568 [encrypted images](encrypted_images.md) document for more information. 569 5703. Swap size: When beginning a new swap operation, the total size that needs 571 to be swapped (based on the slot with largest image + TLVs) is written to 572 this location for easier recovery in case of a reset while performing the 573 swap. 574 5754. Swap info: A single byte which encodes the following information: 576 - Swap type: Stored in bits 0-3. Indicating the type of swap operation in 577 progress. When MCUboot resumes an interrupted swap, it uses this field to 578 determine the type of operation to perform. This field contains one of the 579 following values in the table below. 580 - Image number: Stored in bits 4-7. It has always 0 value at single image 581 boot. In case of multi image boot it indicates, which image was swapped when 582 interrupt happened. The same scratch area is used during in case of all 583 image swap operation. Therefore this field is used to determine which image 584 the trailer belongs to if boot status is found on scratch area when the swap 585 operation is resumed. 586 587| Name | Value | 588| ------------------------- | ----- | 589| `BOOT_SWAP_TYPE_TEST` | 2 | 590| `BOOT_SWAP_TYPE_PERM` | 3 | 591| `BOOT_SWAP_TYPE_REVERT` | 4 | 592 593 5945. Copy done: A single byte indicating whether the image in this slot is 595 complete (0x01=done; 0xff=not done). 596 5976. Image OK: A single byte indicating whether the image in this slot has been 598 confirmed as good by the user (0x01=confirmed; 0xff=not confirmed). 599 6007. MAGIC: A 16-byte field identifying the image trailer layout. It may assume 601 distinct values depending on the maximum supported write alignment 602 (`BOOT_MAX_ALIGN`) of the image, as defined by the following construct: 603 604``` c 605union boot_img_magic_t 606{ 607 struct { 608 uint16_t align; 609 uint8_t magic[14]; 610 }; 611 uint8_t val[16]; 612}; 613``` 614 If `BOOT_MAX_ALIGN` is **8 bytes**, then MAGIC contains the following 16 bytes: 615 616``` c 617const union boot_img_magic_t boot_img_magic = { 618 .val = { 619 0x77, 0xc2, 0x95, 0xf3, 620 0x60, 0xd2, 0xef, 0x7f, 621 0x35, 0x52, 0x50, 0x0f, 622 0x2c, 0xb6, 0x79, 0x80 623 } 624}; 625``` 626 627 In case `BOOT_MAX_ALIGN` is defined to any value different than **8**, then the maximum 628 supported write alignment value is encoded in the MAGIC field, followed by a fixed 629 14-byte pattern: 630 631``` c 632const union boot_img_magic_t boot_img_magic = { 633 .align = BOOT_MAX_ALIGN, 634 .magic = { 635 0x2d, 0xe1, 636 0x5d, 0x29, 0x41, 0x0b, 637 0x8d, 0x77, 0x67, 0x9c, 638 0x11, 0x0f, 0x1f, 0x8a 639 } 640}; 641``` 642 643--- 644***Note*** 645Be aware that the image trailers make the ending area of the image slot 646unavailable for carrying the image data. In particular, the swap status size 647could be huge. For example, for 128 slot sectors with a 4-byte alignment, 648it would become 1536 B. 649 650--- 651 652## [Image trailers](#image-trailers) 653 654At startup, the bootloader determines the boot swap type by inspecting the 655image trailers. When using the term "image trailers" what is meant is the 656aggregate information provided by both image slot's trailers. 657 658### [New swaps (non-resumes)](#new-swaps-non-resumes) 659 660For new swaps, MCUboot must inspect a collection of fields to determine which 661swap operation to perform. 662 663The image trailers records are structured around the limitations imposed by 664flash hardware. As a consequence, they do not have a very intuitive design, and 665it is difficult to get a sense of the state of the device just by looking at the 666image trailers. It is better to map all the possible trailer states to the swap 667types described above via a set of tables. These tables are reproduced below. 668 669--- 670***Note*** 671 672*An important caveat about the tables described below is that they must* 673*be evaluated in the order presented here. Lower state numbers must have a* 674*higher priority when testing the image trailers.* 675 676--- 677 678``` 679 State I (swap using offset only) 680 | primary slot | secondary slot | 681 -----------------+--------------+----------------| 682 magic | Any | Good | 683 image-ok | Any | Unset | 684 copy-done | Any | Set | 685 -----------------+--------------+----------------' 686 result: BOOT_SWAP_TYPE_REVERT | 687 -------------------------------------------------' 688 689 State II 690 | primary slot | secondary slot | 691 -----------------+--------------+----------------| 692 magic | Any | Good | 693 image-ok | Any | Unset | 694 copy-done | Any | Any | 695 -----------------+--------------+----------------' 696 result: BOOT_SWAP_TYPE_TEST | 697 -------------------------------------------------' 698 699 700 State III 701 | primary slot | secondary slot | 702 -----------------+--------------+----------------| 703 magic | Any | Good | 704 image-ok | Any | 0x01 | 705 copy-done | Any | Any | 706 -----------------+--------------+----------------' 707 result: BOOT_SWAP_TYPE_PERM | 708 -------------------------------------------------' 709 710 711 State IV 712 | primary slot | secondary slot | 713 -----------------+--------------+----------------| 714 magic | Good | Any | 715 image-ok | 0xff | Any | 716 copy-done | 0x01 | Any | 717 -----------------+--------------+----------------' 718 result: BOOT_SWAP_TYPE_REVERT | 719 -------------------------------------------------' 720``` 721 722Any of the above three states results in MCUboot attempting to swap images. 723 724Otherwise, MCUboot does not attempt to swap images, resulting in one of the 725other three swap types, as illustrated by State IV. 726 727``` 728 State V 729 | primary slot | secondary slot | 730 -----------------+--------------+----------------| 731 magic | Any | Any | 732 image-ok | Any | Any | 733 copy-done | Any | Any | 734 -----------------+--------------+----------------' 735 result: BOOT_SWAP_TYPE_NONE, | 736 BOOT_SWAP_TYPE_FAIL, or | 737 BOOT_SWAP_TYPE_PANIC | 738 -------------------------------------------------' 739``` 740 741In State V, when no errors occur, MCUboot will attempt to boot the contents of 742the primary slot directly, and the result is `BOOT_SWAP_TYPE_NONE`. If the image 743in the primary slot is not valid, the result is `BOOT_SWAP_TYPE_FAIL`. If a 744fatal error occurs during boot, the result is `BOOT_SWAP_TYPE_PANIC`. If the 745result is either `BOOT_SWAP_TYPE_FAIL` or `BOOT_SWAP_TYPE_PANIC`, MCUboot hangs 746rather than booting an invalid or compromised image. 747 748--- 749***Note*** 750 751*An important caveat to the above is the result when a swap is requested* 752*and the image in the secondary slot fails to validate, due to a hashing or* 753*signing error. This state behaves as State IV with the extra action of* 754*marking the image in the primary slot as "OK", to prevent further attempts* 755*to swap.* 756 757--- 758 759### [Resumed swaps](#resumed-swaps) 760 761If MCUboot determines that it is resuming an interrupted swap (i.e., a reset 762occurred mid-swap), it fully determines the operation to resume by reading the 763`swap info` field from the active trailer and extracting the swap type from bits 7640-3. The set of tables in the previous section are not necessary in the resume 765case. 766 767## [High-level operation](#high-level-operation) 768 769With the terms defined, we can now explore the bootloader's operation. First, 770a high-level overview of the boot process is presented. Then, the following 771sections describe each step of the process in more detail. 772 773Procedure: 774 7751. Inspect swap status region; is an interrupted swap being resumed? 776 + Yes: Complete the partial swap operation; skip to step 3. 777 + No: Proceed to step 2. 778 7792. Inspect image trailers; is a swap requested? 780 + Yes: 781 1. Is the requested image valid (integrity and security check)? 782 + Yes. 783 a. Perform swap operation. 784 b. Persist completion of swap procedure to image trailers. 785 c. Proceed to step 3. 786 + No. 787 a. Erase invalid image. 788 b. Persist failure of swap procedure to image trailers. 789 c. Proceed to step 3. 790 791 + No: Proceed to step 3. 792 7933. Boot into image in primary slot. 794 795### [Multiple image boot](#multiple-image-boot) 796 797When the flash contains multiple executable images the bootloader's operation 798is a bit more complex but similar to the previously described procedure with 799one image. Every image can be updated independently therefore the flash is 800partitioned further to arrange two slots for each image. 801``` 802+--------------------+ 803| MCUboot | 804+--------------------+ 805 ~~~~~ <- memory might be not contiguous 806+--------------------+ 807| Image 0 | 808| primary slot | 809+--------------------+ 810| Image 0 | 811| secondary slot | 812+--------------------+ 813 ~~~~~ <- memory might be not contiguous 814+--------------------+ 815| Image N | 816| primary slot | 817+--------------------+ 818| Image N | 819| secondary slot | 820+--------------------+ 821| Scratch | 822+--------------------+ 823``` 824MCUboot is also capable of handling dependencies between images. For example 825if an image needs to be reverted it might be necessary to revert another one too 826(e.g. due to API incompatibilities) or simply to prevent from being updated 827because of an unsatisfied dependency. Therefore all aborted swaps have to be 828completed and all the swap types have to be determined for each image before 829the dependency checks. Dependency handling is described in more detail in a 830following section. The multiple image boot procedure is organized in loops which 831iterate over all the firmware images. The high-level overview of the boot 832process is presented below. 833 834+ Loop 1. Iterate over all images 835 1. Inspect swap status region of current image; is an interrupted swap being 836 resumed? 837 + Yes: 838 + Review the validity of previously determined swap types 839 of other images. 840 + Complete the partial swap operation. 841 + Mark the swap type as `None`. 842 + Skip to next image. 843 + No: Proceed to step 2. 844 845 2. Inspect image trailers in the primary and secondary slot; is an image 846 swap requested? 847 + Yes: Review the validity of previously determined swap types of other 848 images. Is the requested image valid (integrity and security 849 check)? 850 + Yes: 851 + Set the previously determined swap type for the current image. 852 + Skip to next image. 853 + No: 854 + Erase invalid image. 855 + Persist failure of swap procedure to image trailers. 856 + Mark the swap type as `Fail`. 857 + Skip to next image. 858 + No: 859 + Mark the swap type as `None`. 860 + Skip to next image. 861 862+ Loop 2. Iterate over all images 863 1. Does the current image depend on other image(s)? 864 + Yes: Are all the image dependencies satisfied? 865 + Yes: Skip to next image. 866 + No: 867 + Modify swap type depending on what the previous type was. 868 + Restart dependency check from the first image. 869 + No: Skip to next image. 870 871+ Loop 3. Iterate over all images 872 1. Is an image swap requested? 873 + Yes: 874 + Perform image update operation. 875 + Persist completion of swap procedure to image trailers. 876 + Skip to next image. 877 + No: Skip to next image. 878 879+ Loop 4. Iterate over all images 880 1. Validate image in the primary slot (integrity and security check) or 881 at least do a basic sanity check to avoid booting into an empty flash 882 area. 883 884+ Boot into image in the primary slot of the 0th image position\ 885 (other image in the boot chain is started by another image). 886 887### [Multiple image boot for RAM loading and direct-xip](#multiple-image-boot-for-ram-loading-and-direct-xip) 888 889The operation of the bootloader is different when the ram-load or the 890direct-xip strategy is chosen. The flash map is very similar to the swap 891strategy but there is no need for Scratch area. 892 893+ Loop 1. Until all images are loaded and all dependencies are satisfied 894 1. Subloop 1. Iterate over all images 895 + Does any of the slots contain an image? 896 + Yes: 897 + Choose the newer image. 898 + Copy it to RAM in case of ram-load strategy. 899 + Validate the image (integrity and security check). 900 + If validation fails delete the image from flash and try the other 901 slot. (Image must be deleted from RAM too in case of ram-load 902 strategy.) 903 + No: Return with failure. 904 905 2. Subloop 2. Iterate over all images 906 + Does the current image depend on other image(s)? 907 + Yes: Are all the image dependencies satisfied? 908 + Yes: Skip to next image. 909 + No: 910 + Delete the image from RAM in case of ram-load strategy, but 911 do not delete it from flash. 912 + Try to load the image from the other slot. 913 + Restart dependency check from the first image. 914 + No: Skip to next image. 915 916+ Loop 2. Iterate over all images 917 + Increase the security counter if needed. 918 + Do the measured boot and the data sharing if needed. 919 920+ Boot the loaded slot of image 0. 921 922## [Image swapping](#image-swapping) 923 924The bootloader swaps the contents of the two image slots for two reasons: 925 926 * User has issued a "set pending" operation; the image in the secondary slot 927 should be run once (state I) or repeatedly (state II), depending on 928 whether a permanent swap was specified. 929 * Test image rebooted without being confirmed; the bootloader should 930 revert to the original image currently in the secondary slot (state III). 931 932If the image trailers indicates that the image in the secondary slot should be 933run, the bootloader needs to copy it to the primary slot. The image currently 934in the primary slot also needs to be retained in flash so that it can be used 935later. Furthermore, both images need to be recoverable if the bootloader 936resets in the middle of the swap operation. The two images are swapped 937according to the following procedure: 938 9391. Determine if both slots are compatible enough to have their images swapped. 940 To be compatible, both have to have only sectors that can fit into the 941 scratch area and if one of them has larger sectors than the other, it must 942 be able to entirely fit some rounded number of sectors from the other slot. 943 In the next steps we'll use the terminology "region" for the total amount of 944 data copied/erased because this can be any amount of sectors depending on 945 how many the scratch is able to fit for some swap operation. 9462. Iterate the list of region indices in descending order (i.e., starting 947 with the greatest index); only regions that are predetermined to be part of 948 the image are copied; current element = "index". 949 + a. Erase scratch area. 950 + b. Copy secondary_slot[index] to scratch area. 951 - If this is the last region in the slot, scratch area has a temporary 952 status area initialized to store the initial state, because the 953 primary slot's last region will have to be erased. In this case, 954 only the data that was calculated to amount to the image is copied. 955 - Else if this is the first swapped region but not the last region in 956 the slot, initialize the status area in primary slot and copy the 957 full region contents. 958 - Else, copy entire region contents. 959 + c. Write updated swap status (i). 960 + d. Erase secondary_slot[index] 961 + e. Copy primary_slot[index] to secondary_slot[index] according to amount 962 previosly copied at step b. 963 - If this is not the last region in the slot, erase the trailer in the 964 secondary slot, to always use the one in the primary slot. 965 + f. Write updated swap status (ii). 966 + g. Erase primary_slot[index]. 967 + h. Copy scratch area to primary_slot[index] according to amount 968 previously copied at step b. 969 - If this is the last region in the slot, the status is read from 970 scratch (where it was stored temporarily) and written anew in the 971 primary slot. 972 + i. Write updated swap status (iii). 9733. Persist completion of swap procedure to the primary slot image trailer. 974 975The additional caveats in step 2f are necessary so that the secondary slot image 976trailer can be written by the user at a later time. With the image trailer 977unwritten, the user can test the image in the secondary slot 978(i.e., transition to state I). 979 980--- 981***Note*** 982 983*If the region being copied contains the last sector, then swap status is* 984*temporarily maintained on scratch for the duration of this operation, always* 985*using the primary slot's area otherwise.* 986 987--- 988***Note*** 989 990*The bootloader tries to copy only used sectors (based on largest image* 991*installed on any of the slots), minimizing the amount of sectors copied and* 992*reducing the amount of time required for a swap operation.* 993 994--- 995 996The particulars of step 3 vary depending on whether an image is being tested, 997permanently used, reverted or a validation failure of the secondary slot 998happened when a swap was requested: 999 1000 * test: 1001 o Write primary_slot.copy_done = 1 1002 (swap caused the following values to be written: 1003 primary_slot.magic = BOOT_MAGIC 1004 secondary_slot.magic = UNSET 1005 primary_slot.image_ok = Unset) 1006 1007 * permanent: 1008 o Write primary_slot.copy_done = 1 1009 (swap caused the following values to be written: 1010 primary_slot.magic = BOOT_MAGIC 1011 secondary_slot.magic = UNSET 1012 primary_slot.image_ok = 0x01) 1013 1014 * revert: 1015 o Write primary_slot.copy_done = 1 1016 o Write primary_slot.image_ok = 1 1017 (swap caused the following values to be written: 1018 primary_slot.magic = BOOT_MAGIC) 1019 1020 * failure to validate the secondary slot: 1021 o Write primary_slot.image_ok = 1 1022 1023After completing the operations as described above the image in the primary slot 1024should be booted. 1025 1026## [Swap status](#swap-status) 1027 1028The swap status region allows the bootloader to recover in case it restarts in 1029the middle of an image swap operation. The swap status region consists of a 1030series of single-byte records. These records are written independently, and 1031therefore must be padded according to the minimum write size imposed by the 1032flash hardware. The structure of the swap status region is illustrated below. 1033In this figure, a min-write-size of 1 is assumed for simplicity, this diagram 1034shows 3 states per sector which is applicable to swap using scratch and swap 1035using move, however in swap using offset mode there are only 2 states per 1036sector and the overall state size required is less. 1037 1038``` 1039 0 1 2 3 1040 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 1041 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1042 |sec127,state 0 |sec127,state 1 |sec127,state 2 |sec126,state 0 | 1043 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1044 |sec126,state 1 |sec126,state 2 |sec125,state 0 |sec125,state 1 | 1045 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1046 |sec125,state 2 | | 1047 +-+-+-+-+-+-+-+-+ + 1048 ~ ~ 1049 ~ [Records for indices 124 through 1 ~ 1050 ~ ~ 1051 ~ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1052 ~ |sec000,state 0 |sec000,state 1 |sec000,state 2 | 1053 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 1054``` 1055 1056The above is probably not helpful at all; here is a description in English. 1057 1058Each image slot is partitioned into a sequence of flash sectors. If we were to 1059enumerate the sectors in a single slot, starting at 0, we would have a list of 1060sector indices. Since there are two image slots, each sector index would 1061correspond to a pair of sectors. For example, sector index 0 corresponds to 1062the first sector in the primary slot and the first sector in the secondary slot. 1063Finally, reverse the list of indices such that the list starts with index 1064`BOOT_MAX_IMG_SECTORS - 1` and ends with 0. The swap status region is a 1065representation of this reversed list. 1066 1067During a swap operation, each sector index transitions through four separate 1068states: 1069``` 10700. primary slot: image 0, secondary slot: image 1, scratch: N/A 10711. primary slot: image 0, secondary slot: N/A, scratch: image 1 (1->s, erase 1) 10722. primary slot: N/A, secondary slot: image 0, scratch: image 1 (0->1, erase 0) 10733. primary slot: image 1, secondary slot: image 0, scratch: N/A (s->0) 1074``` 1075 1076Each time a sector index transitions to a new state, the bootloader writes a 1077record to the swap status region. Logically, the bootloader only needs one 1078record per sector index to keep track of the current swap state. However, due 1079to limitations imposed by flash hardware, a record cannot be overwritten when 1080an index's state changes. To solve this problem, the bootloader uses three 1081records per sector index rather than just one. 1082 1083Each sector-state pair is represented as a set of three records. The record 1084values map to the above four states as follows 1085 1086``` 1087 | rec0 | rec1 | rec2 1088 --------+------+------+------ 1089 state 0 | 0xff | 0xff | 0xff 1090 state 1 | 0x01 | 0xff | 0xff 1091 state 2 | 0x01 | 0x02 | 0xff 1092 state 3 | 0x01 | 0x02 | 0x03 1093``` 1094 1095The swap status region can accommodate `BOOT_MAX_IMG_SECTORS` sector indices. 1096Hence, the size of the region, in bytes, is 1097`BOOT_MAX_IMG_SECTORS * min-write-size * s` where `s` is 3 for swap using 1098scratch and swap using move modes, and is 2 for swap using offset mode. The 1099only requirement for the index count is that it is great enough to account 1100for a maximum-sized image (i.e., at least as great as the total sector count in 1101an image slot). If a device's image slots have been configured with 1102`BOOT_MAX_IMG_SECTORS: 128` and use less than 128 sectors, the first record 1103that gets written will be somewhere in the middle of the region. For example, 1104if a slot uses 64 sectors, the first sector index that gets swapped is 63, 1105which corresponds to the exact halfway point within the region. 1106 1107--- 1108***Note*** 1109 1110*Since the scratch area only ever needs to record swapping of the last* 1111*sector, it uses at most min-write-size * 3 bytes for its own status area.* 1112 1113--- 1114 1115## [Reset recovery](#reset-recovery) 1116 1117If the bootloader resets in the middle of a swap operation, the two images may 1118be discontiguous in flash. Bootutil recovers from this condition by using the 1119image trailers to determine how the image parts are distributed in flash. 1120 1121The first step is determine where the relevant swap status region is located. 1122Because this region is embedded within the image slots, its location in flash 1123changes during a swap operation. The below set of tables map image trailers 1124contents to swap status location. In these tables, the "source" field 1125indicates where the swap status region is located. In case of multi image boot 1126the images primary area and the single scratch area is always examined in pairs. 1127If swap status found on scratch area then it might not belong to the current 1128image. The swap_info field of swap status stores the corresponding image number. 1129If it does not match then "source: none" is returned. 1130 1131``` 1132 | primary slot | scratch | 1133 ----------+--------------+--------------| 1134 magic | Good | Any | 1135 copy-done | 0x01 | N/A | 1136 ----------+--------------+--------------' 1137 source: none | 1138 ----------------------------------------' 1139 1140 | primary slot | scratch | 1141 ----------+--------------+--------------| 1142 magic | Good | Any | 1143 copy-done | 0xff | N/A | 1144 ----------+--------------+--------------' 1145 source: primary slot | 1146 ----------------------------------------' 1147 1148 | primary slot | scratch | 1149 ----------+--------------+--------------| 1150 magic | Any | Good | 1151 copy-done | Any | N/A | 1152 ----------+--------------+--------------' 1153 source: scratch | 1154 ----------------------------------------' 1155 1156 | primary slot | scratch | 1157 ----------+--------------+--------------| 1158 magic | Unset | Any | 1159 copy-done | 0xff | N/A | 1160 ----------+--------------+--------------| 1161 source: primary slot | 1162 ----------------------------------------+------------------------------+ 1163 This represents one of two cases: | 1164 o No swaps ever (no status to read, so no harm in checking). | 1165 o Mid-revert; status in the primary slot. | 1166 For this reason we assume the primary slot as source, to trigger a | 1167 check of the status area and find out if there was swapping under way. | 1168 -----------------------------------------------------------------------' 1169``` 1170 1171If the swap status region indicates that the images are not contiguous, MCUboot 1172determines the type of swap operation that was interrupted by reading the `swap 1173info` field in the active image trailer and extracting the swap type from bits 11740-3 then resumes the operation. In other words, it applies the procedure defined 1175in the previous section, moving image 1 into the primary slot and image 0 into 1176the secondary slot. If the boot status indicates that an image part is present 1177in the scratch area, this part is copied into the correct location by starting 1178at step e or step h in the area-swap procedure, depending on whether the part 1179belongs to image 0 or image 1. 1180 1181After the swap operation has been completed, the bootloader proceeds as though 1182it had just been started. 1183 1184## [Integrity check](#integrity-check) 1185 1186An image is checked for integrity immediately before it gets copied into the 1187primary slot. If the bootloader doesn't perform an image swap, then it can 1188perform an optional integrity check of the image in the primary slot if 1189`MCUBOOT_VALIDATE_PRIMARY_SLOT` is set, otherwise it doesn't perform an 1190integrity check. 1191 1192During the integrity check, the bootloader verifies the following aspects of 1193an image: 1194 1195 * 32-bit magic number must be correct (`IMAGE_MAGIC`). 1196 * Image must contain an `image_tlv_info` struct, identified by its magic 1197 (`IMAGE_TLV_PROT_INFO_MAGIC` or `IMAGE_TLV_INFO_MAGIC`) exactly following 1198 the firmware (`hdr_size` + `img_size`). If `IMAGE_TLV_PROT_INFO_MAGIC` is 1199 found then after `ih_protect_tlv_size` bytes, another `image_tlv_info` 1200 with magic equal to `IMAGE_TLV_INFO_MAGIC` must be present. 1201 * Image must contain a SHA256 TLV. 1202 * Calculated SHA256 must match SHA256 TLV contents. 1203 * Image *may* contain a signature TLV. If it does, it must also have a 1204 KEYHASH TLV with the hash of the key that was used to sign. The list of 1205 keys will then be iterated over looking for the matching key, which then 1206 will then be used to verify the image contents. 1207 1208For low performance MCU's where the validation is a heavy process at boot 1209(~1-2 seconds on a arm-cortex-M0), the `MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE` 1210could be used. This option will cache the validation result as described above 1211into the magic area of the primary slot. The next boot, the validation will be 1212skipped if the previous validation was succesfull. This option is reducing the 1213security level since if an attacker could modify the contents of the flash after 1214a good image has been validated, the attacker could run his own image without 1215running validation again. Enabling this option should be done with care. 1216 1217## [Security](#security) 1218 1219As indicated above, the final step of the integrity check is signature 1220verification. The bootloader can have one or more public keys embedded in it 1221at build time. During signature verification, the bootloader verifies that an 1222image was signed with a private key that corresponds to the embedded KEYHASH 1223TLV. 1224 1225For information on embedding public keys in the bootloader, as well as 1226producing signed images, see: [signed_images](signed_images.md). 1227 1228If you want to enable and use encrypted images, see: 1229[encrypted_images](encrypted_images.md). 1230 1231--- 1232***Note*** 1233 1234*Image encryption is not supported when the direct-xip upgrade strategy* 1235*is selected.* 1236 1237--- 1238 1239### [Using hardware keys for verification](#hw-key-support) 1240 1241By default, the whole public key is embedded in the bootloader code and its 1242hash is added to the image manifest as a KEYHASH TLV entry. As an alternative 1243the bootloader can be made independent of the keys (avoiding the incorporation 1244of the public key into the code) by using one of the following options: 1245`MCUBOOT_HW_KEY` or `MCUBOOT_BUILTIN_KEY`. 1246 1247Using any of these options makes MCUboot independent from the public key(s). 1248The key(s) can be provisioned any time and by different parties. 1249 1250Hardware KEYs support options details: 1251- `MCUBOOT_HW_KEY`: In this case the hash of the public key must be 1252provisioned to the target device and MCUboot must be able to retrieve the 1253key-hash from there. For this reason the target must provide a definition 1254for the `boot_retrieve_public_key_hash()` function which is declared in 1255`boot/bootutil/include/bootutil/sign_key.h`. It is also required to use 1256the `full` option for the `--public-key-format` imgtool argument in order to 1257add the whole public key (PUBKEY TLV) to the image manifest instead of its 1258hash (KEYHASH TLV). During boot the public key is validated before using it for 1259signature verification, MCUboot calculates the hash of the public key from the 1260TLV area and compares it with the key-hash that was retrieved from the device. 1261- `MCUBOOT_BUILTIN_KEY`: With this option the whole public key(s) used for 1262signature verification must be provisioned to the target device and the used 1263[cryptographic library](PORTING.md) must support the usage of builtin keys based 1264on key IDs. In this case, neither the code nor the image metadata needs to 1265contain any public key data. During image validation only a key ID is passed to 1266the verifier function. The key handling is entirely the responsibility of the 1267crypto library and the details of the key handling mechanism are abstracted away 1268from the boot code.\ 1269***Note:*** *At the moment the usage of builtin keys is only available with the* 1270*PSA Crypto API based crypto backend (`MCUBOOT_USE_PSA_CRYPTO`) for ECDSA* 1271*signatures.* 1272 1273## [Protected TLVs](#protected-tlvs) 1274 1275If the TLV area contains protected TLV entries, by beginning with a `struct 1276image_tlv_info` with a magic value of `IMAGE_TLV_PROT_INFO_MAGIC` then the 1277data of those TLVs must also be integrity and authenticity protected. Beyond 1278the full size of the protected TLVs being stored in the `image_tlv_info`, 1279the size of the protected TLVs together with the size of the `image_tlv_info` 1280struct itself are also saved in the `ih_protected_size` field inside the 1281header. 1282 1283Whenever an image has protected TLVs the SHA256 has to be calculated over 1284not just the image header and the image but also the TLV info header and the 1285protected TLVs. 1286 1287``` 1288A +---------------------+ 1289 | Header | <- struct image_header 1290 +---------------------+ 1291 | Payload | 1292 +---------------------+ 1293 | TLV area | 1294 | +-----------------+ | struct image_tlv_info with 1295 | | TLV area header | | <- IMAGE_TLV_PROT_INFO_MAGIC (optional) 1296 | +-----------------+ | 1297 | | Protected TLVs | | <- Protected TLVs (struct image_tlv) 1298B | +-----------------+ | 1299 | | TLV area header | | <- struct image_tlv_info with IMAGE_TLV_INFO_MAGIC 1300C | +-----------------+ | 1301 | | SHA256 hash | | <- hash from A - B (struct image_tlv) 1302D | +-----------------+ | 1303 | | Keyhash | | <- indicates which pub. key for sig (struct image_tlv) 1304 | +-----------------+ | 1305 | | Signature | | <- signature from C - D (struct image_tlv), only hash 1306 | +-----------------+ | 1307 +---------------------+ 1308``` 1309 1310## [Dependency check](#dependency-check) 1311 1312MCUboot can handle multiple firmware images. It is possible to update them 1313independently but in many cases it can be desired to be able to describe 1314dependencies between the images (e.g. to ensure API compliance and avoid 1315interoperability issues). 1316 1317The dependencies between images can be described with additional TLV entries in 1318the protected TLV area after the end of an image. There can be more than one 1319dependency entry, but in practice if the platform only supports two individual 1320images then there can be maximum one entry which reflects to the other image. 1321 1322At the phase of dependency check all aborted swaps are finalized if there were 1323any. During the dependency check the bootloader verifies whether the image 1324dependencies are all satisfied. If at least one of the dependencies of an image 1325is not fulfilled then the swap type of that image has to be modified 1326accordingly and the dependency check needs to be restarted. This way the number 1327of unsatisfied dependencies will decrease or remain the same. There is always at 1328least 1 valid configuration. In worst case, the system returns to the initial 1329state after dependency check. 1330 1331For more information on adding dependency entries to an image, 1332see: [imgtool](imgtool.md). 1333 1334## [Downgrade prevention](#downgrade-prevention) 1335 1336Downgrade prevention is a feature which enforces that the new image must have a 1337higher version/security counter number than the image it is replacing, thus 1338preventing the malicious downgrading of the device to an older and possibly 1339vulnerable version of its firmware. 1340 1341### [Software-based downgrade prevention](#sw-downgrade-prevention) 1342 1343During the software based downgrade prevention the image version numbers are 1344compared. This feature is enabled with the `MCUBOOT_DOWNGRADE_PREVENTION` 1345option. In this case downgrade prevention is only available when the 1346overwrite-based image update strategy is used (i.e. `MCUBOOT_OVERWRITE_ONLY` 1347is set). 1348 1349### [Hardware-based downgrade prevention](#hw-downgrade-prevention) 1350 1351Each signed image can contain a security counter in its protected TLV area, which 1352can be added to the image using the `-s` option of the [imgtool](imgtool.md) script. 1353During the hardware based downgrade prevention (alias rollback protection) the 1354new image's security counter will be compared with the currently active security 1355counter value which must be stored in a non-volatile and trusted component of 1356the device. It is beneficial to handle this counter independently from image 1357version number: 1358 1359 * It does not need to increase with each software release, 1360 * It makes it possible to do software downgrade to some extent: if the 1361 security counter has the same value in the older image then it is accepted. 1362 1363It is an optional step of the image validation process and can be enabled with 1364the `MCUBOOT_HW_ROLLBACK_PROT` config option. When enabled, the target must 1365provide an implementation of the security counter interface defined in 1366`boot/bootutil/include/security_cnt.h`. 1367 1368## [Measured boot and data sharing](#boot-data-sharing) 1369 1370MCUboot defines a mechanism for sharing boot status information (also known as 1371measured boot) and an interface for sharing application specific information 1372with the runtime software. If any of these are enabled the target must provide 1373a shared data area between the bootloader and runtime firmware and define the 1374following parameters: 1375 1376```c 1377#define MCUBOOT_SHARED_DATA_BASE <area_base_addr> 1378#define MCUBOOT_SHARED_DATA_SIZE <area_size_in_bytes> 1379``` 1380 1381In the shared memory area all data entries are stored in a type-length-value 1382(TLV) format. Before adding the first data entry, the whole area is overwritten 1383with zeros and a TLV header is added at the beginning of the area during an 1384initialization phase. This TLV header contains a `tlv_magic` field with a value 1385of `SHARED_DATA_TLV_INFO_MAGIC` and a `tlv_tot_len` field which is indicating 1386the total length of shared TLV area including this header. The header is 1387followed by the the data TLV entries which are composed from a 1388`shared_data_tlv_entry` header and the data itself. In the data header there is 1389a `tlv_type` field which identifies the consumer of the entry (in the runtime 1390software) and specifies the subtype of that data item. More information about 1391the `tlv_type` field and data types can be found in the 1392`boot/bootutil/include/bootutil/boot_status.h` file. The type is followed by a 1393`tlv_len` field which indicates the size of the data entry in bytes, not 1394including the entry header. After this header structure comes the actual data. 1395 1396```c 1397/** Shared data TLV header. All fields in little endian. */ 1398struct shared_data_tlv_header { 1399 uint16_t tlv_magic; 1400 uint16_t tlv_tot_len; /* size of whole TLV area (including this header) */ 1401}; 1402 1403/** Shared data TLV entry header format. All fields in little endian. */ 1404struct shared_data_tlv_entry { 1405 uint16_t tlv_type; 1406 uint16_t tlv_len; /* TLV data length (not including this header). */ 1407}; 1408``` 1409 1410The measured boot can be enabled with the `MCUBOOT_MEASURED_BOOT` config option. 1411When enabled, the `--boot_record` argument of the imgtool script must also be 1412used during the image signing process to add a BOOT_RECORD TLV to the image 1413manifest. This TLV contains the following attributes/measurements of the 1414image in CBOR encoded format: 1415 1416 * Software type (role of the software component) 1417 * Software version 1418 * Signer ID (identifies the signing authority) 1419 * Measurement value (hash of the image) 1420 * Measurement type (algorithm used to calculate the measurement value) 1421 1422The `sw_type` string that is passed as the `--boot_record` option's parameter 1423will be the value of the "Software type" attribute in the generated BOOT_RECORD 1424TLV. The target must also define the `MAX_BOOT_RECORD_SZ` macro which indicates 1425the maximum size of the CBOR encoded boot record in bytes. 1426During boot, MCUboot will look for these TLVs (in case of multiple images) in 1427the manifests of the active images (the latest and validated) and copy the CBOR 1428encoded binary data to the shared data area. Preserving all these image 1429attributes from the boot stage for use by later runtime services (such as an 1430attestation service) is known as a measured boot. 1431 1432Setting the `MCUBOOT_DATA_SHARING` option enables the sharing of application 1433specific data using the same shared data area as for the measured boot. For 1434this, the target must provide a definition for the `boot_save_shared_data()` 1435function which is declared in `boot/bootutil/include/bootutil/boot_record.h`. 1436The `boot_add_data_to_shared_area()` function can be used for adding new TLV 1437entries to the shared data area. Alternatively, setting the 1438`MCUBOOT_DATA_SHARING_BOOTINFO` option will provide a default function for 1439this which saves information such as the maximum application size, bootloader 1440version (if available), running slot number, if recovery is part of MCUboot 1441and the signature type. Details of the TLVs for this information can be found 1442in `boot/bootutil/include/bootutil/boot_status.h` with `BLINFO_` prefixes. 1443 1444## [Testing in CI](#testing-in-ci) 1445 1446### [Testing Fault Injection Hardening (FIH)](#testing-fih) 1447 1448The CI currently tests the Fault Injection Hardening feature of MCUboot by 1449executing instruction skip during execution, and looking at whether a corrupted 1450image was booted by the bootloader or not. 1451 1452The main idea is that instruction skipping can be automated by scripting a 1453debugger to automatically execute the following steps: 1454 1455- Set breakpoint at specified address. 1456- Continue execution. 1457- On breakpoint hit increase the Program Counter. 1458- Continue execution. 1459- Detach from target after a timeout reached. 1460 1461Whether or not the corrupted image was booted or not can be decided by looking 1462for certain entries in the log. 1463 1464As MCUboot is deployed on a microcontroller, testing FI would not make much 1465sense in the simulator environment running on a host machine with different 1466architecture than the MCU's, as the degree of hardening depends on compiler 1467behavior. For example, (a bit counterintuitively) the code produced by gcc 1468with `-O0` optimisation is more resilient against FI attacks than the code 1469generated with `-O3` or `-Os` optimizations. 1470 1471To run on a desired architecture in the CI, the tests need to be executed on an 1472emulator (as real devices are not available in the CI environment). For this 1473implementation QEMU is selected. 1474 1475For the tests MCUboot needs a set of drivers and an implementation of a main 1476function. For the purpose of this test Trusted-Firmware-M has been selected as 1477it supports Armv8-M platforms that are also emulated by QEMU. 1478 1479The tests run in a docker container inside the CI VMs, to make it more easy to 1480deploy build and test environment (QEMU, compilers, interpreters). The CI VMs 1481seems to be using quite old Ubuntu (16.04). 1482 1483The sequence of the testing is the following (pseudo code): 1484 1485```sh 1486fn main() 1487 # Implemented in ci/fih-tests_install.sh 1488 generate_docker_image(Dockerfile) 1489 1490 # See details below. Implemented in ci/fih-tests_run.sh. 1491 # Calling the function with different parameters is done by Travis CI based on 1492 # the values provided in the .travis.yaml 1493 start_docker_image(skip_sizes, build_type, damage_type, fih_level) 1494 1495fn start_docker_image(skip_sizes, build_type, damage_type, fih_level) 1496 # implemented in ci/fih_test_docker/execute_test.sh 1497 compile_mcuboot(build_type) 1498 1499 # implemented in ci/fih_test_docker/damage_image.py 1500 damage_image(damage_type) 1501 1502 # implemented in ci/fih_test_docker/run_fi_test.sh 1503 ranges = generate_address_ranges() 1504 for s in skip_sizes 1505 for r in ranges 1506 do_skip_in_qemu(s, r) # See details below 1507 evaluate_logs() 1508 1509fn do_skip_in_qemu(size, range) 1510 for a in r 1511 run_qemu(a, size) # See details below 1512 1513# this part is implemented in ci/fih_test_docker/fi_tester_gdb.sh 1514fn run_qemu(a, size) 1515 script = create_debugger_script(a, size) 1516 start_qemu_in_bacground() # logs serial out to a file 1517 gdb_attach_to_qemu(script) 1518 kill_qemu() 1519 1520 # This checks the debugger and the quemu logs, and decides whether the tets 1521 # was executed successfully, and whether the image is booted or not. Then 1522 # emits a yaml fragment on the standard out to be processed by the caller 1523 # script 1524 evaluate_run(qemu_log_file) 1525``` 1526 1527Further notes: 1528 1529- The image is corrupted by changing its signature. 1530- MCUBOOT_FIH_PROFILE_MAX is not tested as it requires TRNG, and the AN521 1531platform has no support for it. However this profile adds the random 1532execution delay to the code, so should not affect the instruction skip results 1533too much, because break point is placed at exact address. But in practice this 1534makes harder the accurate timing of the attack. 1535- The test cases defined in .travis.yml always return `passed`, if they were 1536executed successfully. A yaml file is created during test execution with the 1537details of the test execution results. A summary of the collected results is 1538printed in the log at the end of the test. 1539 1540An advantage of having the tests running in a docker image is that it is 1541possible to run the tests on a local machine that has git and docker, without 1542installing any additional software. 1543 1544So, running the test on the host looks like the following (The commands below 1545are issued from the MCUboot source directory): 1546 1547```sh 1548$ mkdir docker 1549$ ./ci/fih-tests_install.sh 1550$ FIH_LEVEL=MEDIUM BUILD_TYPE=RELEASE SKIP_SIZE=2 DAMAGE_TYPE=SIGNATURE \ 1551 ./ci/fih-tests_run.sh 1552``` 1553On the travis CI the environment variables in the last command are set based on 1554the configs provided in the `.travis.yaml` 1555 1556This starts the tests, however the shell that it is running in is not 1557interactive, it is not possible to examine the results of the test run. To have 1558an interactive shell where the results can be examined, the following can be 1559done: 1560 1561- The docker image needs to be built with `ci/fih-tests_install.sh` as described 1562 above. 1563- Start the docker image with the following command: 1564 `docker run -i -t mcuboot/fih-test`. 1565- Execute the test with a command similar to the following: 1566 `/root/execute_test.sh 8 RELEASE SIGNATURE MEDIUM`. After the test finishes, 1567 the shell returns, and it is possible to investigate the results. It is also 1568 possible to stop the test with _Ctrl+c_. The parameters to the 1569 `execute_test.sh` are `SKIP_SIZE`, `BUILD_TYPE`, `DAMAGE_TYPE`, `FIH_LEVEL` in 1570 order. 1571