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