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-2021 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 #ifndef H_BOOTUTIL_PRIV_
29 #define H_BOOTUTIL_PRIV_
30 
31 #include <string.h>
32 
33 #include "sysflash/sysflash.h"
34 
35 #include <flash_map_backend/flash_map_backend.h>
36 
37 #include "bootutil/bootutil.h"
38 #include "bootutil/image.h"
39 #include "bootutil/fault_injection_hardening.h"
40 #include "mcuboot_config/mcuboot_config.h"
41 
42 #ifdef MCUBOOT_ENC_IMAGES
43 #include "bootutil/enc_key.h"
44 #endif
45 
46 #ifdef __cplusplus
47 extern "C" {
48 #endif
49 
50 struct flash_area;
51 
52 #define BOOT_TMPBUF_SZ  256
53 
54 /** Number of image slots in flash; currently limited to two. */
55 #define BOOT_NUM_SLOTS                  2
56 
57 #if (defined(MCUBOOT_OVERWRITE_ONLY) + \
58      defined(MCUBOOT_SWAP_USING_MOVE) + \
59      defined(MCUBOOT_DIRECT_XIP) + \
60      defined(MCUBOOT_RAM_LOAD) + \
61      defined(MCUBOOT_FIRMWARE_LOADER)) > 1
62 #error "Please enable only one of MCUBOOT_OVERWRITE_ONLY, MCUBOOT_SWAP_USING_MOVE, MCUBOOT_DIRECT_XIP, MCUBOOT_RAM_LOAD or MCUBOOT_FIRMWARE_LOADER"
63 #endif
64 
65 #if !defined(MCUBOOT_OVERWRITE_ONLY) && \
66     !defined(MCUBOOT_SWAP_USING_MOVE) && \
67     !defined(MCUBOOT_DIRECT_XIP) && \
68     !defined(MCUBOOT_RAM_LOAD) && \
69     !defined(MCUBOOT_SINGLE_APPLICATION_SLOT) && \
70     !defined(MCUBOOT_FIRMWARE_LOADER)
71 #define MCUBOOT_SWAP_USING_SCRATCH 1
72 #endif
73 
74 #define BOOT_STATUS_OP_MOVE     1
75 #define BOOT_STATUS_OP_SWAP     2
76 
77 /*
78  * Maintain state of copy progress.
79  */
80 struct boot_status {
81     uint32_t idx;         /* Which area we're operating on */
82     uint8_t state;        /* Which part of the swapping process are we at */
83     uint8_t op;           /* What operation are we performing? */
84     uint8_t use_scratch;  /* Are status bytes ever written to scratch? */
85     uint8_t swap_type;    /* The type of swap in effect */
86     uint32_t swap_size;   /* Total size of swapped image */
87 #ifdef MCUBOOT_ENC_IMAGES
88     uint8_t enckey[BOOT_NUM_SLOTS][BOOT_ENC_KEY_ALIGN_SIZE];
89 #if MCUBOOT_SWAP_SAVE_ENCTLV
90     uint8_t enctlv[BOOT_NUM_SLOTS][BOOT_ENC_TLV_ALIGN_SIZE];
91 #endif
92 #endif
93     int source;           /* Which slot contains swap status metadata */
94 };
95 
96 #define BOOT_STATUS_IDX_0   1
97 
98 #define BOOT_STATUS_STATE_0 1
99 #define BOOT_STATUS_STATE_1 2
100 #define BOOT_STATUS_STATE_2 3
101 
102 /**
103  * End-of-image slot structure.
104  *
105  *   0                   1                   2                   3
106  *   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
107  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
108  *  ~                                                               ~
109  *  ~    Swap status (BOOT_MAX_IMG_SECTORS * min-write-size * 3)    ~
110  *  ~                                                               ~
111  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
112  *  |                 Encryption key 0 (16 octets) [*]              |
113  *  |                                                               |
114  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
115  *  |                    0xff padding as needed                     |
116  *  |  (BOOT_MAX_ALIGN minus 16 octets from Encryption key 0) [*]   |
117  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
118  *  |                 Encryption key 1 (16 octets) [*]              |
119  *  |                                                               |
120  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
121  *  |                    0xff padding as needed                     |
122  *  |  (BOOT_MAX_ALIGN minus 16 octets from Encryption key 1) [*]   |
123  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
124  *  |                      Swap size (4 octets)                     |
125  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
126  *  |                    0xff padding as needed                     |
127  *  |        (BOOT_MAX_ALIGN minus 4 octets from Swap size)         |
128  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
129  *  |   Swap info   |  0xff padding (BOOT_MAX_ALIGN minus 1 octet)  |
130  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
131  *  |   Copy done   |  0xff padding (BOOT_MAX_ALIGN minus 1 octet)  |
132  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
133  *  |   Image OK    |  0xff padding (BOOT_MAX_ALIGN minus 1 octet)  |
134  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
135  *  |                    0xff padding as needed                     |
136  *  |         (BOOT_MAX_ALIGN minus 16 octets from MAGIC)           |
137  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
138  *  |                       MAGIC (16 octets)                       |
139  *  |                                                               |
140  *  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
141  *
142  * [*]: Only present if the encryption option is enabled
143  *      (`MCUBOOT_ENC_IMAGES`).
144  */
145 
146 union boot_img_magic_t
147 {
148     struct {
149         uint16_t align;
150         uint8_t magic[14];
151     };
152     uint8_t val[16];
153 };
154 
155 extern const union boot_img_magic_t boot_img_magic;
156 
157 #define BOOT_IMG_MAGIC  (boot_img_magic.val)
158 
159 #if BOOT_MAX_ALIGN == 8
160 #define BOOT_IMG_ALIGN  (BOOT_MAX_ALIGN)
161 #else
162 #define BOOT_IMG_ALIGN  (boot_img_magic.align)
163 #endif
164 
165 _Static_assert(sizeof(boot_img_magic) == BOOT_MAGIC_SZ, "Invalid size for image magic");
166 
167 #if !defined(MCUBOOT_DIRECT_XIP) && !defined(MCUBOOT_RAM_LOAD)
168 #define ARE_SLOTS_EQUIVALENT()    0
169 #else
170 #define ARE_SLOTS_EQUIVALENT()    1
171 
172 #if defined(MCUBOOT_DIRECT_XIP) && defined(MCUBOOT_ENC_IMAGES)
173 #error "Image encryption (MCUBOOT_ENC_IMAGES) is not supported when MCUBOOT_DIRECT_XIP is selected."
174 #endif /* MCUBOOT_DIRECT_XIP && MCUBOOT_ENC_IMAGES */
175 #endif /* MCUBOOT_DIRECT_XIP || MCUBOOT_RAM_LOAD */
176 
177 #define BOOT_MAX_IMG_SECTORS       MCUBOOT_MAX_IMG_SECTORS
178 
179 #define BOOT_LOG_IMAGE_INFO(slot, hdr)                                    \
180     BOOT_LOG_INF("%-9s slot: version=%u.%u.%u+%u",                        \
181                  ((slot) == BOOT_PRIMARY_SLOT) ? "Primary" : "Secondary", \
182                  (hdr)->ih_ver.iv_major,                                  \
183                  (hdr)->ih_ver.iv_minor,                                  \
184                  (hdr)->ih_ver.iv_revision,                               \
185                  (hdr)->ih_ver.iv_build_num)
186 
187 #if MCUBOOT_SWAP_USING_MOVE
188 #define BOOT_STATUS_MOVE_STATE_COUNT    1
189 #define BOOT_STATUS_SWAP_STATE_COUNT    2
190 #define BOOT_STATUS_STATE_COUNT         (BOOT_STATUS_MOVE_STATE_COUNT + BOOT_STATUS_SWAP_STATE_COUNT)
191 #else
192 #define BOOT_STATUS_STATE_COUNT         3
193 #endif
194 
195 /** Maximum number of image sectors supported by the bootloader. */
196 #define BOOT_STATUS_MAX_ENTRIES         BOOT_MAX_IMG_SECTORS
197 
198 #define BOOT_PRIMARY_SLOT               0
199 #define BOOT_SECONDARY_SLOT             1
200 
201 #define BOOT_STATUS_SOURCE_NONE         0
202 #define BOOT_STATUS_SOURCE_SCRATCH      1
203 #define BOOT_STATUS_SOURCE_PRIMARY_SLOT 2
204 
205 /**
206  * Compatibility shim for flash sector type.
207  *
208  * This can be deleted when flash_area_to_sectors() is removed.
209  */
210 #ifdef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
211 typedef struct flash_sector boot_sector_t;
212 #else
213 typedef struct flash_area boot_sector_t;
214 #endif
215 
216 /** Private state maintained during boot. */
217 struct boot_loader_state {
218     struct {
219         struct image_header hdr;
220         const struct flash_area *area;
221         boot_sector_t *sectors;
222         uint32_t num_sectors;
223     } imgs[BOOT_IMAGE_NUMBER][BOOT_NUM_SLOTS];
224 
225 #if MCUBOOT_SWAP_USING_SCRATCH
226     struct {
227         const struct flash_area *area;
228         boot_sector_t *sectors;
229         uint32_t num_sectors;
230     } scratch;
231 #endif
232 
233     uint8_t swap_type[BOOT_IMAGE_NUMBER];
234     uint32_t write_sz;
235 
236 #if defined(MCUBOOT_ENC_IMAGES)
237     struct enc_key_data enc[BOOT_IMAGE_NUMBER][BOOT_NUM_SLOTS];
238 #endif
239 
240 #if (BOOT_IMAGE_NUMBER > 1)
241     uint8_t curr_img_idx;
242     bool img_mask[BOOT_IMAGE_NUMBER];
243 #endif
244 
245 #if defined(MCUBOOT_DIRECT_XIP) || defined(MCUBOOT_RAM_LOAD)
246     struct slot_usage_t {
247         /* Index of the slot chosen to be loaded */
248         uint32_t active_slot;
249         bool slot_available[BOOT_NUM_SLOTS];
250 #if defined(MCUBOOT_RAM_LOAD)
251         /* Image destination and size for the active slot */
252         uint32_t img_dst;
253         uint32_t img_sz;
254 #elif defined(MCUBOOT_DIRECT_XIP_REVERT)
255         /* Swap status for the active slot */
256         struct boot_swap_state swap_state;
257 #endif
258     } slot_usage[BOOT_IMAGE_NUMBER];
259 #endif /* MCUBOOT_DIRECT_XIP || MCUBOOT_RAM_LOAD */
260 };
261 
262 fih_ret bootutil_verify_sig(uint8_t *hash, uint32_t hlen, uint8_t *sig,
263                             size_t slen, uint8_t key_id);
264 
265 fih_ret boot_fih_memequal(const void *s1, const void *s2, size_t n);
266 
267 int boot_find_status(int image_index, const struct flash_area **fap);
268 int boot_magic_compatible_check(uint8_t tbl_val, uint8_t val);
269 uint32_t boot_status_sz(uint32_t min_write_sz);
270 uint32_t boot_trailer_sz(uint32_t min_write_sz);
271 int boot_status_entries(int image_index, const struct flash_area *fap);
272 uint32_t boot_status_off(const struct flash_area *fap);
273 int boot_read_swap_state(const struct flash_area *fap,
274                          struct boot_swap_state *state);
275 int boot_read_swap_state_by_id(int flash_area_id,
276                                struct boot_swap_state *state);
277 int boot_write_magic(const struct flash_area *fap);
278 int boot_write_status(const struct boot_loader_state *state, struct boot_status *bs);
279 int boot_write_copy_done(const struct flash_area *fap);
280 int boot_write_image_ok(const struct flash_area *fap);
281 int boot_write_swap_info(const struct flash_area *fap, uint8_t swap_type,
282                          uint8_t image_num);
283 int boot_write_swap_size(const struct flash_area *fap, uint32_t swap_size);
284 int boot_write_trailer(const struct flash_area *fap, uint32_t off,
285                        const uint8_t *inbuf, uint8_t inlen);
286 int boot_write_trailer_flag(const struct flash_area *fap, uint32_t off,
287                             uint8_t flag_val);
288 int boot_read_swap_size(const struct flash_area *fap, uint32_t *swap_size);
289 int boot_slots_compatible(struct boot_loader_state *state);
290 uint32_t boot_status_internal_off(const struct boot_status *bs, int elem_sz);
291 int boot_read_image_header(struct boot_loader_state *state, int slot,
292                            struct image_header *out_hdr, struct boot_status *bs);
293 int boot_copy_region(struct boot_loader_state *state,
294                      const struct flash_area *fap_src,
295                      const struct flash_area *fap_dst,
296                      uint32_t off_src, uint32_t off_dst, uint32_t sz);
297 int boot_erase_region(const struct flash_area *fap, uint32_t off, uint32_t sz);
298 bool boot_status_is_reset(const struct boot_status *bs);
299 
300 #ifdef MCUBOOT_ENC_IMAGES
301 int boot_write_enc_key(const struct flash_area *fap, uint8_t slot,
302                        const struct boot_status *bs);
303 int boot_read_enc_key(const struct flash_area *fap, uint8_t slot,
304                       struct boot_status *bs);
305 #endif
306 
307 /**
308  * Checks that a buffer is erased according to what the erase value for the
309  * flash device provided in `flash_area` is.
310  *
311  * @returns true if the buffer is erased; false if any of the bytes is not
312  * erased, or when buffer is NULL, or when len == 0.
313  */
314 bool bootutil_buffer_is_erased(const struct flash_area *area,
315                                const void *buffer, size_t len);
316 
317 /**
318  * Safe (non-overflowing) uint32_t addition.  Returns true, and stores
319  * the result in *dest if it can be done without overflow.  Otherwise,
320  * returns false.
321  */
boot_u32_safe_add(uint32_t * dest,uint32_t a,uint32_t b)322 static inline bool boot_u32_safe_add(uint32_t *dest, uint32_t a, uint32_t b)
323 {
324     /*
325      * "a + b <= UINT32_MAX", subtract 'b' from both sides to avoid
326      * the overflow.
327      */
328     if (a > UINT32_MAX - b) {
329         return false;
330     } else {
331         *dest = a + b;
332         return true;
333     }
334 }
335 
336 /**
337  * Safe (non-overflowing) uint16_t addition.  Returns true, and stores
338  * the result in *dest if it can be done without overflow.  Otherwise,
339  * returns false.
340  */
boot_u16_safe_add(uint16_t * dest,uint16_t a,uint16_t b)341 static inline bool boot_u16_safe_add(uint16_t *dest, uint16_t a, uint16_t b)
342 {
343     uint32_t tmp = a + b;
344     if (tmp > UINT16_MAX) {
345         return false;
346     } else {
347         *dest = tmp;
348         return true;
349     }
350 }
351 
352 /*
353  * Accessors for the contents of struct boot_loader_state.
354  */
355 
356 /* These are macros so they can be used as lvalues. */
357 #if (BOOT_IMAGE_NUMBER > 1)
358 #define BOOT_CURR_IMG(state) ((state)->curr_img_idx)
359 #else
360 #define BOOT_CURR_IMG(state) 0
361 #endif
362 #ifdef MCUBOOT_ENC_IMAGES
363 #define BOOT_CURR_ENC(state) ((state)->enc[BOOT_CURR_IMG(state)])
364 #else
365 #define BOOT_CURR_ENC(state) NULL
366 #endif
367 #define BOOT_IMG(state, slot) ((state)->imgs[BOOT_CURR_IMG(state)][(slot)])
368 #define BOOT_IMG_AREA(state, slot) (BOOT_IMG(state, slot).area)
369 #define BOOT_WRITE_SZ(state) ((state)->write_sz)
370 #define BOOT_SWAP_TYPE(state) ((state)->swap_type[BOOT_CURR_IMG(state)])
371 #define BOOT_TLV_OFF(hdr) ((hdr)->ih_hdr_size + (hdr)->ih_img_size)
372 
373 #define BOOT_IS_UPGRADE(swap_type)             \
374     (((swap_type) == BOOT_SWAP_TYPE_TEST) ||   \
375      ((swap_type) == BOOT_SWAP_TYPE_REVERT) || \
376      ((swap_type) == BOOT_SWAP_TYPE_PERM))
377 
378 static inline struct image_header*
boot_img_hdr(struct boot_loader_state * state,size_t slot)379 boot_img_hdr(struct boot_loader_state *state, size_t slot)
380 {
381     return &BOOT_IMG(state, slot).hdr;
382 }
383 
384 static inline size_t
boot_img_num_sectors(const struct boot_loader_state * state,size_t slot)385 boot_img_num_sectors(const struct boot_loader_state *state, size_t slot)
386 {
387     return BOOT_IMG(state, slot).num_sectors;
388 }
389 
390 /*
391  * Offset of the slot from the beginning of the flash device.
392  */
393 static inline uint32_t
boot_img_slot_off(struct boot_loader_state * state,size_t slot)394 boot_img_slot_off(struct boot_loader_state *state, size_t slot)
395 {
396     return flash_area_get_off(BOOT_IMG(state, slot).area);
397 }
398 
399 #ifndef MCUBOOT_USE_FLASH_AREA_GET_SECTORS
400 
401 static inline size_t
boot_img_sector_size(const struct boot_loader_state * state,size_t slot,size_t sector)402 boot_img_sector_size(const struct boot_loader_state *state,
403                      size_t slot, size_t sector)
404 {
405     return flash_area_get_size(&BOOT_IMG(state, slot).sectors[sector]);
406 }
407 
408 /*
409  * Offset of the sector from the beginning of the image, NOT the flash
410  * device.
411  */
412 static inline uint32_t
boot_img_sector_off(const struct boot_loader_state * state,size_t slot,size_t sector)413 boot_img_sector_off(const struct boot_loader_state *state, size_t slot,
414                     size_t sector)
415 {
416     return flash_area_get_off(&BOOT_IMG(state, slot).sectors[sector]) -
417            flash_area_get_off(&BOOT_IMG(state, slot).sectors[0]);
418 }
419 
420 #else  /* defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
421 
422 static inline size_t
boot_img_sector_size(const struct boot_loader_state * state,size_t slot,size_t sector)423 boot_img_sector_size(const struct boot_loader_state *state,
424                      size_t slot, size_t sector)
425 {
426     return flash_sector_get_size(&BOOT_IMG(state, slot).sectors[sector]);
427 }
428 
429 static inline uint32_t
boot_img_sector_off(const struct boot_loader_state * state,size_t slot,size_t sector)430 boot_img_sector_off(const struct boot_loader_state *state, size_t slot,
431                     size_t sector)
432 {
433     return flash_sector_get_off(&BOOT_IMG(state, slot).sectors[sector]) -
434            flash_sector_get_off(&BOOT_IMG(state, slot).sectors[0]);
435 }
436 
437 #endif  /* !defined(MCUBOOT_USE_FLASH_AREA_GET_SECTORS) */
438 
439 #ifdef MCUBOOT_RAM_LOAD
440 #   ifdef __BOOTSIM__
441 
442 /* Query for the layout of a RAM buffer appropriate for holding the
443  * image.  This will be per-test-thread, and therefore must be queried
444  * through this call. */
445 struct bootsim_ram_info {
446     uint32_t start;
447     uint32_t size;
448     uintptr_t base;
449 };
450 struct bootsim_ram_info *bootsim_get_ram_info(void);
451 
452 #define IMAGE_GET_FIELD(field) (bootsim_get_ram_info()->field)
453 #define IMAGE_RAM_BASE IMAGE_GET_FIELD(base)
454 #define IMAGE_EXECUTABLE_RAM_START IMAGE_GET_FIELD(start)
455 #define IMAGE_EXECUTABLE_RAM_SIZE IMAGE_GET_FIELD(size)
456 
457 #   else
458 #       define IMAGE_RAM_BASE ((uintptr_t)0)
459 #   endif
460 
461 #define LOAD_IMAGE_DATA(hdr, fap, start, output, size)       \
462     (memcpy((output),(void*)(IMAGE_RAM_BASE + (hdr)->ih_load_addr + (start)), \
463     (size)), 0)
464 #else
465 #define IMAGE_RAM_BASE ((uintptr_t)0)
466 
467 #define LOAD_IMAGE_DATA(hdr, fap, start, output, size)       \
468     (flash_area_read((fap), (start), (output), (size)))
469 #endif /* MCUBOOT_RAM_LOAD */
470 
471 uint32_t bootutil_max_image_size(const struct flash_area *fap);
472 
473 #ifdef __cplusplus
474 }
475 #endif
476 
477 #endif
478