blob: 2af04329af6e02997da7ae956b208ceb3db250d7 [file] [log] [blame] [view]
David Brown17e20d12017-09-12 11:53:20 -06001<!--
David Brownaac71112020-02-03 16:13:42 -07002 - SPDX-License-Identifier: Apache-2.0
David Brown17e20d12017-09-12 11:53:20 -06003
David Vinczee574f2d2020-07-10 11:42:03 +02004 - Copyright (c) 2017-2020 Linaro LTD
David Brownaac71112020-02-03 16:13:42 -07005 - Copyright (c) 2017-2019 JUUL Labs
Salome Thirot0f641972021-05-14 11:19:55 +01006 - Copyright (c) 2019-2021 Arm Limited
David Brownaac71112020-02-03 16:13:42 -07007
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.
David Vinczeba3bd602019-06-17 16:01:43 +020026-->
27
David Brown17e20d12017-09-12 11:53:20 -060028# Boot Loader
29
Fabio Utzigd37d8772019-12-03 10:32:18 -030030## [Summary](#summary)
Christopher Collins92ea77f2016-12-12 15:59:26 -080031
Fabio Utzigac834962017-07-20 13:20:48 -030032mcuboot comprises two packages:
Christopher Collins92ea77f2016-12-12 15:59:26 -080033
David Brown17e20d12017-09-12 11:53:20 -060034* The bootutil library (boot/bootutil)
35* The boot application (each port has its own at boot/<port>)
Christopher Collins92ea77f2016-12-12 15:59:26 -080036
37The bootutil library performs most of the functions of a boot loader. 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.
40Boot loader functionality is separated in this manner to enable unit testing of
41the boot loader. A library can be unit tested, but an application can't.
42Therefore, functionality is delegated to the bootutil library when possible.
43
Fabio Utzigd37d8772019-12-03 10:32:18 -030044## [Limitations](#limitations)
Christopher Collins92ea77f2016-12-12 15:59:26 -080045
46The boot loader currently only supports images with the following
47characteristics:
David Brown17e20d12017-09-12 11:53:20 -060048* Built to run from flash.
49* Built to run from a fixed location (i.e., not position-independent).
Christopher Collins92ea77f2016-12-12 15:59:26 -080050
Fabio Utzigd37d8772019-12-03 10:32:18 -030051## [Image Format](#image-format)
Christopher Collins92ea77f2016-12-12 15:59:26 -080052
53The following definitions describe the image format.
54
David Brown17e20d12017-09-12 11:53:20 -060055``` c
Fabio Utzigea422c22017-09-11 11:02:47 -030056#define IMAGE_MAGIC 0x96f3b83d
Christopher Collins92ea77f2016-12-12 15:59:26 -080057
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;
Fabio Utzigea422c22017-09-11 11:02:47 -030070 uint32_t ih_load_addr;
David Vinczee32483f2019-06-13 10:46:24 +020071 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_[...]. */
Christopher Collins92ea77f2016-12-12 15:59:26 -080075 struct image_version ih_ver;
David Vinczee32483f2019-06-13 10:46:24 +020076 uint32_t _pad1;
Christopher Collins92ea77f2016-12-12 15:59:26 -080077};
78
Fabio Utzigfd140ec2019-09-12 14:37:48 -030079#define IMAGE_TLV_INFO_MAGIC 0x6907
80#define IMAGE_TLV_PROT_INFO_MAGIC 0x6908
81
Fabio Utzigea422c22017-09-11 11:02:47 -030082/** 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
Christopher Collins92ea77f2016-12-12 15:59:26 -080088/** Image trailer TLV format. All fields in little endian. */
89struct image_tlv {
90 uint8_t it_type; /* IMAGE_TLV_[...]. */
91 uint8_t _pad;
Marti Bolivar49b29172017-08-04 14:50:51 -040092 uint16_t it_len; /* Data length (not including TLV header). */
Christopher Collins92ea77f2016-12-12 15:59:26 -080093};
94
95/*
96 * Image header flags.
97 */
Marti Bolivar7c057e92017-08-04 14:46:39 -040098#define IMAGE_F_PIC 0x00000001 /* Not supported. */
Salome Thirot0f641972021-05-14 11:19:55 +010099#define IMAGE_F_ENCRYPTED_AES128 0x00000004 /* Encrypted using AES128. */
100#define IMAGE_F_ENCRYPTED_AES256 0x00000008 /* Encrypted using AES256. */
Marti Bolivar7c057e92017-08-04 14:46:39 -0400101#define IMAGE_F_NON_BOOTABLE 0x00000010 /* Split image app. */
Fabio Utzigea422c22017-09-11 11:02:47 -0300102#define IMAGE_F_RAM_LOAD 0x00000020
Christopher Collins92ea77f2016-12-12 15:59:26 -0800103
104/*
105 * Image trailer TLV types.
106 */
Fabio Utzigea422c22017-09-11 11:02:47 -0300107#define IMAGE_TLV_KEYHASH 0x01 /* hash of the public key */
David Brown27648b82017-08-31 10:40:29 -0600108#define IMAGE_TLV_SHA256 0x10 /* SHA256 of image hdr and body */
Marko Kiiskila8dd56f32017-08-22 21:40:49 -0700109#define IMAGE_TLV_RSA2048_PSS 0x20 /* RSA2048 of hash output */
David Brown27648b82017-08-31 10:40:29 -0600110#define IMAGE_TLV_ECDSA224 0x21 /* ECDSA of hash output */
111#define IMAGE_TLV_ECDSA256 0x22 /* ECDSA of hash output */
Fabio Utzig3501c012019-05-13 15:07:25 -0700112#define IMAGE_TLV_RSA3072_PSS 0x23 /* RSA3072 of hash output */
Fabio Utzig195411f2019-06-28 07:48:21 -0300113#define IMAGE_TLV_ED25519 0x24 /* ED25519 of hash output */
David Vinczee32483f2019-06-13 10:46:24 +0200114#define IMAGE_TLV_ENC_RSA2048 0x30 /* Key encrypted with RSA-OAEP-2048 */
Salome Thirot0f641972021-05-14 11:19:55 +0100115#define IMAGE_TLV_ENC_KW 0x31 /* Key encrypted with AES-KW-128 or
116 256 */
Fabio Utzig5eaa5762020-04-02 13:30:43 -0300117#define IMAGE_TLV_ENC_EC256 0x32 /* Key encrypted with ECIES-P256 */
118#define IMAGE_TLV_ENC_X25519 0x33 /* Key encrypted with ECIES-X25519 */
David Vinczee32483f2019-06-13 10:46:24 +0200119#define IMAGE_TLV_DEPENDENCY 0x40 /* Image depends on other image */
David Vinczec3084132020-02-18 14:50:47 +0100120#define IMAGE_TLV_SEC_CNT 0x50 /* security counter */
David Brown17e20d12017-09-12 11:53:20 -0600121```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800122
123Optional type-length-value records (TLVs) containing image metadata are placed
124after the end of the image.
125
David Vinczee32483f2019-06-13 10:46:24 +0200126The `ih_protect_tlv_size` field indicates the length of the protected TLV area.
Fabio Utzigfd140ec2019-09-12 14:37:48 -0300127If protected TLVs are present then a TLV info header with magic equal to
128`IMAGE_TLV_PROT_INFO_MAGIC` must be present and the protected TLVs (plus the
129info header itself) have to be included in the hash calculation. Otherwise the
130hash is only calculated over the image header and the image itself. In this
David Vinczee32483f2019-06-13 10:46:24 +0200131case the value of the `ih_protect_tlv_size` field is 0.
132
David Brown17e20d12017-09-12 11:53:20 -0600133The `ih_hdr_size` field indicates the length of the header, and therefore the
Christopher Collins92ea77f2016-12-12 15:59:26 -0800134offset of the image itself. This field provides for backwards compatibility in
135case of changes to the format of the image header.
136
Fabio Utzigd37d8772019-12-03 10:32:18 -0300137## [Flash Map](#flash-map)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800138
Fabio Utzigac834962017-07-20 13:20:48 -0300139A device's flash is partitioned according to its _flash map_. At a high
Christopher Collins92ea77f2016-12-12 15:59:26 -0800140level, the flash map maps numeric IDs to _flash areas_. A flash area is a
141region of disk with the following properties:
David Brown17e20d12017-09-12 11:53:20 -06001421. An area can be fully erased without affecting any other areas.
1432. A write to one area does not restrict writes to other areas.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800144
Marti Bolivar4e64d562017-08-04 14:53:33 -0400145The boot loader uses the following flash area IDs:
David Vinczeb75c12a2019-03-22 14:58:33 +0100146```c
147/* Independent from multiple image boot */
David Vincze2d736ad2019-02-18 11:50:22 +0100148#define FLASH_AREA_BOOTLOADER 0
David Vinczeb75c12a2019-03-22 14:58:33 +0100149#define FLASH_AREA_IMAGE_SCRATCH 3
150```
151```c
152/* If the boot loader is working with the first image */
David Vincze2d736ad2019-02-18 11:50:22 +0100153#define FLASH_AREA_IMAGE_PRIMARY 1
154#define FLASH_AREA_IMAGE_SECONDARY 2
David Vinczeb75c12a2019-03-22 14:58:33 +0100155```
156```c
157/* If the boot loader is working with the second image */
158#define FLASH_AREA_IMAGE_PRIMARY 5
159#define FLASH_AREA_IMAGE_SECONDARY 6
David Brown17e20d12017-09-12 11:53:20 -0600160```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800161
Marti Bolivar4e64d562017-08-04 14:53:33 -0400162The bootloader area contains the bootloader image itself. The other areas are
David Vinczeb75c12a2019-03-22 14:58:33 +0100163described in subsequent sections. The flash could contain multiple executable
164images therefore the flash area IDs of primary and secondary areas are mapped
165based on the number of the active image (on which the bootloader is currently
166working).
Marti Bolivar4e64d562017-08-04 14:53:33 -0400167
Fabio Utzigd37d8772019-12-03 10:32:18 -0300168## [Image Slots](#image-slots)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800169
David Vinczeb75c12a2019-03-22 14:58:33 +0100170A portion of the flash memory can be partitioned into multiple image areas, each
171contains two image slots: a primary slot and a secondary slot.
David Vinczee574f2d2020-07-10 11:42:03 +0200172Normally, the boot loader will only run an image from the primary slot, so
173images must be built such that they can run from that fixed location in flash
Tamas Banfe031092020-09-10 17:32:39 +0200174(the exception to this is the [direct-xip](#direct-xip) and the
175[ram-load](#ram-load) upgrade mode). If the boot loader needs to run the
176image resident in the secondary slot, it must copy its contents into the primary
177slot before doing so, either by swapping the two images or by overwriting the
178contents of the primary slot. The bootloader supports either swap- or
179overwrite-based image upgrades, but must be configured at build time to choose
180one of these two strategies.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800181
David Vinczeb75c12a2019-03-22 14:58:33 +0100182In addition to the slots of image areas, the boot loader requires a scratch
183area to allow for reliable image swapping. The scratch area must have a size
184that is enough to store at least the largest sector that is going to be swapped.
185Many devices have small equally sized flash sectors, eg 4K, while others have
David Vincze2d736ad2019-02-18 11:50:22 +0100186variable sized sectors where the largest sectors might be 128K or 256K, so the
187scratch must be big enough to store that. The scratch is only ever used when
188swapping firmware, which means only when doing an upgrade. Given that, the main
189reason for using a larger size for the scratch is that flash wear will be more
190evenly distributed, because a single sector would be written twice the number of
191times than using two sectors, for example. To evaluate the ideal size of the
192scratch for your use case the following parameters are relevant:
Fabio Utziga722f5a2017-12-12 14:04:53 -0200193
194* the ratio of image size / scratch size
195* the number of erase cycles supported by the flash hardware
196
197The image size is used (instead of slot size) because only the slot's sectors
198that are actually used for storing the image are copied. The image/scratch ratio
199is the number of times the scratch will be erased on every upgrade. The number
200of erase cycles divided by the image/scratch ratio will give you the number of
201times an upgrade can be performed before the device goes out of spec.
202
203```
204num_upgrades = number_of_erase_cycles / (image_size / scratch_size)
205```
206
207Let's assume, for example, a device with 10000 erase cycles, an image size of
208150K and a scratch of 4K (usual minimum size of 4K sector devices). This would
209result in a total of:
210
211`10000 / (150 / 4) ~ 267`
212
213Increasing the scratch to 16K would give us:
214
215`10000 / (150 / 16) ~ 1067`
216
217There is no *best* ratio, as the right size is use-case dependent. Factors to
218consider include the number of times a device will be upgraded both in the field
David Vincze2d736ad2019-02-18 11:50:22 +0100219and during development, as well as any desired safety margin on the
220manufacturer's specified number of erase cycles. In general, using a ratio that
221allows hundreds to thousands of field upgrades in production is recommended.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800222
David Vinczee574f2d2020-07-10 11:42:03 +0200223### [Equal slots (direct-xip)](#direct-xip)
224
225When the direct-xip mode is enabled the active image flag is "moved" between the
226slots during image upgrade and in contrast to the above, the bootloader can
227run an image directly from either the primary or the secondary slot (without
228having to move/copy it into the primary slot). Therefore the image update
229client, which downloads the new images must be aware, which slot contains the
230active image and which acts as a staging area and it is responsible for loading
231the proper images into the proper slot. All this requires that the images be
232built to be executed from the corresponding slot. At boot time the bootloader
233first looks for images in the slots and then inspects the version numbers in the
234image headers. It selects the newest image (with the highest version number) and
235then checks its validity (integrity check, signature verification etc.). If the
236image is invalid MCUboot erases its memory slot and starts to validate the other
237image. After a successful validation of the selected image the bootloader
238chain-loads it.
David Vincze505fba22020-10-22 13:53:29 +0200239
240An additional "revert" mechanism is also supported. For more information, please
241read the [corresponding section](#direct-xip-revert).
David Vinczee574f2d2020-07-10 11:42:03 +0200242Handling the primary and secondary slots as equals has its drawbacks. Since the
243images are not moved between the slots, the on-the-fly image
244encryption/decryption can't be supported (it only applies to storing the image
245in an external flash on the device, the transport of encrypted image data is
246still feasible).
247
248The overwrite and the direct-xip upgrade strategies are substantially simpler to
249implement than the image swapping strategy, especially since the bootloader must
250work properly even when it is reset during the middle of an image swap. For this
251reason, the rest of the document describes its behavior when configured to swap
252images during an upgrade.
Marti Bolivara91674f2017-08-04 14:56:08 -0400253
Tamas Banfe031092020-09-10 17:32:39 +0200254### [RAM Loading](#ram-load)
255
256In ram-load mode the slots are equal. Like the direct-xip mode, this mode
257also selects the newest image by reading the image version numbers in the image
258headers. But instead of executing it in place, the newest image is copied to the
259RAM for execution. The load address, the location in RAM where the image is
260copied to, is stored in the image header. The ram-load upgrade mode can be
261useful when there is no internal flash in the SoC, but there is a big enough
262internal RAM to hold the images. Usually in this case the images are stored
263in an external storage device. Execution from external storage has some
264drawbacks (lower execution speed, image is exposed to attacks) therefore the
265image is always copied to the internal RAM before the authentication and
266execution. Ram-load mode requires the image to be built to be executed from
267the RAM address range instead of the storage device address range. If
268ram-load is enabled then platform must define the following parameters:
269
270```c
271#define IMAGE_EXECUTABLE_RAM_START <area_base_addr>
272#define IMAGE_EXECUTABLE_RAM_SIZE <area_size_in_bytes>
273```
274
Mark Horvathccaf7f82021-01-04 18:16:42 +0100275For multiple image load if multiple ram regions are used platform must define
276the `MULTIPLE_EXECUTABLE_RAM_REGIONS` flag instead and implement the following
277function:
278
279```c
280int boot_get_image_exec_ram_info(uint32_t image_id,
281 uint32_t *exec_ram_start,
282 uint32_t *exec_ram_size)
283```
284
Tamas Banfe031092020-09-10 17:32:39 +0200285When ram-load is enabled, the `--load-addr <addr>` option of the `imgtool`
286script must also be used when signing the images. This option set the `RAM_LOAD`
287flag in the image header which indicates that the image should be loaded to the
288RAM and also set the load address in the image header.
289
Mark Horvathccaf7f82021-01-04 18:16:42 +0100290The ram-load mode currently does not support the image encryption feature.
Tamas Banfe031092020-09-10 17:32:39 +0200291
Fabio Utzigd37d8772019-12-03 10:32:18 -0300292## [Boot Swap Types](#boot-swap-types)
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800293
Marti Bolivar048d8d82017-08-04 17:14:24 -0400294When the device first boots under normal circumstances, there is an up-to-date
David Vinczeba3bd602019-06-17 16:01:43 +0200295firmware image in each primary slot, which mcuboot can validate and then
David Vincze2d736ad2019-02-18 11:50:22 +0100296chain-load. In this case, no image swaps are necessary. During device upgrades,
David Vinczeba3bd602019-06-17 16:01:43 +0200297however, new candidate image(s) is present in the secondary slot(s), which
298mcuboot must swap into the primary slot(s) before booting as discussed above.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800299
Marti Bolivar048d8d82017-08-04 17:14:24 -0400300Upgrading an old image with a new one by swapping can be a two-step process. In
301this process, mcuboot performs a "test" swap of image data in flash and boots
David Vinczeba3bd602019-06-17 16:01:43 +0200302the new image or it will be executed during operation. The new image can then
303update the contents of flash at runtime to mark itself "OK", and mcuboot will
304then still choose to run it during the next boot. When this happens, the swap is
305made "permanent". If this doesn't happen, mcuboot will perform a "revert" swap
306during the next boot by swapping the image(s) back into its original location(s)
307, and attempting to boot the old image(s).
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800308
Marti Bolivar048d8d82017-08-04 17:14:24 -0400309Depending on the use case, the first swap can also be made permanent directly.
310In this case, mcuboot will never attempt to revert the images on the next reset.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800311
Marti Bolivar048d8d82017-08-04 17:14:24 -0400312Test swaps are supported to provide a rollback mechanism to prevent devices
313from becoming "bricked" by bad firmware. If the device crashes immediately
314upon booting a new (bad) image, mcuboot will revert to the old (working) image
315at the next device reset, rather than booting the bad image again. This allows
316device firmware to make test swaps permanent only after performing a self-test
317routine.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800318
David Vinczeba3bd602019-06-17 16:01:43 +0200319On startup, mcuboot inspects the contents of flash to decide for each images
320which of these "swap types" to perform; this decision determines how it
321proceeds.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800322
Marti Bolivar048d8d82017-08-04 17:14:24 -0400323The possible swap types, and their meanings, are:
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800324
David Brown17e20d12017-09-12 11:53:20 -0600325- `BOOT_SWAP_TYPE_NONE`: The "usual" or "no upgrade" case; attempt to boot the
David Vincze2d736ad2019-02-18 11:50:22 +0100326 contents of the primary slot.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800327
David Vincze2d736ad2019-02-18 11:50:22 +0100328- `BOOT_SWAP_TYPE_TEST`: Boot the contents of the secondary slot by swapping
329 images. Unless the swap is made permanent, revert back on the next boot.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800330
David Brown17e20d12017-09-12 11:53:20 -0600331- `BOOT_SWAP_TYPE_PERM`: Permanently swap images, and boot the upgraded image
Marti Bolivar048d8d82017-08-04 17:14:24 -0400332 firmware.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800333
David Vincze2d736ad2019-02-18 11:50:22 +0100334- `BOOT_SWAP_TYPE_REVERT`: A previous test swap was not made permanent;
335 swap back to the old image whose data are now in the secondary slot. If the
336 old image marks itself "OK" when it boots, the next boot will have swap type
337 `BOOT_SWAP_TYPE_NONE`.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800338
David Brown17e20d12017-09-12 11:53:20 -0600339- `BOOT_SWAP_TYPE_FAIL`: Swap failed because image to be run is not valid.
Marti Bolivar048d8d82017-08-04 17:14:24 -0400340
David Brown17e20d12017-09-12 11:53:20 -0600341- `BOOT_SWAP_TYPE_PANIC`: Swapping encountered an unrecoverable error.
Marti Bolivar048d8d82017-08-04 17:14:24 -0400342
343The "swap type" is a high-level representation of the outcome of the
344boot. Subsequent sections describe how mcuboot determines the swap type from
345the bit-level contents of flash.
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800346
David Vincze505fba22020-10-22 13:53:29 +0200347### [Revert mechanism in direct-xip mode](#direct-xip-revert)
348
349The direct-xip mode also supports a "revert" mechanism which is the equivalent
David Vincze1c456242021-06-29 15:25:24 +0200350of the swap mode's "revert" swap. When the direct-xip mode is selected it can be
351enabled with the MCUBOOT_DIRECT_XIP_REVERT config option and an image trailer
352must also be added to the signed images (the "--pad" option of the `imgtool`
353script must be used). For more information on this please read the
354[Image Trailer](#image-trailer) section and the [imgtool](imgtool.md)
355documentation. Making the images permanent (marking them as confirmed in
356advance) is also supported just like in swap mode. The individual steps of the
357direct-xip mode's "revert" mechanism are the following:
David Vincze505fba22020-10-22 13:53:29 +0200358
3591. Select the slot which holds the newest potential image.
3602. Was the image previously selected to run (during a previous boot)?
361 + Yes: Did the image mark itself "OK" (was the self-test successful)?
362 + Yes.
363 - Proceed to step 3.
364 + No.
365 - Erase the image from the slot to prevent it from being selected
366 again during the next boot.
367 - Return to step 1 (the bootloader will attempt to select and
368 possibly boot the previous image if there is one).
369 + No.
370 - Mark the image as "selected" (set the copy_done flag in the trailer).
371 - Proceed to step 3.
3723. Proceed to image validation ...
373
Fabio Utzigd37d8772019-12-03 10:32:18 -0300374## [Image Trailer](#image-trailer)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800375
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300376For the bootloader to be able to determine the current state and what actions
Marti Bolivar42818032017-08-04 15:45:01 -0400377should be taken during the current boot operation, it uses metadata stored in
378the image flash areas. While swapping, some of this metadata is temporarily
379copied into and out of the scratch area.
380
381This metadata is located at the end of the image flash areas, and is called an
382image trailer. An image trailer has the following structure:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800383
David Brown17e20d12017-09-12 11:53:20 -0600384```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800385 0 1 2 3
386 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
387 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collins92ea77f2016-12-12 15:59:26 -0800388 ~ ~
Fabio Utzig2c05f1b2018-04-04 10:35:17 -0300389 ~ Swap status (BOOT_MAX_IMG_SECTORS * min-write-size * 3) ~
Christopher Collins92ea77f2016-12-12 15:59:26 -0800390 ~ ~
391 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700392 | Encryption key 0 (16 octets) [*] |
393 | |
Christopher Collins92ea77f2016-12-12 15:59:26 -0800394 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700395 | Encryption key 1 (16 octets) [*] |
396 | |
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300397 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700398 | Swap size (4 octets) |
Fabio Utzigea422c22017-09-11 11:02:47 -0300399 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
David Vinczee2453472019-06-17 12:31:59 +0200400 | Swap info | 0xff padding (7 octets) |
Fabio Utzigea422c22017-09-11 11:02:47 -0300401 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
Christopher Collinsa1c12042019-05-23 14:00:28 -0700402 | Copy done | 0xff padding (7 octets) |
403 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
404 | Image OK | 0xff padding (7 octets) |
405 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
406 | MAGIC (16 octets) |
407 | |
Christopher Collins92ea77f2016-12-12 15:59:26 -0800408 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
David Brown17e20d12017-09-12 11:53:20 -0600409```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800410
Christopher Collinsa1c12042019-05-23 14:00:28 -0700411[*]: Only present if the encryption option is enabled (`MCUBOOT_ENC_IMAGES`).
412
Marti Bolivar42818032017-08-04 15:45:01 -0400413The offset immediately following such a record represents the start of the next
414flash area.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800415
416Note: "min-write-size" is a property of the flash hardware. If the hardware
417allows individual bytes to be written at arbitrary addresses, then
418min-write-size is 1. If the hardware only allows writes at even addresses,
419then min-write-size is 2, and so on.
420
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400421An image trailer contains the following fields:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800422
Marti Bolivar1dcb6852017-08-04 15:59:32 -04004231. Swap status: A series of records which records the progress of an image
David Vincze2d736ad2019-02-18 11:50:22 +0100424 swap. To swap entire images, data are swapped between the two image areas
425 one or more sectors at a time, like this:
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400426
David Vincze2d736ad2019-02-18 11:50:22 +0100427 - sector data in the primary slot is copied into scratch, then erased
428 - sector data in the secondary slot is copied into the primary slot,
429 then erased
430 - sector data in scratch is copied into the secondary slot
Marti Bolivar1dcb6852017-08-04 15:59:32 -0400431
432As it swaps images, the bootloader updates the swap status field in a way that
433allows it to compute how far this swap operation has progressed for each
434sector. The swap status field can thus used to resume a swap operation if the
435bootloader is halted while a swap operation is ongoing and later reset. The
David Vincze2d736ad2019-02-18 11:50:22 +0100436`BOOT_MAX_IMG_SECTORS` value is the configurable maximum number of sectors
437mcuboot supports for each image; its value defaults to 128, but allows for
438either decreasing this size, to limit RAM usage, or to increase it in devices
439that have massive amounts of Flash or very small sized sectors and thus require
440a bigger configuration to allow for the handling of all slot's sectors.
441The factor of min-write-sz is due to the behavior of flash hardware. The factor
442of 3 is explained below.
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300443
Christopher Collinsa1c12042019-05-23 14:00:28 -07004442. Encryption keys: key-encrypting keys (KEKs). These keys are needed for
445 image encryption and decryption. See the
446 [encrypted images](encrypted_images.md) document for more information.
447
4483. Swap size: When beginning a new swap operation, the total size that needs
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +0000449 to be swapped (based on the slot with largest image + TLVs) is written to
David Vincze2d736ad2019-02-18 11:50:22 +0100450 this location for easier recovery in case of a reset while performing the
451 swap.
Fabio Utzigea422c22017-09-11 11:02:47 -0300452
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +00004534. Swap info: A single byte which encodes the following information:
David Vinczee2453472019-06-17 12:31:59 +0200454 - Swap type: Stored in bits 0-3. Indicating the type of swap operation in
455 progress. When mcuboot resumes an interrupted swap, it uses this field to
456 determine the type of operation to perform. This field contains one of the
457 following values in the table below.
458 - Image number: Stored in bits 4-7. It has always 0 value at single image
459 boot. In case of multi image boot it indicates, which image was swapped when
460 interrupt happened. The same scratch area is used during in case of all
461 image swap operation. Therefore this field is used to determine which image
462 the trailer belongs to if boot status is found on scratch area when the swap
463 operation is resumed.
Christopher Collinsa1c12042019-05-23 14:00:28 -0700464
465| Name | Value |
466| ------------------------- | ----- |
467| `BOOT_SWAP_TYPE_TEST` | 2 |
468| `BOOT_SWAP_TYPE_PERM` | 3 |
469| `BOOT_SWAP_TYPE_REVERT` | 4 |
470
471
4725. Copy done: A single byte indicating whether the image in this slot is
David Brown17e20d12017-09-12 11:53:20 -0600473 complete (0x01=done; 0xff=not done).
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300474
Christopher Collinsa1c12042019-05-23 14:00:28 -07004756. Image OK: A single byte indicating whether the image in this slot has been
David Brown17e20d12017-09-12 11:53:20 -0600476 confirmed as good by the user (0x01=confirmed; 0xff=not confirmed).
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300477
Christopher Collinsa1c12042019-05-23 14:00:28 -07004787. MAGIC: The following 16 bytes, written in host-byte-order:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800479
David Brown17e20d12017-09-12 11:53:20 -0600480``` c
Christopher Collins92ea77f2016-12-12 15:59:26 -0800481 const uint32_t boot_img_magic[4] = {
482 0xf395c277,
483 0x7fefd260,
484 0x0f505235,
485 0x8079b62c,
486 };
David Brown17e20d12017-09-12 11:53:20 -0600487```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800488
Fabio Utzigd37d8772019-12-03 10:32:18 -0300489## [IMAGE TRAILERS](#image-trailers)
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300490
Marti Bolivar048d8d82017-08-04 17:14:24 -0400491At startup, the boot loader determines the boot swap type by inspecting the
492image trailers. When using the term "image trailers" what is meant is the
493aggregate information provided by both image slot's trailers.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300494
Fabio Utzigd37d8772019-12-03 10:32:18 -0300495### [New swaps (non-resumes)](#new-swaps-non-resumes)
Christopher Collinsa1c12042019-05-23 14:00:28 -0700496
497For new swaps, mcuboot must inspect a collection of fields to determine which
498swap operation to perform.
499
David Vincze2d736ad2019-02-18 11:50:22 +0100500The image trailers records are structured around the limitations imposed by
501flash hardware. As a consequence, they do not have a very intuitive design, and
502it is difficult to get a sense of the state of the device just by looking at the
Marti Bolivar048d8d82017-08-04 17:14:24 -0400503image trailers. It is better to map all the possible trailer states to the swap
504types described above via a set of tables. These tables are reproduced below.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300505
506Note: An important caveat about the tables described below is that they must
507be evaluated in the order presented here. Lower state numbers must have a
508higher priority when testing the image trailers.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800509
David Brown17e20d12017-09-12 11:53:20 -0600510```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800511 State I
David Vincze2d736ad2019-02-18 11:50:22 +0100512 | primary slot | secondary slot |
513 -----------------+--------------+----------------|
514 magic | Any | Good |
515 image-ok | Any | Unset |
516 copy-done | Any | Any |
517 -----------------+--------------+----------------'
518 result: BOOT_SWAP_TYPE_TEST |
519 -------------------------------------------------'
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300520
Christopher Collins92ea77f2016-12-12 15:59:26 -0800521
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300522 State II
David Vincze2d736ad2019-02-18 11:50:22 +0100523 | primary slot | secondary slot |
524 -----------------+--------------+----------------|
525 magic | Any | Good |
526 image-ok | Any | 0x01 |
527 copy-done | Any | Any |
528 -----------------+--------------+----------------'
529 result: BOOT_SWAP_TYPE_PERM |
530 -------------------------------------------------'
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300531
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800532
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300533 State III
David Vincze2d736ad2019-02-18 11:50:22 +0100534 | primary slot | secondary slot |
535 -----------------+--------------+----------------|
536 magic | Good | Unset |
537 image-ok | 0xff | Any |
538 copy-done | 0x01 | Any |
539 -----------------+--------------+----------------'
540 result: BOOT_SWAP_TYPE_REVERT |
541 -------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -0600542```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800543
Marti Bolivar048d8d82017-08-04 17:14:24 -0400544Any of the above three states results in mcuboot attempting to swap images.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800545
Marti Bolivar048d8d82017-08-04 17:14:24 -0400546Otherwise, mcuboot does not attempt to swap images, resulting in one of the
547other three swap types, as illustrated by State IV.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300548
David Brown17e20d12017-09-12 11:53:20 -0600549```
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300550 State IV
David Vincze2d736ad2019-02-18 11:50:22 +0100551 | primary slot | secondary slot |
552 -----------------+--------------+----------------|
553 magic | Any | Any |
554 image-ok | Any | Any |
555 copy-done | Any | Any |
556 -----------------+--------------+----------------'
557 result: BOOT_SWAP_TYPE_NONE, |
558 BOOT_SWAP_TYPE_FAIL, or |
559 BOOT_SWAP_TYPE_PANIC |
560 -------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -0600561```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800562
Marti Bolivar048d8d82017-08-04 17:14:24 -0400563In State IV, when no errors occur, mcuboot will attempt to boot the contents of
David Vincze2d736ad2019-02-18 11:50:22 +0100564the primary slot directly, and the result is `BOOT_SWAP_TYPE_NONE`. If the image
565in the primary slot is not valid, the result is `BOOT_SWAP_TYPE_FAIL`. If a
566fatal error occurs during boot, the result is `BOOT_SWAP_TYPE_PANIC`. If the
567result is either `BOOT_SWAP_TYPE_FAIL` or `BOOT_SWAP_TYPE_PANIC`, mcuboot hangs
568rather than booting an invalid or compromised image.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300569
Marti Bolivar048d8d82017-08-04 17:14:24 -0400570Note: An important caveat to the above is the result when a swap is requested
David Vincze2d736ad2019-02-18 11:50:22 +0100571 and the image in the secondary slot fails to validate, due to a hashing or
572 signing error. This state behaves as State IV with the extra action of
573 marking the image in the primary slot as "OK", to prevent further attempts
574 to swap.
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300575
Fabio Utzigd37d8772019-12-03 10:32:18 -0300576### [Resumed swaps](#resumed-swaps)
Christopher Collinsa1c12042019-05-23 14:00:28 -0700577
578If mcuboot determines that it is resuming an interrupted swap (i.e., a reset
579occurred mid-swap), it fully determines the operation to resume by reading the
David Vinczee2453472019-06-17 12:31:59 +0200580`swap info` field from the active trailer and extracting the swap type from bits
5810-3. The set of tables in the previous section are not necessary in the resume
582case.
Christopher Collinsa1c12042019-05-23 14:00:28 -0700583
Fabio Utzigd37d8772019-12-03 10:32:18 -0300584## [High-Level Operation](#high-level-operation)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800585
586With the terms defined, we can now explore the boot loader's operation. First,
587a high-level overview of the boot process is presented. Then, the following
588sections describe each step of the process in more detail.
589
590Procedure:
591
David Brown17e20d12017-09-12 11:53:20 -06005921. Inspect swap status region; is an interrupted swap being resumed?
Fabio Utzig75b34412019-09-06 08:30:43 -0300593 + Yes: Complete the partial swap operation; skip to step 3.
594 + No: Proceed to step 2.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800595
David Brown17e20d12017-09-12 11:53:20 -06005962. Inspect image trailers; is a swap requested?
Fabio Utzig75b34412019-09-06 08:30:43 -0300597 + Yes:
598 1. Is the requested image valid (integrity and security check)?
599 + Yes.
600 a. Perform swap operation.
601 b. Persist completion of swap procedure to image trailers.
602 c. Proceed to step 3.
603 + No.
604 a. Erase invalid image.
605 b. Persist failure of swap procedure to image trailers.
606 c. Proceed to step 3.
607
608 + No: Proceed to step 3.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800609
David Vincze2d736ad2019-02-18 11:50:22 +01006103. Boot into image in primary slot.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800611
Fabio Utzigd37d8772019-12-03 10:32:18 -0300612### [Multiple Image Boot](#multiple-image-boot)
David Vinczeba3bd602019-06-17 16:01:43 +0200613
614When the flash contains multiple executable images the boot loader's operation
615is a bit more complex but similar to the previously described procedure with
616one image. Every image can be updated independently therefore the flash is
617partitioned further to arrange two slots for each image.
618```
619+--------------------+
620| MCUBoot |
621+--------------------+
622 ~~~~~ <- memory might be not contiguous
623+--------------------+
624| Image 0 |
625| primary slot |
626+--------------------+
627| Image 0 |
628| secondary slot |
629+--------------------+
630 ~~~~~ <- memory might be not contiguous
631+--------------------+
632| Image N |
633| primary slot |
634+--------------------+
635| Image N |
636| secondary slot |
637+--------------------+
638| Scratch |
639+--------------------+
640```
David Vinczee32483f2019-06-13 10:46:24 +0200641MCUBoot is also capable of handling dependencies between images. For example
642if an image needs to be reverted it might be necessary to revert another one too
643(e.g. due to API incompatibilities) or simply to prevent from being updated
644because of an unsatisfied dependency. Therefore all aborted swaps have to be
645completed and all the swap types have to be determined for each image before
646the dependency checks. Dependency handling is described in more detail in a
647following section. The multiple image boot procedure is organized in loops which
648iterate over all the firmware images. The high-level overview of the boot
649process is presented below.
David Vinczeba3bd602019-06-17 16:01:43 +0200650
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700651+ Loop 1. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200652 1. Inspect swap status region of current image; is an interrupted swap being
653 resumed?
654 + Yes:
655 + Review the validity of previously determined swap types
656 of other images.
657 + Complete the partial swap operation.
658 + Mark the swap type as `None`.
659 + Skip to next image.
660 + No: Proceed to step 2.
661
662 2. Inspect image trailers in the primary and secondary slot; is an image
663 swap requested?
664 + Yes: Review the validity of previously determined swap types of other
665 images. Is the requested image valid (integrity and security
666 check)?
667 + Yes:
668 + Set the previously determined swap type for the current image.
669 + Skip to next image.
670 + No:
671 + Erase invalid image.
672 + Persist failure of swap procedure to image trailers.
673 + Mark the swap type as `Fail`.
674 + Skip to next image.
675 + No:
676 + Mark the swap type as `None`.
677 + Skip to next image.
678
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700679+ Loop 2. Iterate over all images
David Vinczee32483f2019-06-13 10:46:24 +0200680 1. Does the current image depend on other image(s)?
681 + Yes: Are all the image dependencies satisfied?
682 + Yes: Skip to next image.
683 + No:
684 + Modify swap type depending on what the previous type was.
685 + Restart dependency check from the first image.
686 + No: Skip to next image.
David Vinczeba3bd602019-06-17 16:01:43 +0200687
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700688+ Loop 3. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200689 1. Is an image swap requested?
690 + Yes:
691 + Perform image update operation.
692 + Persist completion of swap procedure to image trailers.
693 + Skip to next image.
694 + No: Skip to next image.
695
Martí Bolívara6a0e0e2019-08-08 07:12:54 -0700696+ Loop 4. Iterate over all images
David Vinczeba3bd602019-06-17 16:01:43 +0200697 1. Validate image in the primary slot (integrity and security check) or
698 at least do a basic sanity check to avoid booting into an empty flash
699 area.
700
701+ Boot into image in the primary slot of the 0th image position\
702 (other image in the boot chain is started by another image).
703
Mark Horvathccaf7f82021-01-04 18:16:42 +0100704### [Multiple Image Boot for RAM loading and direct-xip](#multiple-image-boot-for-ram-loading-and-direct-xip)
705
706The operation of the boot loader is different when the ram-load or the
707direct-xip strategy is chosen. The flash map is very similar to the swap
708strategy but there is no need for Scratch area.
709
710+ Loop 1. Until all images are loaded and all dependencies are satisfied
711 1. Subloop 1. Iterate over all images
712 + Does any of the slots contain an image?
713 + Yes:
714 + Choose the newer image.
715 + Copy it to RAM in case of ram-load strategy.
716 + Validate the image (integrity and security check).
717 + If validation fails delete the image from flash and try the other
718 slot. (Image must be deleted from RAM too in case of ram-load
719 strategy.)
720 + No: Return with failure.
721
722 2. Subloop 2. Iterate over all images
723 + Does the current image depend on other image(s)?
724 + Yes: Are all the image dependencies satisfied?
725 + Yes: Skip to next image.
726 + No:
727 + Delete the image from RAM in case of ram-load strategy, but
728 do not delete it from flash.
729 + Try to load the image from the other slot.
730 + Restart dependency check from the first image.
731 + No: Skip to next image.
732
733+ Loop 2. Iterate over all images
734 + Increase the security counter if needed.
735 + Do the measured boot and the data sharing if needed.
736
737+ Boot the loaded slot of image 0.
738
Fabio Utzigd37d8772019-12-03 10:32:18 -0300739## [Image Swapping](#image-swapping)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800740
741The boot loader swaps the contents of the two image slots for two reasons:
Fabio Utzig75b34412019-09-06 08:30:43 -0300742
743 * User has issued a "set pending" operation; the image in the secondary slot
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000744 should be run once (state I) or repeatedly (state II), depending on
Fabio Utzig75b34412019-09-06 08:30:43 -0300745 whether a permanent swap was specified.
746 * Test image rebooted without being confirmed; the boot loader should
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000747 revert to the original image currently in the secondary slot (state III).
Christopher Collins92ea77f2016-12-12 15:59:26 -0800748
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300749If the image trailers indicates that the image in the secondary slot should be
Christopher Collins92ea77f2016-12-12 15:59:26 -0800750run, the boot loader needs to copy it to the primary slot. The image currently
751in the primary slot also needs to be retained in flash so that it can be used
752later. Furthermore, both images need to be recoverable if the boot loader
753resets in the middle of the swap operation. The two images are swapped
754according to the following procedure:
755
Fabio Utzig60319ac2019-09-06 08:29:50 -03007561. Determine if both slots are compatible enough to have their images swapped.
757 To be compatible, both have to have only sectors that can fit into the
758 scratch area and if one of them has larger sectors than the other, it must
759 be able to entirely fit some rounded number of sectors from the other slot.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300760 In the next steps we'll use the terminology "region" for the total amount of
761 data copied/erased because this can be any amount of sectors depending on
762 how many the scratch is able to fit for some swap operation.
7632. Iterate the list of region indices in descending order (i.e., starting
764 with the greatest index); only regions that are predetermined to be part of
Fabio Utzig60319ac2019-09-06 08:29:50 -0300765 the image are copied; current element = "index".
766 + a. Erase scratch area.
767 + b. Copy secondary_slot[index] to scratch area.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300768 - If this is the last region in the slot, scratch area has a temporary
Fabio Utzig60319ac2019-09-06 08:29:50 -0300769 status area initialized to store the initial state, because the
Fabio Utzigc28005b2019-09-10 12:18:29 -0300770 primary slot's last region will have to be erased. In this case,
Fabio Utzig60319ac2019-09-06 08:29:50 -0300771 only the data that was calculated to amount to the image is copied.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300772 - Else if this is the first swapped region but not the last region in
Fabio Utzig60319ac2019-09-06 08:29:50 -0300773 the slot, initialize the status area in primary slot and copy the
Fabio Utzigc28005b2019-09-10 12:18:29 -0300774 full region contents.
775 - Else, copy entire region contents.
Fabio Utzig60319ac2019-09-06 08:29:50 -0300776 + c. Write updated swap status (i).
777 + d. Erase secondary_slot[index]
778 + e. Copy primary_slot[index] to secondary_slot[index] according to amount
779 previosly copied at step b.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300780 - If this is not the last region in the slot, erase the trailer in the
Fabio Utzig60319ac2019-09-06 08:29:50 -0300781 secondary slot, to always use the one in the primary slot.
782 + f. Write updated swap status (ii).
783 + g. Erase primary_slot[index].
784 + h. Copy scratch area to primary_slot[index] according to amount
785 previously copied at step b.
Fabio Utzigc28005b2019-09-10 12:18:29 -0300786 - If this is the last region in the slot, the status is read from
Fabio Utzig60319ac2019-09-06 08:29:50 -0300787 scratch (where it was stored temporarily) and written anew in the
788 primary slot.
789 + i. Write updated swap status (iii).
7903. Persist completion of swap procedure to the primary slot image trailer.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800791
David Vincze2d736ad2019-02-18 11:50:22 +0100792The additional caveats in step 2f are necessary so that the secondary slot image
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800793trailer can be written by the user at a later time. With the image trailer
David Vincze2d736ad2019-02-18 11:50:22 +0100794unwritten, the user can test the image in the secondary slot
Håkon Øye Amundsen11d91c32020-03-04 08:49:47 +0000795(i.e., transition to state I).
Christopher Collins92ea77f2016-12-12 15:59:26 -0800796
Fabio Utzigc28005b2019-09-10 12:18:29 -0300797Note1: If the region being copied contains the last sector, then swap status is
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300798temporarily maintained on scratch for the duration of this operation, always
David Vincze2d736ad2019-02-18 11:50:22 +0100799using the primary slot's area otherwise.
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300800
801Note2: The bootloader tries to copy only used sectors (based on largest image
802installed on any of the slots), minimizing the amount of sectors copied and
803reducing the amount of time required for a swap operation.
804
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800805The particulars of step 3 vary depending on whether an image is being tested,
David Vincze2d736ad2019-02-18 11:50:22 +0100806permanently used, reverted or a validation failure of the secondary slot
807happened when a swap was requested:
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300808
Christopher Collins92ea77f2016-12-12 15:59:26 -0800809 * test:
David Vincze2d736ad2019-02-18 11:50:22 +0100810 o Write primary_slot.copy_done = 1
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800811 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100812 primary_slot.magic = BOOT_MAGIC
Håkon Øye Amundsencdf94c22020-03-04 08:52:31 +0000813 secondary_slot.magic = UNSET
David Vincze2d736ad2019-02-18 11:50:22 +0100814 primary_slot.image_ok = Unset)
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800815
816 * permanent:
David Vincze2d736ad2019-02-18 11:50:22 +0100817 o Write primary_slot.copy_done = 1
Christopher Collinsfd7eb5c2016-12-21 13:46:08 -0800818 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100819 primary_slot.magic = BOOT_MAGIC
Håkon Øye Amundsencdf94c22020-03-04 08:52:31 +0000820 secondary_slot.magic = UNSET
David Vincze2d736ad2019-02-18 11:50:22 +0100821 primary_slot.image_ok = 0x01)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800822
823 * revert:
David Vincze2d736ad2019-02-18 11:50:22 +0100824 o Write primary_slot.copy_done = 1
825 o Write primary_slot.image_ok = 1
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300826 (swap caused the following values to be written:
David Vincze2d736ad2019-02-18 11:50:22 +0100827 primary_slot.magic = BOOT_MAGIC)
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300828
David Vincze2d736ad2019-02-18 11:50:22 +0100829 * failure to validate the secondary slot:
830 o Write primary_slot.image_ok = 1
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300831
David Vincze2d736ad2019-02-18 11:50:22 +0100832After completing the operations as described above the image in the primary slot
833should be booted.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800834
Fabio Utzigd37d8772019-12-03 10:32:18 -0300835## [Swap Status](#swap-status)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800836
837The swap status region allows the boot loader to recover in case it restarts in
838the middle of an image swap operation. The swap status region consists of a
839series of single-byte records. These records are written independently, and
840therefore must be padded according to the minimum write size imposed by the
841flash hardware. In the below figure, a min-write-size of 1 is assumed for
842simplicity. The structure of the swap status region is illustrated below. In
843this figure, a min-write-size of 1 is assumed for simplicity.
844
David Brown17e20d12017-09-12 11:53:20 -0600845```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800846 0 1 2 3
847 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
848 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
849 |sec127,state 0 |sec127,state 1 |sec127,state 2 |sec126,state 0 |
850 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
851 |sec126,state 1 |sec126,state 2 |sec125,state 0 |sec125,state 1 |
852 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
853 |sec125,state 2 | |
854 +-+-+-+-+-+-+-+-+ +
855 ~ ~
856 ~ [Records for indices 124 through 1 ~
857 ~ ~
858 ~ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
859 ~ |sec000,state 0 |sec000,state 1 |sec000,state 2 |
860 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
David Brown17e20d12017-09-12 11:53:20 -0600861```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800862
863The above is probably not helpful at all; here is a description in English.
864
865Each image slot is partitioned into a sequence of flash sectors. If we were to
866enumerate the sectors in a single slot, starting at 0, we would have a list of
867sector indices. Since there are two image slots, each sector index would
868correspond to a pair of sectors. For example, sector index 0 corresponds to
David Vincze2d736ad2019-02-18 11:50:22 +0100869the first sector in the primary slot and the first sector in the secondary slot.
870Finally, reverse the list of indices such that the list starts with index
871`BOOT_MAX_IMG_SECTORS - 1` and ends with 0. The swap status region is a
872representation of this reversed list.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800873
874During a swap operation, each sector index transitions through four separate
875states:
David Brown17e20d12017-09-12 11:53:20 -0600876```
David Vincze2d736ad2019-02-18 11:50:22 +01008770. primary slot: image 0, secondary slot: image 1, scratch: N/A
8781. primary slot: image 0, secondary slot: N/A, scratch: image 1 (1->s, erase 1)
8792. primary slot: N/A, secondary slot: image 0, scratch: image 1 (0->1, erase 0)
8803. primary slot: image 1, secondary slot: image 0, scratch: N/A (s->0)
David Brown17e20d12017-09-12 11:53:20 -0600881```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800882
883Each time a sector index transitions to a new state, the boot loader writes a
884record to the swap status region. Logically, the boot loader only needs one
885record per sector index to keep track of the current swap state. However, due
886to limitations imposed by flash hardware, a record cannot be overwritten when
887an index's state changes. To solve this problem, the boot loader uses three
888records per sector index rather than just one.
889
890Each sector-state pair is represented as a set of three records. The record
891values map to the above four states as follows
892
David Brown17e20d12017-09-12 11:53:20 -0600893```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800894 | rec0 | rec1 | rec2
895 --------+------+------+------
896 state 0 | 0xff | 0xff | 0xff
897 state 1 | 0x01 | 0xff | 0xff
898 state 2 | 0x01 | 0x02 | 0xff
899 state 3 | 0x01 | 0x02 | 0x03
David Brown17e20d12017-09-12 11:53:20 -0600900```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800901
Fabio Utzig2c05f1b2018-04-04 10:35:17 -0300902The swap status region can accommodate `BOOT_MAX_IMG_SECTORS` sector indices.
David Vincze2d736ad2019-02-18 11:50:22 +0100903Hence, the size of the region, in bytes, is
904`BOOT_MAX_IMG_SECTORS * min-write-size * 3`. The only requirement for the index
905count is that it is great enough to account for a maximum-sized image
906(i.e., at least as great as the total sector count in an image slot). If a
907device's image slots have been configured with `BOOT_MAX_IMG_SECTORS: 128` and
908use less than 128 sectors, the first record that gets written will be somewhere
909in the middle of the region. For example, if a slot uses 64 sectors, the first
910sector index that gets swapped is 63, which corresponds to the exact halfway
911point within the region.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800912
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300913Note: since the scratch area only ever needs to record swapping of the last
914sector, it uses at most min-write-size * 3 bytes for its own status area.
915
Fabio Utzigd37d8772019-12-03 10:32:18 -0300916## [Reset Recovery](#reset-recovery)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800917
918If the boot loader resets in the middle of a swap operation, the two images may
919be discontiguous in flash. Bootutil recovers from this condition by using the
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300920image trailers to determine how the image parts are distributed in flash.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800921
922The first step is determine where the relevant swap status region is located.
923Because this region is embedded within the image slots, its location in flash
Fabio Utzig86fe4b22017-07-28 18:56:29 -0300924changes during a swap operation. The below set of tables map image trailers
Christopher Collins92ea77f2016-12-12 15:59:26 -0800925contents to swap status location. In these tables, the "source" field
David Vinczeba3bd602019-06-17 16:01:43 +0200926indicates where the swap status region is located. In case of multi image boot
927the images primary area and the single scratch area is always examined in pairs.
928If swap status found on scratch area then it might not belong to the current
929image. The swap_info field of swap status stores the corresponding image number.
930If it does not match then "source: none" is returned.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800931
David Brown17e20d12017-09-12 11:53:20 -0600932```
David Vincze2d736ad2019-02-18 11:50:22 +0100933 | primary slot | scratch |
934 ----------+--------------+--------------|
935 magic | Good | Any |
936 copy-done | 0x01 | N/A |
937 ----------+--------------+--------------'
938 source: none |
939 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -0400940
David Vincze2d736ad2019-02-18 11:50:22 +0100941 | primary slot | scratch |
942 ----------+--------------+--------------|
943 magic | Good | Any |
944 copy-done | 0xff | N/A |
945 ----------+--------------+--------------'
946 source: primary slot |
947 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -0400948
David Vincze2d736ad2019-02-18 11:50:22 +0100949 | primary slot | scratch |
950 ----------+--------------+--------------|
951 magic | Any | Good |
952 copy-done | Any | N/A |
953 ----------+--------------+--------------'
954 source: scratch |
955 ----------------------------------------'
Marti Bolivar49b29172017-08-04 14:50:51 -0400956
David Vincze2d736ad2019-02-18 11:50:22 +0100957 | primary slot | scratch |
958 ----------+--------------+--------------|
959 magic | Unset | Any |
960 copy-done | 0xff | N/A |
961 ----------+--------------+--------------|
962 source: primary slot |
963 ----------------------------------------+------------------------------+
964 This represents one of two cases: |
965 o No swaps ever (no status to read, so no harm in checking). |
966 o Mid-revert; status in the primary slot. |
967 For this reason we assume the primary slot as source, to trigger a |
968 check of the status area and find out if there was swapping under way. |
969 -----------------------------------------------------------------------'
David Brown17e20d12017-09-12 11:53:20 -0600970```
Christopher Collins92ea77f2016-12-12 15:59:26 -0800971
Christopher Collinsa1c12042019-05-23 14:00:28 -0700972If the swap status region indicates that the images are not contiguous, mcuboot
973determines the type of swap operation that was interrupted by reading the `swap
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +0000974info` field in the active image trailer and extracting the swap type from bits
David Vinczee2453472019-06-17 12:31:59 +02009750-3 then resumes the operation. In other words, it applies the procedure defined
976in the previous section, moving image 1 into the primary slot and image 0 into
977the secondary slot. If the boot status indicates that an image part is present
978in the scratch area, this part is copied into the correct location by starting
979at step e or step h in the area-swap procedure, depending on whether the part
980belongs to image 0 or image 1.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800981
982After the swap operation has been completed, the boot loader proceeds as though
983it had just been started.
984
Fabio Utzigd37d8772019-12-03 10:32:18 -0300985## [Integrity Check](#integrity-check)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800986
987An image is checked for integrity immediately before it gets copied into the
Fabio Utzig5bd4e582017-07-20 08:55:38 -0300988primary slot. If the boot loader doesn't perform an image swap, then it can
David Vincze2d736ad2019-02-18 11:50:22 +0100989perform an optional integrity check of the image in the primary slot if
990`MCUBOOT_VALIDATE_PRIMARY_SLOT` is set, otherwise it doesn't perform an
991integrity check.
Christopher Collins92ea77f2016-12-12 15:59:26 -0800992
993During the integrity check, the boot loader verifies the following aspects of
994an image:
Fabio Utzig75b34412019-09-06 08:30:43 -0300995
Fabio Utzigfd140ec2019-09-12 14:37:48 -0300996 * 32-bit magic number must be correct (`IMAGE_MAGIC`).
Fabio Utzig75b34412019-09-06 08:30:43 -0300997 * Image must contain an `image_tlv_info` struct, identified by its magic
Fabio Utzigfd140ec2019-09-12 14:37:48 -0300998 (`IMAGE_TLV_PROT_INFO_MAGIC` or `IMAGE_TLV_INFO_MAGIC`) exactly following
999 the firmware (`hdr_size` + `img_size`). If `IMAGE_TLV_PROT_INFO_MAGIC` is
1000 found then after `ih_protect_tlv_size` bytes, another `image_tlv_info`
1001 with magic equal to `IMAGE_TLV_INFO_MAGIC` must be present.
Fabio Utzig75b34412019-09-06 08:30:43 -03001002 * Image must contain a SHA256 TLV.
1003 * Calculated SHA256 must match SHA256 TLV contents.
1004 * Image *may* contain a signature TLV. If it does, it must also have a
1005 KEYHASH TLV with the hash of the key that was used to sign. The list of
1006 keys will then be iterated over looking for the matching key, which then
1007 will then be used to verify the image contents.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001008
Fabio Utzigd37d8772019-12-03 10:32:18 -03001009## [Security](#security)
Christopher Collins92ea77f2016-12-12 15:59:26 -08001010
1011As indicated above, the final step of the integrity check is signature
1012verification. The boot loader can have one or more public keys embedded in it
1013at build time. During signature verification, the boot loader verifies that an
Håkon Øye Amundsencbf30472019-07-24 08:34:03 +00001014image was signed with a private key that corresponds to the embedded KEYHASH
Fabio Utzigea422c22017-09-11 11:02:47 -03001015TLV.
Christopher Collins92ea77f2016-12-12 15:59:26 -08001016
1017For information on embedding public keys in the boot loader, as well as
Fabio Utzig4dce6aa2018-02-12 15:31:32 -02001018producing signed images, see: [signed_images](signed_images.md).
Fabio Utzigcdfa11a2018-10-01 09:45:54 -03001019
1020If you want to enable and use encrypted images, see:
1021[encrypted_images](encrypted_images.md).
David Vinczee32483f2019-06-13 10:46:24 +02001022
Tamas Banfe031092020-09-10 17:32:39 +02001023Note: Image encryption is not supported when the direct-xip or the ram-load
1024upgrade strategy is selected.
David Vinczee574f2d2020-07-10 11:42:03 +02001025
David Vincze25459bf2020-04-21 17:11:20 +02001026### [Using Hardware Keys for Verification](#hw-key-support)
1027
1028By default, the whole public key is embedded in the bootloader code and its
1029hash is added to the image manifest as a KEYHASH TLV entry. As an alternative
1030the bootloader can be made independent of the keys by setting the
1031`MCUBOOT_HW_KEY` option. In this case the hash of the public key must be
1032provisioned to the target device and mcuboot must be able to retrieve the
1033key-hash from there. For this reason the target must provide a definition
1034for the `boot_retrieve_public_key_hash()` function which is declared in
1035`boot/bootutil/include/bootutil/sign_key.h`. It is also required to use
1036the `full` option for the `--public-key-format` imgtool argument in order to
1037add the whole public key (PUBKEY TLV) to the image manifest instead of its
1038hash (KEYHASH TLV). During boot the public key is validated before using it for
1039signature verification, mcuboot calculates the hash of the public key from the
1040TLV area and compares it with the key-hash that was retrieved from the device.
1041This way mcuboot is independent from the public key(s). The key(s) can be
1042provisioned any time and by different parties.
1043
Fabio Utzigd37d8772019-12-03 10:32:18 -03001044## [Protected TLVs](#protected-tlvs)
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001045
1046If the TLV area contains protected TLV entries, by beginning with a `struct
1047image_tlv_info` with a magic value of `IMAGE_TLV_PROT_INFO_MAGIC` then the
1048data of those TLVs must also be integrity and authenticity protected. Beyond
1049the full size of the protected TLVs being stored in the `image_tlv_info`,
1050the size of the protected TLVs together with the size of the `image_tlv_info`
1051struct itself are also saved in the `ih_protected_size` field inside the
1052header.
1053
1054Whenever an image has protected TLVs the SHA256 has to be calculated over
1055not just the image header and the image but also the TLV info header and the
1056protected TLVs.
1057
1058```
1059A +---------------------+
1060 | Header | <- struct image_header
1061 +---------------------+
1062 | Payload |
1063 +---------------------+
1064 | TLV area |
1065 | +-----------------+ | struct image_tlv_info with
1066 | | TLV area header | | <- IMAGE_TLV_PROT_INFO_MAGIC (optional)
1067 | +-----------------+ |
1068 | | Protected TLVs | | <- Protected TLVs (struct image_tlv)
1069B | +-----------------+ |
1070 | | TLV area header | | <- struct image_tlv_info with IMAGE_TLV_INFO_MAGIC
1071C | +-----------------+ |
1072 | | SHA256 hash | | <- hash from A - B (struct image_tlv)
1073D | +-----------------+ |
1074 | | Keyhash | | <- indicates which pub. key for sig (struct image_tlv)
1075 | +-----------------+ |
1076 | | Signature | | <- signature from C - D (struct image_tlv), only hash
1077 | +-----------------+ |
1078 +---------------------+
1079```
1080
Fabio Utzigd37d8772019-12-03 10:32:18 -03001081## [Dependency Check](#dependency-check)
David Vinczee32483f2019-06-13 10:46:24 +02001082
1083MCUBoot can handle multiple firmware images. It is possible to update them
1084independently but in many cases it can be desired to be able to describe
1085dependencies between the images (e.g. to ensure API compliance and avoid
1086interoperability issues).
1087
1088The dependencies between images can be described with additional TLV entries in
Fabio Utzigfd140ec2019-09-12 14:37:48 -03001089the protected TLV area after the end of an image. There can be more than one
1090dependency entry, but in practice if the platform only supports two individual
1091images then there can be maximum one entry which reflects to the other image.
David Vinczee32483f2019-06-13 10:46:24 +02001092
David Vinczee32483f2019-06-13 10:46:24 +02001093At the phase of dependency check all aborted swaps are finalized if there were
1094any. During the dependency check the boot loader verifies whether the image
1095dependencies are all satisfied. If at least one of the dependencies of an image
1096is not fulfilled then the swap type of that image has to be modified
1097accordingly and the dependency check needs to be restarted. This way the number
1098of unsatisfied dependencies will decrease or remain the same. There is always at
1099least 1 valid configuration. In worst case, the system returns to the initial
1100state after dependency check.
1101
1102For more information on adding dependency entries to an image,
1103see: [imgtool](imgtool.md).
Håkon Øye Amundsen2d1bac12020-01-03 13:08:09 +00001104
1105## [Downgrade Prevention](#downgrade-prevention)
1106
1107Downgrade prevention is a feature which enforces that the new image must have a
David Vinczec3084132020-02-18 14:50:47 +01001108higher version/security counter number than the image it is replacing, thus
1109preventing the malicious downgrading of the device to an older and possibly
1110vulnerable version of its firmware.
1111
1112### [SW Based Downgrade Prevention](#sw-downgrade-prevention)
1113
1114During the software based downgrade prevention the image version numbers are
1115compared. This feature is enabled with the `MCUBOOT_DOWNGRADE_PREVENTION`
1116option. In this case downgrade prevention is only available when the
1117overwrite-based image update strategy is used (i.e. `MCUBOOT_OVERWRITE_ONLY`
1118is set).
1119
1120### [HW Based Downgrade Prevention](#hw-downgrade-prevention)
1121
David Vincze25459bf2020-04-21 17:11:20 +02001122Each signed image can contain a security counter in its protected TLV area, which
1123can be added to the image using the `-s` option of the [imgtool](imgtool.md) script.
David Vinczec3084132020-02-18 14:50:47 +01001124During the hardware based downgrade prevention (alias rollback protection) the
1125new image's security counter will be compared with the currently active security
1126counter value which must be stored in a non-volatile and trusted component of
David Vincze25459bf2020-04-21 17:11:20 +02001127the device. It is beneficial to handle this counter independently from image
1128version number:
David Vinczec3084132020-02-18 14:50:47 +01001129
1130 * It does not need to increase with each software release,
1131 * It makes it possible to do software downgrade to some extent: if the
1132 security counter has the same value in the older image then it is accepted.
David Vincze25459bf2020-04-21 17:11:20 +02001133
1134It is an optional step of the image validation process and can be enabled with
1135the `MCUBOOT_HW_ROLLBACK_PROT` config option. When enabled, the target must
1136provide an implementation of the security counter interface defined in
1137`boot/bootutil/include/security_cnt.h`.
1138
1139## [Measured boot and data sharing](#boot-data-sharing)
1140
1141MCUBoot defines a mechanism for sharing boot status information (also known as
1142measured boot) and an interface for sharing application specific information
1143with the runtime software. If any of these are enabled the target must provide
1144a shared data area between the bootloader and runtime firmware and define the
1145following parameters:
1146
1147```c
1148#define MCUBOOT_SHARED_DATA_BASE <area_base_addr>
1149#define MCUBOOT_SHARED_DATA_SIZE <area_size_in_bytes>
1150```
1151
1152In the shared memory area all data entries are stored in a type-length-value
1153(TLV) format. Before adding the first data entry, the whole area is overwritten
1154with zeros and a TLV header is added at the beginning of the area during an
1155initialization phase. This TLV header contains a `tlv_magic` field with a value
1156of `SHARED_DATA_TLV_INFO_MAGIC` and a `tlv_tot_len` field which is indicating
1157the total length of shared TLV area including this header. The header is
1158followed by the the data TLV entries which are composed from a
1159`shared_data_tlv_entry` header and the data itself. In the data header there is
1160a `tlv_type` field which identifies the consumer of the entry (in the runtime
1161software) and specifies the subtype of that data item. More information about
1162the `tlv_type` field and data types can be found in the
1163`boot/bootutil/include/bootutil/boot_status.h` file. The type is followed by a
1164`tlv_len` field which indicates the size of the data entry in bytes, not
1165including the entry header. After this header structure comes the actual data.
1166
1167```c
1168/** Shared data TLV header. All fields in little endian. */
1169struct shared_data_tlv_header {
1170 uint16_t tlv_magic;
1171 uint16_t tlv_tot_len; /* size of whole TLV area (including this header) */
1172};
1173
1174/** Shared data TLV entry header format. All fields in little endian. */
1175struct shared_data_tlv_entry {
1176 uint16_t tlv_type;
1177 uint16_t tlv_len; /* TLV data length (not including this header). */
1178};
1179```
1180
1181The measured boot can be enabled with the `MCUBOOT_MEASURED_BOOT` config option.
1182When enabled, the `--boot_record` argument of the imgtool script must also be
1183used during the image signing process to add a BOOT_RECORD TLV to the image
1184manifest. This TLV contains the following attributes/measurements of the
1185image in CBOR encoded format:
1186
1187 * Software type (role of the software component)
1188 * Software version
1189 * Signer ID (identifies the signing authority)
1190 * Measurement value (hash of the image)
1191 * Measurement type (algorithm used to calculate the measurement value)
1192
1193The `sw_type` string that is passed as the `--boot_record` option's parameter
1194will be the value of the "Software type" attribute in the generated BOOT_RECORD
1195TLV. The target must also define the `MAX_BOOT_RECORD_SZ` macro which indicates
1196the maximum size of the CBOR encoded boot record in bytes.
1197During boot, MCUBoot will look for these TLVs (in case of multiple images) in
1198the manifests of the active images (the latest and validated) and copy the CBOR
1199encoded binary data to the shared data area. Preserving all these image
1200attributes from the boot stage for use by later runtime services (such as an
1201attestation service) is known as a measured boot.
1202
1203Setting the `MCUBOOT_DATA_SHARING` option enables the sharing of application
1204specific data using the same shared data area as for the measured boot. For
1205this, the target must provide a definition for the `boot_save_shared_data()`
1206function which is declared in `boot/bootutil/include/bootutil/boot_record.h`.
1207The `boot_add_data_to_shared_area()` function can be used for adding new TLV
1208entries to the shared data area.
Mate Toth-Palcbf9d392020-11-09 16:47:49 +01001209
1210## [Testing in CI](#testing-in-ci)
1211
1212### [Testing Fault Injection Hardening (FIH)](#testing-fih)
1213
1214The CI currently tests the Fault Injection Hardening feature of MCUboot by
1215executing instruction skip during execution, and looking at whether a corrupted
1216image was booted by the bootloader or not.
1217
1218The main idea is that instruction skipping can be automated by scripting a
1219debugger to automatically execute the following steps:
1220
1221- Set breakpoint at specified address.
1222- Continue execution.
1223- On breakpoint hit increase the Program Counter.
1224- Continue execution.
1225- Detach from target after a timeout reached.
1226
1227Whether or not the corrupted image was booted or not can be decided by looking
1228for certain entries in the log.
1229
1230As MCUboot is deployed on a microcontroller, testing FI would not make much
1231sense in the simulator environment running on a host machine with different
1232architecture than the MCU's, as the degree of hardening depends on compiler
1233behavior. For example, (a bit counterintuitively) the code produced by gcc
1234with `-O0` optimisation is more resilient against FI attacks than the code
1235generated with `-O3` or `-Os` optimizations.
1236
1237To run on a desired architecture in the CI, the tests need to be executed on an
1238emulator (as real devices are not available in the CI environment). For this
1239implementation QEMU is selected.
1240
1241For the tests MCUboot needs a set of drivers and an implementation of a main
1242function. For the purpose of this test Trusted-Firmware-M has been selected as
1243it supports Armv8-M platforms that are also emulated by QEMU.
1244
1245The tests run in a docker container inside the CI VMs, to make it more easy to
1246deploy build and test environment (QEMU, compilers, interpreters). The CI VMs
1247seems to be using quite old Ubuntu (16.04).
1248
1249The sequence of the testing is the following (pseudo code):
1250
1251```sh
1252fn main()
1253 # Implemented in ci/fih-tests_install.sh
1254 generate_docker_image(Dockerfile)
1255
1256 # See details below. Implemented in ci/fih-tests_run.sh.
1257 # Calling the function with different parameters is done by Travis CI based on
1258 # the values provided in the .travis.yaml
1259 start_docker_image(skip_sizes, build_type, damage_type, fih_level)
1260
1261fn start_docker_image(skip_sizes, build_type, damage_type, fih_level)
1262 # implemented in ci/fih_test_docker/execute_test.sh
1263 compile_mcuboot(build_type)
1264
1265 # implemented in ci/fih_test_docker/damage_image.py
1266 damage_image(damage_type)
1267
1268 # implemented in ci/fih_test_docker/run_fi_test.sh
1269 ranges = generate_address_ranges()
1270 for s in skip_sizes
1271 for r in ranges
1272 do_skip_in_qemu(s, r) # See details below
1273 evaluate_logs()
1274
1275fn do_skip_in_qemu(size, range)
1276 for a in r
1277 run_qemu(a, size) # See details below
1278
1279# this part is implemented in ci/fih_test_docker/fi_tester_gdb.sh
1280fn run_qemu(a, size)
1281 script = create_debugger_script(a, size)
1282 start_qemu_in_bacground() # logs serial out to a file
1283 gdb_attach_to_qemu(script)
1284 kill_qemu()
1285
1286 # This checks the debugger and the quemu logs, and decides whether the tets
1287 # was executed successfully, and whether the image is booted or not. Then
1288 # emits a yaml fragment on the standard out to be processed by the caller
1289 # script
1290 evaluate_run(qemu_log_file)
1291```
1292
1293Further notes:
1294
1295- The image is corrupted by changing its signature.
1296- MCUBOOT_FIH_PROFILE_MAX is not tested as it requires TRNG, and the AN521
1297platform has no support for it. However this profile adds the random
1298execution delay to the code, so should not affect the instruction skip results
1299too much, because break point is placed at exact address. But in practice this
1300makes harder the accurate timing of the attack.
1301- The test cases defined in .travis.yml always return `passed`, if they were
1302executed successfully. A yaml file is created during test execution with the
1303details of the test execution results. A summary of the collected results is
1304printed in the log at the end of the test.
1305
1306An advantage of having the tests running in a docker image is that it is
1307possible to run the tests on a local machine that has git and docker, without
1308installing any additional software.
1309
1310So, running the test on the host looks like the following (The commands below
1311are issued from the MCUboot source directory):
1312
1313```sh
1314$ ./ci/fih-tests_install.sh
1315$ FIH_LEVEL=MCUBOOT_FIH_PROFILE_MEDIUM BUILD_TYPE=RELEASE SKIP_SIZE=2 \
1316 DAMAGE_TYPE=SIGNATURE ./ci/fih-tests_run.sh
1317```
1318On the travis CI the environment variables in the last command are set based on
1319the configs provided in the `.travis.yaml`
1320
1321This starts the tests, however the shell that it is running in is not
1322interactive, it is not possible to examine the results of the test run. To have
1323an interactive shell where the results can be examined, the following can be
1324done:
1325
1326- The docker image needs to be built with `ci/fih-tests_install.sh` as described
1327 above.
1328- Start the docker image with the following command:
1329 `docker run -i -t mcuboot/fih-test`.
1330- Execute the test with a command similar to the following:
1331 `/root/execute_test.sh 8 RELEASE SIGNATURE MEDIUM`. After the test finishes,
1332 the shell returns, and it is possible to investigate the results. It is also
1333 possible to stop the test with _Ctrl+c_. The parameters to the
1334 `execute_test.sh` are `SKIP_SIZE`, `BUILD_TYPE`, `DAMAGE_TYPE`, `FIH_LEVEL` in
Salome Thirot0f641972021-05-14 11:19:55 +01001335 order.