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