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