1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one
3  * or more contributor license agreements.  See the NOTICE file
4  * distributed with this work for additional information
5  * regarding copyright ownership.  The ASF licenses this file
6  * to you under the Apache License, Version 2.0 (the
7  * "License"); you may not use this file except in compliance
8  * with the License.  You may obtain a copy of the License at
9  *
10  *  http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing,
13  * software distributed under the License is distributed on an
14  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15  * KIND, either express or implied.  See the License for the
16  * specific language governing permissions and limitations
17  * under the License.
18  */
19 #include <assert.h>
20 #include <stddef.h>
21 #include <inttypes.h>
22 #include <ctype.h>
23 #include <stdio.h>
24 #include <errno.h>
25 #include <limits.h>
26 
27 #include "sysflash/sysflash.h"
28 
29 #include "bootutil/bootutil_log.h"
30 
31 #ifdef __ZEPHYR__
32 #include <zephyr/sys/reboot.h>
33 #include <zephyr/sys/byteorder.h>
34 #include <zephyr/sys/__assert.h>
35 #include <zephyr/drivers/flash.h>
36 #include <zephyr/kernel.h>
37 #include <zephyr/sys/crc.h>
38 #include <zephyr/sys/base64.h>
39 #include <hal/hal_flash.h>
40 #elif __ESPRESSIF__
41 #include <bootloader_utility.h>
42 #include <esp_rom_sys.h>
43 #include <esp_crc.h>
44 #include <endian.h>
45 #include <mbedtls/base64.h>
46 #else
47 #include <bsp/bsp.h>
48 #include <hal/hal_system.h>
49 #include <hal/hal_flash.h>
50 #include <os/endian.h>
51 #include <os/os_cputime.h>
52 #include <crc/crc16.h>
53 #include <base64/base64.h>
54 #endif /* __ZEPHYR__ */
55 
56 #include <zcbor_decode.h>
57 #include <zcbor_encode.h>
58 #include "zcbor_bulk.h"
59 
60 #include <flash_map_backend/flash_map_backend.h>
61 #include <os/os.h>
62 #include <os/os_malloc.h>
63 
64 #include <bootutil/image.h>
65 #include <bootutil/bootutil.h>
66 
67 #include "boot_serial/boot_serial.h"
68 #include "boot_serial_priv.h"
69 #include "mcuboot_config/mcuboot_config.h"
70 #include "../src/bootutil_priv.h"
71 
72 #ifdef MCUBOOT_ENC_IMAGES
73 #include "boot_serial/boot_serial_encryption.h"
74 #endif
75 
76 #include "bootutil/boot_hooks.h"
77 
78 BOOT_LOG_MODULE_DECLARE(mcuboot);
79 
80 #ifndef ARRAY_SIZE
81 #define ARRAY_SIZE ZCBOR_ARRAY_SIZE
82 #endif
83 
84 #ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
85 #define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
86 #endif
87 
88 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
89 #define BOOT_SERIAL_IMAGE_STATE_SIZE_MAX 48
90 #else
91 #define BOOT_SERIAL_IMAGE_STATE_SIZE_MAX 0
92 #endif
93 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
94 #define BOOT_SERIAL_HASH_SIZE_MAX 36
95 #else
96 #define BOOT_SERIAL_HASH_SIZE_MAX 0
97 #endif
98 #ifdef MCUBOOT_SERIAL_IMG_GRP_SLOT_INFO
99 #define BOOT_SERIAL_SLOT_INFO_SIZE_MAX 164
100 #else
101 #define BOOT_SERIAL_SLOT_INFO_SIZE_MAX 0
102 #endif
103 
104 #if (128 + BOOT_SERIAL_IMAGE_STATE_SIZE_MAX + BOOT_SERIAL_HASH_SIZE_MAX) > \
105     BOOT_SERIAL_SLOT_INFO_SIZE_MAX
106 #define BOOT_SERIAL_MAX_MESSAGE_SIZE (128 + BOOT_SERIAL_IMAGE_STATE_SIZE_MAX + \
107         BOOT_SERIAL_HASH_SIZE_MAX)
108 #else
109 #define BOOT_SERIAL_MAX_MESSAGE_SIZE BOOT_SERIAL_SLOT_INFO_SIZE_MAX
110 #endif
111 
112 #define BOOT_SERIAL_OUT_MAX     (BOOT_SERIAL_MAX_MESSAGE_SIZE * BOOT_IMAGE_NUMBER)
113 
114 #define BOOT_SERIAL_FRAME_MTU   124 /* 127 - pkt start (2 bytes) and stop (1 byte) */
115 
116 /* Number of estimated CBOR elements for responses */
117 #define CBOR_ENTRIES_SLOT_INFO_IMAGE_MAP 4
118 #define CBOR_ENTRIES_SLOT_INFO_SLOTS_MAP 3
119 
120 #ifdef __ZEPHYR__
121 /* base64 lib encodes data to null-terminated string */
122 #define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
123 
124 #define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
125 #define CRC_CITT_POLYMINAL 0x1021
126 
127 #define ntohs(x) sys_be16_to_cpu(x)
128 #define htons(x) sys_cpu_to_be16(x)
129 #elif __ESPRESSIF__
130 #define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
131 #define CRC16_INITIAL_CRC       0       /* what to seed crc16 with */
132 
133 #define ntohs(x) be16toh(x)
134 #define htons(x) htobe16(x)
135 
136 #define base64_decode mbedtls_base64_decode
137 #define base64_encode mbedtls_base64_encode
138 #endif
139 
140 #if (BOOT_IMAGE_NUMBER > 1)
141 #define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
142 #else
143 #define IMAGES_ITER(x)
144 #endif
145 
146 static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
147 static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
148 const struct boot_uart_funcs *boot_uf;
149 static struct nmgr_hdr *bs_hdr;
150 static bool bs_entry;
151 
152 static char bs_obuf[BOOT_SERIAL_OUT_MAX];
153 
154 static void boot_serial_output(void);
155 
156 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
157 static int boot_serial_get_hash(const struct image_header *hdr,
158                                 const struct flash_area *fap, uint8_t *hash);
159 #endif
160 
161 static zcbor_state_t cbor_state[2];
162 
reset_cbor_state(void)163 void reset_cbor_state(void)
164 {
165     zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
166         sizeof(bs_obuf), 0);
167 }
168 
169 /**
170  * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
171  * used to process any groups that have not been processed by generic boot
172  * serial implementation.
173  *
174  * @param[in] hdr -- the decoded header of mcumgr message;
175  * @param[in] buffer -- buffer with first mcumgr message;
176  * @param[in] len -- length of of data in buffer;
177  * @param[out] *cs -- object with encoded response.
178  *
179  * @return 0 on success; non-0 error code otherwise.
180  */
181 extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
182                                       const char *buffer,
183                                       int len, zcbor_state_t *cs);
184 
185 #define zcbor_tstr_put_lit_cast(state, string) \
186 	zcbor_tstr_encode_ptr(state, (char *)string, sizeof(string) - 1)
187 
188 #ifndef MCUBOOT_USE_SNPRINTF
189 /*
190  * Convert version into string without use of snprintf().
191  */
192 static int
u32toa(char * tgt,uint32_t val)193 u32toa(char *tgt, uint32_t val)
194 {
195     char *dst;
196     uint32_t d = 1;
197     uint32_t dgt;
198     int n = 0;
199 
200     dst = tgt;
201     while (val / d >= 10) {
202         d *= 10;
203     }
204     while (d) {
205         dgt = val / d;
206         val %= d;
207         d /= 10;
208         if (n || dgt > 0 || d == 0) {
209             *dst++ = dgt + '0';
210             ++n;
211         }
212     }
213     *dst = '\0';
214 
215     return dst - tgt;
216 }
217 
218 /*
219  * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
220  */
221 static void
bs_list_img_ver(char * dst,int maxlen,struct image_version * ver)222 bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
223 {
224     int off;
225 
226     off = u32toa(dst, ver->iv_major);
227     dst[off++] = '.';
228     off += u32toa(dst + off, ver->iv_minor);
229     dst[off++] = '.';
230     off += u32toa(dst + off, ver->iv_revision);
231 
232     if (ver->iv_build_num != 0) {
233         dst[off++] = '.';
234         off += u32toa(dst + off, ver->iv_build_num);
235     }
236 }
237 #else
238 /*
239  * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
240  */
241 static void
bs_list_img_ver(char * dst,int maxlen,struct image_version * ver)242 bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
243 {
244    int len;
245 
246    len = snprintf(dst, maxlen, "%hu.%hu.%hu", (uint16_t)ver->iv_major,
247                   (uint16_t)ver->iv_minor, ver->iv_revision);
248 
249    if (ver->iv_build_num != 0 && len > 0 && len < maxlen) {
250       snprintf(&dst[len], (maxlen - len), ".%u", ver->iv_build_num);
251    }
252 }
253 #endif /* !MCUBOOT_USE_SNPRINTF */
254 
255 /*
256  * List images.
257  */
258 static void
bs_list(char * buf,int len)259 bs_list(char *buf, int len)
260 {
261     struct image_header hdr;
262     uint32_t slot, area_id;
263     const struct flash_area *fap;
264     uint8_t image_index;
265 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
266     uint8_t hash[32];
267 #endif
268 
269     zcbor_map_start_encode(cbor_state, 1);
270     zcbor_tstr_put_lit_cast(cbor_state, "images");
271     zcbor_list_start_encode(cbor_state, 5);
272     image_index = 0;
273     IMAGES_ITER(image_index) {
274 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
275         int swap_status = boot_swap_type_multi(image_index);
276 #endif
277 
278         for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
279             FIH_DECLARE(fih_rc, FIH_FAILURE);
280             uint8_t tmpbuf[64];
281 
282 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
283             bool active = false;
284             bool confirmed = false;
285             bool pending = false;
286             bool permanent = false;
287 #endif
288 
289             area_id = flash_area_id_from_multi_image_slot(image_index, slot);
290             if (flash_area_open(area_id, &fap)) {
291                 continue;
292             }
293 
294             int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
295                                     BOOT_HOOK_REGULAR, image_index, slot, &hdr);
296             if (rc == BOOT_HOOK_REGULAR)
297             {
298                 flash_area_read(fap, 0, &hdr, sizeof(hdr));
299             }
300 
301             if (hdr.ih_magic == IMAGE_MAGIC)
302             {
303                 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
304                                    FIH_BOOT_HOOK_REGULAR,
305                                    fih_rc, image_index, slot);
306                 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
307                 {
308 #if defined(MCUBOOT_ENC_IMAGES)
309 #if !defined(MCUBOOT_SINGLE_APPLICATION_SLOT)
310                     if (IS_ENCRYPTED(&hdr) && MUST_DECRYPT(fap, image_index, &hdr)) {
311                         FIH_CALL(boot_image_validate_encrypted, fih_rc, fap,
312                                  &hdr, tmpbuf, sizeof(tmpbuf));
313                     } else {
314 #endif
315                         if (IS_ENCRYPTED(&hdr)) {
316                             /*
317                              * There is an image present which has an encrypted flag set but is
318                              * not encrypted, therefore remove the flag from the header and run a
319                              * normal image validation on it.
320                              */
321                             hdr.ih_flags &= ~ENCRYPTIONFLAGS;
322                         }
323 #endif
324 
325                         FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr,
326                                  fap, tmpbuf, sizeof(tmpbuf), NULL, 0, NULL);
327 #if defined(MCUBOOT_ENC_IMAGES) && !defined(MCUBOOT_SINGLE_APPLICATION_SLOT)
328                     }
329 #endif
330                 }
331             }
332 
333             if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
334                 flash_area_close(fap);
335                 continue;
336             }
337 
338 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
339             /* Retrieve SHA256 hash of image for identification */
340             rc = boot_serial_get_hash(&hdr, fap, hash);
341 #endif
342 
343             flash_area_close(fap);
344             zcbor_map_start_encode(cbor_state, 20);
345 
346 #if (BOOT_IMAGE_NUMBER > 1)
347             zcbor_tstr_put_lit_cast(cbor_state, "image");
348             zcbor_uint32_put(cbor_state, image_index);
349 #endif
350 
351 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
352             if (swap_status == BOOT_SWAP_TYPE_NONE) {
353                 if (slot == BOOT_PRIMARY_SLOT) {
354                     confirmed = true;
355                     active = true;
356                 }
357             } else if (swap_status == BOOT_SWAP_TYPE_TEST) {
358                 if (slot == BOOT_PRIMARY_SLOT) {
359                     confirmed = true;
360                 } else {
361                     pending = true;
362                 }
363             } else if (swap_status == BOOT_SWAP_TYPE_PERM) {
364                 if (slot == BOOT_PRIMARY_SLOT) {
365                     confirmed = true;
366                 } else {
367                     pending = true;
368                     permanent = true;
369                 }
370             } else if (swap_status == BOOT_SWAP_TYPE_REVERT) {
371                 if (slot == BOOT_PRIMARY_SLOT) {
372                     active = true;
373                 } else {
374                     confirmed = true;
375                 }
376             }
377 
378             if (!(hdr.ih_flags & IMAGE_F_NON_BOOTABLE)) {
379                 zcbor_tstr_put_lit_cast(cbor_state, "bootable");
380                 zcbor_bool_put(cbor_state, true);
381             }
382 
383             if (confirmed) {
384                 zcbor_tstr_put_lit_cast(cbor_state, "confirmed");
385                 zcbor_bool_put(cbor_state, true);
386             }
387 
388             if (active) {
389                 zcbor_tstr_put_lit_cast(cbor_state, "active");
390                 zcbor_bool_put(cbor_state, true);
391             }
392 
393             if (pending) {
394                 zcbor_tstr_put_lit_cast(cbor_state, "pending");
395                 zcbor_bool_put(cbor_state, true);
396             }
397 
398             if (permanent) {
399                 zcbor_tstr_put_lit_cast(cbor_state, "permanent");
400                 zcbor_bool_put(cbor_state, true);
401             }
402 #endif
403 
404             zcbor_tstr_put_lit_cast(cbor_state, "slot");
405             zcbor_uint32_put(cbor_state, slot);
406 
407 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
408             if (rc == 0) {
409                 zcbor_tstr_put_lit_cast(cbor_state, "hash");
410                 zcbor_bstr_encode_ptr(cbor_state, hash, sizeof(hash));
411             }
412 #endif
413 
414             zcbor_tstr_put_lit_cast(cbor_state, "version");
415 
416             bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
417 
418             zcbor_tstr_encode_ptr(cbor_state, (char *)tmpbuf, strlen((char *)tmpbuf));
419             zcbor_map_end_encode(cbor_state, 20);
420         }
421     }
422     zcbor_list_end_encode(cbor_state, 5);
423     zcbor_map_end_encode(cbor_state, 1);
424     boot_serial_output();
425 }
426 
427 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
428 /*
429  * Set image state.
430  */
431 static void
bs_set(char * buf,int len)432 bs_set(char *buf, int len)
433 {
434     /*
435      * Expected data format.
436      * {
437      *   "confirm":<true for confirm, false for test>
438      *   "hash":<hash of image (OPTIONAL for single image only)>
439      * }
440      */
441     uint8_t image_index = 0;
442     size_t decoded = 0;
443     uint8_t hash[32];
444     bool confirm;
445     struct zcbor_string img_hash;
446     bool ok;
447     int rc;
448 
449 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
450     bool found = false;
451 #endif
452 
453     zcbor_state_t zsd[4];
454     zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1, NULL, 0);
455 
456     struct zcbor_map_decode_key_val image_set_state_decode[] = {
457         ZCBOR_MAP_DECODE_KEY_DECODER("confirm", zcbor_bool_decode, &confirm),
458 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
459         ZCBOR_MAP_DECODE_KEY_DECODER("hash", zcbor_bstr_decode, &img_hash),
460 #endif
461     };
462 
463     ok = zcbor_map_decode_bulk(zsd, image_set_state_decode, ARRAY_SIZE(image_set_state_decode),
464                                &decoded) == 0;
465 
466     if (!ok) {
467         rc = MGMT_ERR_EINVAL;
468         goto out;
469     }
470 
471 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
472     if ((img_hash.len != sizeof(hash) && img_hash.len != 0) ||
473         (img_hash.len == 0 && BOOT_IMAGE_NUMBER > 1)) {
474         /* Hash is required and was not provided or is invalid size */
475         rc = MGMT_ERR_EINVAL;
476         goto out;
477     }
478 
479     if (img_hash.len != 0) {
480         for (image_index = 0; image_index < BOOT_IMAGE_NUMBER; ++image_index) {
481             struct image_header hdr;
482             uint32_t area_id;
483             const struct flash_area *fap;
484             uint8_t tmpbuf[64];
485 
486             area_id = flash_area_id_from_multi_image_slot(image_index, 1);
487             if (flash_area_open(area_id, &fap)) {
488                 BOOT_LOG_ERR("Failed to open flash area ID %d", area_id);
489                 continue;
490             }
491 
492             rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
493                                 BOOT_HOOK_REGULAR, image_index, 1, &hdr);
494             if (rc == BOOT_HOOK_REGULAR)
495             {
496                 flash_area_read(fap, 0, &hdr, sizeof(hdr));
497             }
498 
499             if (hdr.ih_magic == IMAGE_MAGIC)
500             {
501                 FIH_DECLARE(fih_rc, FIH_FAILURE);
502 
503                 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
504                                    FIH_BOOT_HOOK_REGULAR,
505                                    fih_rc, image_index, 1);
506                 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
507                 {
508 #ifdef MCUBOOT_ENC_IMAGES
509                     if (IS_ENCRYPTED(&hdr)) {
510                         FIH_CALL(boot_image_validate_encrypted, fih_rc, fap,
511                                  &hdr, tmpbuf, sizeof(tmpbuf));
512                     } else {
513 #endif
514                         FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr,
515                                  fap, tmpbuf, sizeof(tmpbuf), NULL, 0, NULL);
516 #ifdef MCUBOOT_ENC_IMAGES
517                     }
518 #endif
519                 }
520 
521                 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
522                     continue;
523                 }
524             }
525 
526             /* Retrieve SHA256 hash of image for identification */
527             rc = boot_serial_get_hash(&hdr, fap, hash);
528             flash_area_close(fap);
529 
530             if (rc == 0 && memcmp(hash, img_hash.value, sizeof(hash)) == 0) {
531                 /* Hash matches, set this slot for test or confirmation */
532                 found = true;
533                 break;
534             }
535         }
536 
537         if (!found) {
538             /* Image was not found with specified hash */
539             BOOT_LOG_ERR("Did not find image with specified hash");
540             rc = MGMT_ERR_ENOENT;
541             goto out;
542         }
543     }
544 #endif
545 
546     rc = boot_set_pending_multi(image_index, confirm);
547 
548 out:
549     if (rc == 0) {
550         /* Success - return updated list of images */
551         bs_list(buf, len);
552     } else {
553         /* Error code, only return the error */
554         zcbor_map_start_encode(cbor_state, 10);
555         zcbor_tstr_put_lit_cast(cbor_state, "rc");
556         zcbor_int32_put(cbor_state, rc);
557         zcbor_map_end_encode(cbor_state, 10);
558 
559         boot_serial_output();
560     }
561 }
562 #endif
563 
564 /*
565  * Send rc code only.
566  */
567 static void
bs_rc_rsp(int rc_code)568 bs_rc_rsp(int rc_code)
569 {
570     zcbor_map_start_encode(cbor_state, 10);
571     zcbor_tstr_put_lit_cast(cbor_state, "rc");
572     zcbor_int32_put(cbor_state, rc_code);
573     zcbor_map_end_encode(cbor_state, 10);
574     boot_serial_output();
575 }
576 
577 static void
bs_list_set(uint8_t op,char * buf,int len)578 bs_list_set(uint8_t op, char *buf, int len)
579 {
580     if (op == NMGR_OP_READ) {
581         bs_list(buf, len);
582     } else {
583 #ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
584         bs_set(buf, len);
585 #else
586         bs_rc_rsp(MGMT_ERR_ENOTSUP);
587 #endif
588     }
589 }
590 
591 #ifdef MCUBOOT_SERIAL_IMG_GRP_SLOT_INFO
592 static void
bs_slot_info(uint8_t op,char * buf,int len)593 bs_slot_info(uint8_t op, char *buf, int len)
594 {
595     uint32_t slot, area_id;
596     const struct flash_area *fap;
597     uint8_t image_index = 0;
598     int rc;
599     bool ok = true;
600     const struct image_max_size *image_max_sizes;
601 
602     if (op != NMGR_OP_READ) {
603         bs_rc_rsp(MGMT_ERR_ENOTSUP);
604     }
605 
606     image_max_sizes = boot_get_max_app_size();
607 
608     zcbor_map_start_encode(cbor_state, 1);
609     zcbor_tstr_put_lit_cast(cbor_state, "images");
610     zcbor_list_start_encode(cbor_state, MCUBOOT_IMAGE_NUMBER);
611 
612     IMAGES_ITER(image_index) {
613         for (slot = 0; slot < BOOT_NUM_SLOTS; slot++) {
614             if (slot == 0) {
615                     ok = zcbor_map_start_encode(cbor_state, CBOR_ENTRIES_SLOT_INFO_IMAGE_MAP) &&
616                          zcbor_tstr_put_lit(cbor_state, "image") &&
617                          zcbor_uint32_put(cbor_state, (uint32_t)image_index) &&
618                          zcbor_tstr_put_lit(cbor_state, "slots") &&
619                          zcbor_list_start_encode(cbor_state, BOOT_NUM_SLOTS);
620 
621                     if (!ok) {
622                             goto finish;
623                     }
624                 }
625 
626                 ok = zcbor_map_start_encode(cbor_state, CBOR_ENTRIES_SLOT_INFO_SLOTS_MAP) &&
627                      zcbor_tstr_put_lit(cbor_state, "slot") &&
628                      zcbor_uint32_put(cbor_state, slot);
629 
630                 if (!ok) {
631                     goto finish;
632                 }
633 
634                 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
635                 rc = flash_area_open(area_id, &fap);
636 
637                 if (rc) {
638                     ok = zcbor_tstr_put_lit(cbor_state, "rc") &&
639                          zcbor_int32_put(cbor_state, rc);
640                 } else {
641                     if (sizeof(fap->fa_size) == sizeof(uint64_t)) {
642                         ok = zcbor_tstr_put_lit(cbor_state, "size") &&
643                              zcbor_uint64_put(cbor_state, fap->fa_size);
644                     } else {
645                         ok = zcbor_tstr_put_lit(cbor_state, "size") &&
646                              zcbor_uint32_put(cbor_state, fap->fa_size);
647                     }
648 
649                     if (!ok) {
650                         flash_area_close(fap);
651                         goto finish;
652                     }
653 
654                     /*
655                      * Check if we support uploading to this slot and if so, return the
656                      * image ID
657                      */
658 #if defined(MCUBOOT_SINGLE_APPLICATION_SLOT)
659                     ok = zcbor_tstr_put_lit(cbor_state, "upload_image_id") &&
660                          zcbor_uint32_put(cbor_state, (image_index + 1));
661 #elif defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
662                     ok = zcbor_tstr_put_lit(cbor_state, "upload_image_id") &&
663                          zcbor_uint32_put(cbor_state, (image_index * 2 + slot + 1));
664 #else
665                     if (slot == 1) {
666                         ok = zcbor_tstr_put_lit(cbor_state, "upload_image_id") &&
667                              zcbor_uint32_put(cbor_state, (image_index * 2 + 1));
668                     }
669 #endif
670 
671                     flash_area_close(fap);
672 
673                     if (!ok) {
674                         goto finish;
675                     }
676 
677                     ok = zcbor_map_end_encode(cbor_state, CBOR_ENTRIES_SLOT_INFO_SLOTS_MAP);
678 
679                     if (!ok) {
680                             goto finish;
681                     }
682 
683                     if (slot == (BOOT_NUM_SLOTS - 1)) {
684                         ok = zcbor_list_end_encode(cbor_state, BOOT_NUM_SLOTS);
685 
686                         if (!ok) {
687                             goto finish;
688                         }
689 
690                         if (image_max_sizes[image_index].calculated == true) {
691                             ok = zcbor_tstr_put_lit(cbor_state, "max_image_size") &&
692                                  zcbor_uint32_put(cbor_state,
693                                                   image_max_sizes[image_index].max_size);
694 
695                             if (!ok) {
696                                 goto finish;
697                             }
698                         }
699 
700                         ok = zcbor_map_end_encode(cbor_state, CBOR_ENTRIES_SLOT_INFO_IMAGE_MAP);
701 
702                     }
703                 }
704 
705                 if (!ok) {
706                     goto finish;
707                 }
708             }
709         }
710 
711         ok = zcbor_list_end_encode(cbor_state, MCUBOOT_IMAGE_NUMBER) &&
712              zcbor_map_end_encode(cbor_state, 1);
713 
714 finish:
715     if (!ok) {
716         reset_cbor_state();
717         bs_rc_rsp(MGMT_ERR_ENOMEM);
718     }
719 
720     boot_serial_output();
721 }
722 #endif
723 
724 #ifdef MCUBOOT_ERASE_PROGRESSIVELY
725 /** Erases range of flash, aligned to sector size
726  *
727  * Function will erase all sectors withing [start, end] range; it does not check
728  * the @p start for alignment, and it will use @p end to find boundaries of las
729  * sector to erase. Function returns offset of the first byte past the last
730  * erased sector, so basically offset of next sector to be erased if needed.
731  * The function is intended to be called iteratively with previously returned
732  * offset as @p start.
733  *
734  * @param   start starting offset, aligned to sector offset;
735  * @param   end ending offset, maybe anywhere within sector;
736  *
737  * @retval On success: offset of the first byte past last erased sector;
738  *         On failure: -EINVAL.
739  */
erase_range(const struct flash_area * fap,off_t start,off_t end)740 static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
741 {
742     struct flash_sector sect;
743     size_t size;
744     int rc;
745 
746     if (end >= flash_area_get_size(fap)) {
747         return -EINVAL;
748     }
749 
750     if (end < start) {
751         return start;
752     }
753 
754     if (flash_area_get_sector(fap, end, &sect)) {
755         return -EINVAL;
756     }
757 
758     size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
759     BOOT_LOG_DBG("Erasing range 0x%jx:0x%jx", (intmax_t)start,
760 		 (intmax_t)(start + size - 1));
761 
762     rc = flash_area_erase(fap, start, size);
763     if (rc != 0) {
764         BOOT_LOG_ERR("Error %d while erasing range", rc);
765         return -EINVAL;
766     }
767 
768     return start + size;
769 }
770 #endif
771 
772 /*
773  * Image upload request.
774  */
775 static void
bs_upload(char * buf,int len)776 bs_upload(char *buf, int len)
777 {
778     static size_t img_size;             /* Total image size, held for duration of upload */
779     static uint32_t curr_off;           /* Expected current offset */
780     const uint8_t *img_chunk = NULL;    /* Pointer to buffer with received image chunk */
781     size_t img_chunk_len = 0;           /* Length of received image chunk */
782     size_t img_chunk_off = SIZE_MAX;    /* Offset of image chunk within image  */
783     size_t rem_bytes;                   /* Reminder bytes after aligning chunk write to
784                                          * to flash alignment */
785     uint32_t img_num_tmp = UINT_MAX;    /* Temp variable for image number */
786     static uint32_t img_num = 0;
787     size_t img_size_tmp = SIZE_MAX;     /* Temp variable for image size */
788     const struct flash_area *fap = NULL;
789     int rc;
790     struct zcbor_string img_chunk_data;
791     size_t decoded = 0;
792     bool ok;
793 #ifdef MCUBOOT_ERASE_PROGRESSIVELY
794     static off_t not_yet_erased = 0;    /* Offset of next byte to erase; writes to flash
795                                          * are done in consecutive manner and erases are done
796                                          * to allow currently received chunk to be written;
797                                          * this state variable holds information where last
798                                          * erase has stopped to let us know whether erase
799                                          * is needed to be able to write current chunk.
800                                          */
801     static struct flash_sector status_sector;
802 #endif
803 
804     zcbor_state_t zsd[4];
805     zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1, NULL, 0);
806 
807     struct zcbor_map_decode_key_val image_upload_decode[] = {
808         ZCBOR_MAP_DECODE_KEY_DECODER("image", zcbor_uint32_decode, &img_num_tmp),
809         ZCBOR_MAP_DECODE_KEY_DECODER("data", zcbor_bstr_decode, &img_chunk_data),
810         ZCBOR_MAP_DECODE_KEY_DECODER("len", zcbor_size_decode, &img_size_tmp),
811         ZCBOR_MAP_DECODE_KEY_DECODER("off", zcbor_size_decode, &img_chunk_off),
812     };
813 
814     ok = zcbor_map_decode_bulk(zsd, image_upload_decode, ARRAY_SIZE(image_upload_decode),
815                                &decoded) == 0;
816 
817     if (!ok) {
818         goto out_invalid_data;
819     }
820 
821     img_chunk = img_chunk_data.value;
822     img_chunk_len = img_chunk_data.len;
823 
824     /*
825      * Expected data format.
826      * {
827      *   "image":<image number in a multi-image set (OPTIONAL)>
828      *   "data":<image data>
829      *   "len":<image len>
830      *   "off":<current offset of image data>
831      * }
832      */
833 
834     if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
835         /*
836          * Offset must be set in every block.
837          */
838         goto out_invalid_data;
839     }
840 
841     /* Use image number only from packet with offset == 0. */
842     if (img_chunk_off == 0) {
843         if (img_num_tmp != UINT_MAX) {
844             img_num = img_num_tmp;
845         } else {
846             img_num = 0;
847         }
848     }
849 
850 #if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
851     rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
852 #else
853     rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
854 #endif
855     if (rc) {
856         rc = MGMT_ERR_EINVAL;
857         goto out;
858     }
859 
860     if (img_chunk_off == 0) {
861         /* Receiving chunk with 0 offset resets the upload state; this basically
862          * means that upload has started from beginning.
863          */
864         const size_t area_size = flash_area_get_size(fap);
865 
866         curr_off = 0;
867 #ifdef MCUBOOT_ERASE_PROGRESSIVELY
868         /* Get trailer sector information; this is done early because inability to get
869          * that sector information means that upload will not work anyway.
870          * TODO: This is single occurrence issue, it should get detected during tests
871          * and fixed otherwise you are deploying broken mcuboot.
872          */
873         if (flash_area_get_sector(fap, boot_status_off(fap), &status_sector)) {
874             rc = MGMT_ERR_EUNKNOWN;
875             BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
876             goto out;
877          }
878 #endif
879 
880 #if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
881         /* We are using swap state at end of flash area to store validation
882          * result. Make sure the user cannot write it from an image to skip validation.
883          */
884         if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
885             goto out_invalid_data;
886         }
887 #else
888         if (img_size_tmp > area_size) {
889             goto out_invalid_data;
890         }
891 
892 #endif
893 
894 #ifndef MCUBOOT_ERASE_PROGRESSIVELY
895         /* Non-progressive erase erases entire image slot when first chunk of
896          * an image is received.
897          */
898         rc = flash_area_erase(fap, 0, area_size);
899         if (rc) {
900             goto out_invalid_data;
901         }
902 #else
903         not_yet_erased = 0;
904 #endif
905 
906         img_size = img_size_tmp;
907     } else if (img_chunk_off != curr_off) {
908         /* If received chunk offset does not match expected one jump, pretend
909          * success and jump to out; out will respond to client with success
910          * and request the expected offset, held by curr_off.
911          */
912         rc = 0;
913         goto out;
914     } else if (curr_off + img_chunk_len > img_size) {
915         rc = MGMT_ERR_EINVAL;
916         goto out;
917     }
918 
919 #ifdef MCUBOOT_ERASE_PROGRESSIVELY
920     /* Progressive erase will erase enough flash, aligned to sector size,
921      * as needed for the current chunk to be written.
922      */
923     not_yet_erased = erase_range(fap, not_yet_erased,
924                                  curr_off + img_chunk_len - 1);
925 
926     if (not_yet_erased < 0) {
927         rc = MGMT_ERR_EINVAL;
928         goto out;
929     }
930 #endif
931 
932     /* Writes are aligned to flash write alignment, so may drop a few bytes
933      * from the end of the buffer; we will request these bytes again with
934      * new buffer by responding with request for offset after the last aligned
935      * write.
936      */
937     rem_bytes = img_chunk_len % flash_area_align(fap);
938     img_chunk_len -= rem_bytes;
939 
940     if (curr_off + img_chunk_len + rem_bytes < img_size) {
941         rem_bytes = 0;
942     }
943 
944     BOOT_LOG_DBG("Writing at 0x%x until 0x%x", curr_off, curr_off + (uint32_t)img_chunk_len);
945     /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
946 #if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
947     if (flash_area_align(fap) > 1 &&
948         (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
949         /* Buffer address incompatible with write address, use buffer to write */
950         size_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
951         uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
952 
953         while (img_chunk_len >= flash_area_align(fap)) {
954             if (write_size > img_chunk_len) {
955                 write_size = img_chunk_len;
956             }
957 
958             memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
959             memcpy(wbs_aligned, img_chunk, write_size);
960 
961             rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
962 
963             if (rc != 0) {
964                 goto out;
965             }
966 
967             curr_off += write_size;
968             img_chunk += write_size;
969             img_chunk_len -= write_size;
970         }
971     } else {
972         rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
973     }
974 #else
975     rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
976 #endif
977 
978     if (rc == 0 && rem_bytes) {
979         /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
980          * part, in the img_chunk_len - rem_bytes count bytes, has already been
981          * written by the above write, so we are left with the rem_bytes.
982          */
983         uint8_t wbs_aligned[BOOT_MAX_ALIGN];
984 
985         memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
986         memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
987 
988         rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
989                               flash_area_align(fap));
990     }
991 
992     if (rc == 0) {
993         curr_off += img_chunk_len + rem_bytes;
994         if (curr_off == img_size) {
995 #ifdef MCUBOOT_ERASE_PROGRESSIVELY
996             /* Assure that sector for image trailer was erased. */
997             /* Check whether it was erased during previous upload. */
998             off_t start = flash_sector_get_off(&status_sector);
999 
1000             if (erase_range(fap, start, start) < 0) {
1001                 rc = MGMT_ERR_EUNKNOWN;
1002                 goto out;
1003             }
1004 #endif
1005             rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
1006                                 img_size);
1007             if (rc) {
1008                 BOOT_LOG_ERR("Error %d post upload hook", rc);
1009                 goto out;
1010             }
1011         }
1012     } else {
1013     out_invalid_data:
1014         rc = MGMT_ERR_EINVAL;
1015     }
1016 
1017 out:
1018     BOOT_LOG_DBG("RX: 0x%x", rc);
1019     zcbor_map_start_encode(cbor_state, 10);
1020     zcbor_tstr_put_lit_cast(cbor_state, "rc");
1021     zcbor_int32_put(cbor_state, rc);
1022     if (rc == 0) {
1023         zcbor_tstr_put_lit_cast(cbor_state, "off");
1024         zcbor_uint32_put(cbor_state, curr_off);
1025     }
1026     zcbor_map_end_encode(cbor_state, 10);
1027 
1028     boot_serial_output();
1029 
1030 #ifdef MCUBOOT_ENC_IMAGES
1031     /* Check if this upload was for the primary slot */
1032 #if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
1033     if (flash_area_id_from_multi_image_slot(img_num, 0) == FLASH_AREA_IMAGE_PRIMARY(0))
1034 #else
1035     if (flash_area_id_from_direct_image(img_num) == FLASH_AREA_IMAGE_PRIMARY(0))
1036 #endif
1037     {
1038         if (curr_off == img_size) {
1039             /* Last sector received, now start a decryption on the image if it is encrypted */
1040             rc = boot_handle_enc_fw(fap);
1041         }
1042     }
1043 #endif
1044 
1045     flash_area_close(fap);
1046 }
1047 
1048 #ifdef MCUBOOT_BOOT_MGMT_ECHO
1049 static void
bs_echo(char * buf,int len)1050 bs_echo(char *buf, int len)
1051 {
1052     struct zcbor_string value = { 0 };
1053     struct zcbor_string key;
1054     bool ok;
1055     uint32_t rc = MGMT_ERR_EINVAL;
1056 
1057     zcbor_state_t zsd[4];
1058     zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1, NULL, 0);
1059 
1060     if (!zcbor_map_start_decode(zsd)) {
1061         goto out;
1062     }
1063 
1064     do {
1065         ok = zcbor_tstr_decode(zsd, &key);
1066 
1067         if (ok) {
1068             if (key.len == 1 && *key.value == 'd') {
1069                 ok = zcbor_tstr_decode(zsd, &value);
1070                 break;
1071             }
1072 
1073             ok = zcbor_any_skip(zsd, NULL);
1074         }
1075     } while (ok);
1076 
1077     if (!ok || !zcbor_map_end_decode(zsd)) {
1078         goto out;
1079     }
1080 
1081     zcbor_map_start_encode(cbor_state, 10);
1082     zcbor_tstr_put_lit(cbor_state, "r");
1083     if (zcbor_tstr_encode(cbor_state, &value) && zcbor_map_end_encode(cbor_state, 10)) {
1084         boot_serial_output();
1085         return;
1086     } else {
1087         rc = MGMT_ERR_ENOMEM;
1088     }
1089 
1090 out:
1091     reset_cbor_state();
1092     bs_rc_rsp(rc);
1093 }
1094 #endif
1095 
1096 /*
1097  * Reset, and (presumably) boot to newly uploaded image. Flush console
1098  * before restarting.
1099  */
1100 static void
bs_reset(char * buf,int len)1101 bs_reset(char *buf, int len)
1102 {
1103     int rc = BOOT_HOOK_CALL(boot_reset_request_hook, 0, false);
1104     if (rc == BOOT_RESET_REQUEST_HOOK_BUSY) {
1105 	rc = MGMT_ERR_EBUSY;
1106     } else {
1107         /* Currently whatever else is returned it is just converted
1108          * to 0/no error. Boot serial starts accepting "force" parameter
1109          * in command this needs to change.
1110          */
1111          rc = 0;
1112     }
1113     bs_rc_rsp(rc);
1114 
1115     if (rc == 0) {
1116 #ifdef __ZEPHYR__
1117 #ifdef CONFIG_MULTITHREADING
1118         k_sleep(K_MSEC(250));
1119 #else
1120         k_busy_wait(250000);
1121 #endif
1122         sys_reboot(SYS_REBOOT_COLD);
1123 #elif __ESPRESSIF__
1124         esp_rom_delay_us(250000);
1125         bootloader_reset();
1126 #else
1127         os_cputime_delay_usecs(250000);
1128         hal_system_reset();
1129 #endif
1130     }
1131 }
1132 
1133 /*
1134  * Parse incoming line of input from console.
1135  * Expect newtmgr protocol with serial transport.
1136  */
1137 void
boot_serial_input(char * buf,int len)1138 boot_serial_input(char *buf, int len)
1139 {
1140     struct nmgr_hdr *hdr;
1141 
1142     hdr = (struct nmgr_hdr *)buf;
1143     if (len < sizeof(*hdr) ||
1144       (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
1145       (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
1146         return;
1147     }
1148     bs_hdr = hdr;
1149     hdr->nh_group = ntohs(hdr->nh_group);
1150 
1151     buf += sizeof(*hdr);
1152     len -= sizeof(*hdr);
1153 
1154     reset_cbor_state();
1155 
1156     /*
1157      * Limited support for commands.
1158      */
1159     if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
1160         switch (hdr->nh_id) {
1161         case IMGMGR_NMGR_ID_STATE:
1162             bs_list_set(hdr->nh_op, buf, len);
1163             break;
1164         case IMGMGR_NMGR_ID_UPLOAD:
1165             bs_upload(buf, len);
1166             break;
1167 #ifdef MCUBOOT_SERIAL_IMG_GRP_SLOT_INFO
1168         case IMGMGR_NMGR_ID_SLOT_INFO:
1169             bs_slot_info(hdr->nh_op, buf, len);
1170             break;
1171 #endif
1172         default:
1173             bs_rc_rsp(MGMT_ERR_ENOTSUP);
1174             break;
1175         }
1176     } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
1177         switch (hdr->nh_id) {
1178 #ifdef MCUBOOT_BOOT_MGMT_ECHO
1179         case NMGR_ID_ECHO:
1180             bs_echo(buf, len);
1181             break;
1182 #endif
1183         case NMGR_ID_CONS_ECHO_CTRL:
1184             bs_rc_rsp(0);
1185             break;
1186         case NMGR_ID_RESET:
1187             bs_reset(buf, len);
1188             break;
1189         default:
1190             bs_rc_rsp(MGMT_ERR_ENOTSUP);
1191             break;
1192         }
1193     } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
1194         if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
1195             boot_serial_output();
1196         }
1197     } else {
1198         bs_rc_rsp(MGMT_ERR_ENOTSUP);
1199     }
1200 #ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1201     bs_entry = true;
1202 #endif
1203 }
1204 
1205 static void
boot_serial_output(void)1206 boot_serial_output(void)
1207 {
1208     char *data;
1209     int len, out;
1210     uint16_t crc;
1211     uint16_t totlen;
1212     char pkt_cont[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
1213     char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
1214     char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
1215     char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
1216 
1217     data = bs_obuf;
1218     len = (uintptr_t)cbor_state->payload_mut - (uintptr_t)bs_obuf;
1219 
1220     bs_hdr->nh_op++;
1221     bs_hdr->nh_flags = 0;
1222     bs_hdr->nh_len = htons(len);
1223     bs_hdr->nh_group = htons(bs_hdr->nh_group);
1224 
1225 #ifdef __ZEPHYR__
1226     crc =  crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
1227     crc =  crc16_itu_t(crc, data, len);
1228 #elif __ESPRESSIF__
1229     /* For ESP32 it was used the CRC API in rom/crc.h */
1230     crc =  ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
1231     crc =  ~esp_crc16_be(~crc, (uint8_t *)data, len);
1232 #else
1233     crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
1234     crc = crc16_ccitt(crc, data, len);
1235 #endif
1236     crc = htons(crc);
1237 
1238     totlen = len + sizeof(*bs_hdr) + sizeof(crc);
1239     totlen = htons(totlen);
1240 
1241     memcpy(buf, &totlen, sizeof(totlen));
1242     totlen = sizeof(totlen);
1243     memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
1244     totlen += sizeof(*bs_hdr);
1245     memcpy(&buf[totlen], data, len);
1246     totlen += len;
1247     memcpy(&buf[totlen], &crc, sizeof(crc));
1248     totlen += sizeof(crc);
1249 #ifdef __ZEPHYR__
1250     size_t enc_len;
1251     base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
1252     totlen = enc_len;
1253 #elif __ESPRESSIF__
1254     size_t enc_len;
1255     base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
1256     totlen = enc_len;
1257 #else
1258     totlen = base64_encode(buf, totlen, encoded_buf, 1);
1259 #endif
1260 
1261     out = 0;
1262     while (out < totlen) {
1263         if (out == 0) {
1264             boot_uf->write(pkt_start, sizeof(pkt_start));
1265         } else {
1266             boot_uf->write(pkt_cont, sizeof(pkt_cont));
1267         }
1268 
1269         len = MIN(BOOT_SERIAL_FRAME_MTU, totlen - out);
1270         boot_uf->write(&encoded_buf[out], len);
1271 
1272         out += len;
1273 
1274         boot_uf->write("\n", 1);
1275     }
1276 
1277     BOOT_LOG_DBG("TX");
1278 }
1279 
1280 /*
1281  * Returns 1 if full packet has been received.
1282  */
1283 static int
boot_serial_in_dec(char * in,int inlen,char * out,int * out_off,int maxout)1284 boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
1285 {
1286     size_t rc;
1287     uint16_t crc;
1288     uint16_t len;
1289 
1290 #ifdef __ZEPHYR__
1291     int err;
1292     err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
1293     if (err) {
1294         return -1;
1295     }
1296 #elif __ESPRESSIF__
1297     int err;
1298     err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, &rc, (unsigned char *)in, inlen);
1299     if (err) {
1300         return -1;
1301     }
1302 #else
1303     if (*out_off + base64_decode_len(in) >= maxout) {
1304         return -1;
1305     }
1306     rc = base64_decode(in, &out[*out_off]);
1307     if (rc < 0) {
1308         return -1;
1309     }
1310 #endif
1311 
1312     *out_off += rc;
1313     if (*out_off <= sizeof(uint16_t)) {
1314         return 0;
1315     }
1316 
1317     len = ntohs(*(uint16_t *)out);
1318     if (len != *out_off - sizeof(uint16_t)) {
1319         return 0;
1320     }
1321 
1322     out += sizeof(uint16_t);
1323 #ifdef __ZEPHYR__
1324     crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
1325 #elif __ESPRESSIF__
1326     crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
1327 #else
1328     crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
1329 #endif
1330     if (crc || len <= sizeof(crc)) {
1331         return 0;
1332     }
1333     *out_off -= sizeof(crc);
1334     out[*out_off] = '\0';
1335 
1336     return 1;
1337 }
1338 
1339 /*
1340  * Task which waits reading console, expecting to get image over
1341  * serial port.
1342  */
1343 static void
boot_serial_read_console(const struct boot_uart_funcs * f,int timeout_in_ms)1344 boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
1345 {
1346     int rc;
1347     int off;
1348     int dec_off = 0;
1349     int full_line;
1350     int max_input;
1351     int elapsed_in_ms = 0;
1352 
1353 #ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
1354     bool allow_idle = true;
1355 #endif
1356 
1357     boot_uf = f;
1358     max_input = sizeof(in_buf);
1359 
1360     off = 0;
1361     while (timeout_in_ms > 0 || bs_entry) {
1362         /*
1363          * Don't enter CPU idle state here if timeout based serial recovery is
1364          * used as otherwise the boot process hangs forever, waiting for input
1365          * from serial console (if single-thread mode is used).
1366          */
1367 #ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
1368         if (allow_idle == true) {
1369             MCUBOOT_CPU_IDLE();
1370             allow_idle = false;
1371         }
1372 #endif
1373         MCUBOOT_WATCHDOG_FEED();
1374 #ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1375         uint32_t start = k_uptime_get_32();
1376 #endif
1377         rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
1378         if (rc <= 0 && !full_line) {
1379 #ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
1380             allow_idle = true;
1381 #endif
1382             goto check_timeout;
1383         }
1384         off += rc;
1385         if (!full_line) {
1386             if (off == max_input) {
1387                 /*
1388                  * Full line, no newline yet. Reset the input buffer.
1389                  */
1390                 off = 0;
1391             }
1392             goto check_timeout;
1393         }
1394         if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
1395           in_buf[1] == SHELL_NLIP_PKT_START2) {
1396             dec_off = 0;
1397             rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
1398         } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
1399           in_buf[1] == SHELL_NLIP_DATA_START2) {
1400             rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
1401         }
1402 
1403         /* serve errors: out of decode memory, or bad encoding */
1404         if (rc == 1) {
1405             boot_serial_input(&dec_buf[2], dec_off - 2);
1406         }
1407         off = 0;
1408 check_timeout:
1409         /* Subtract elapsed time */
1410 #ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1411         elapsed_in_ms = (k_uptime_get_32() - start);
1412 #endif
1413         timeout_in_ms -= elapsed_in_ms;
1414     }
1415 }
1416 
1417 /*
1418  * Task which waits reading console, expecting to get image over
1419  * serial port.
1420  */
1421 void
boot_serial_start(const struct boot_uart_funcs * f)1422 boot_serial_start(const struct boot_uart_funcs *f)
1423 {
1424     bs_entry = true;
1425     boot_serial_read_console(f,0);
1426 }
1427 
1428 #ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1429 /*
1430  * Task which waits reading console for a certain amount of timeout.
1431  * If within this timeout no mcumgr command is received, the function is
1432  * returning, else the serial boot is never exited
1433  */
1434 void
boot_serial_check_start(const struct boot_uart_funcs * f,int timeout_in_ms)1435 boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
1436 {
1437     bs_entry = false;
1438     boot_serial_read_console(f,timeout_in_ms);
1439 }
1440 #endif
1441 
1442 #ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
1443 /* Function to find the hash of an image, returns 0 on success. */
boot_serial_get_hash(const struct image_header * hdr,const struct flash_area * fap,uint8_t * hash)1444 static int boot_serial_get_hash(const struct image_header *hdr,
1445                                 const struct flash_area *fap, uint8_t *hash)
1446 {
1447     struct image_tlv_iter it;
1448     uint32_t offset;
1449     uint16_t len;
1450     uint16_t type;
1451     int rc;
1452 
1453     /* Manifest data is concatenated to the end of the image.
1454      * It is encoded in TLV format.
1455      */
1456     rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
1457     if (rc) {
1458         return -1;
1459     }
1460 
1461     /* Traverse through the TLV area to find the image hash TLV. */
1462     while (true) {
1463         rc = bootutil_tlv_iter_next(&it, &offset, &len, &type);
1464         if (rc < 0) {
1465             return -1;
1466         } else if (rc > 0) {
1467             break;
1468         }
1469 
1470         if (type == IMAGE_TLV_SHA256) {
1471             /* Get the image's hash value from the manifest section. */
1472             if (len != 32) {
1473                 return -1;
1474             }
1475 
1476             rc = flash_area_read(fap, offset, hash, len);
1477             if (rc) {
1478                 return -1;
1479             }
1480 
1481             return 0;
1482         }
1483     }
1484 
1485     return -1;
1486 }
1487 #endif
1488