blob: 3866834eb0431152d31311fde702b6aedb4f979a [file] [log] [blame]
Christopher Collins92ea77f2016-12-12 15:59:26 -08001/*
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>
Almir Okato90be6e62022-09-23 14:52:25 -030024#include <errno.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080025
26#include "sysflash/sysflash.h"
27
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020028#include "bootutil/bootutil_log.h"
29
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020030#ifdef __ZEPHYR__
Fabio Baltieri888e2612022-07-19 20:54:26 +000031#include <zephyr/sys/reboot.h>
32#include <zephyr/sys/byteorder.h>
33#include <zephyr/sys/__assert.h>
34#include <zephyr/drivers/flash.h>
Gerard Marull-Paretas4eca54f2022-10-06 11:45:11 +020035#include <zephyr/kernel.h>
Fabio Baltieri888e2612022-07-19 20:54:26 +000036#include <zephyr/sys/crc.h>
37#include <zephyr/sys/base64.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030038#include <hal/hal_flash.h>
39#elif __ESPRESSIF__
40#include <bootloader_utility.h>
41#include <esp_rom_sys.h>
Almir Okato7d3622f2022-10-20 12:44:58 -030042#include <esp_crc.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030043#include <endian.h>
44#include <mbedtls/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020045#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080046#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080047#include <hal/hal_system.h>
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030048#include <hal/hal_flash.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080049#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020051#include <crc/crc16.h>
52#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020053#endif /* __ZEPHYR__ */
54
Jamie McCraecb07e882023-04-14 09:28:24 +010055#include <zcbor_decode.h>
56#include <zcbor_encode.h>
57#include "zcbor_bulk.h"
58
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020059#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020060#include <os/os.h>
61#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080062
63#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020064#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080065
66#include "boot_serial/boot_serial.h"
67#include "boot_serial_priv.h"
Almir Okatoe8cbc0d2022-06-13 10:45:39 -030068#include "mcuboot_config/mcuboot_config.h"
Christopher Collins92ea77f2016-12-12 15:59:26 -080069
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000070#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020071#include "bootutil_priv.h"
72#endif
73
Wouter Cappelle953a7612021-05-03 16:53:05 +020074#ifdef MCUBOOT_ENC_IMAGES
75#include "single_loader.h"
76#endif
77
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020078#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010079
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020080BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010081
Jamie McCraecb07e882023-04-14 09:28:24 +010082#ifndef ARRAY_SIZE
83#define ARRAY_SIZE ZCBOR_ARRAY_SIZE
84#endif
85
Jamie McCraead1fb3d2022-12-01 14:24:37 +000086#ifndef MCUBOOT_SERIAL_MAX_RECEIVE_SIZE
87#define MCUBOOT_SERIAL_MAX_RECEIVE_SIZE 512
88#endif
89
Jamie McCraefac2cab2023-03-30 10:07:36 +010090#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
91#define BOOT_SERIAL_IMAGE_STATE_SIZE_MAX 48
92#else
93#define BOOT_SERIAL_IMAGE_STATE_SIZE_MAX 0
94#endif
95#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
96#define BOOT_SERIAL_HASH_SIZE_MAX 36
97#else
98#define BOOT_SERIAL_HASH_SIZE_MAX 0
99#endif
100
101#define BOOT_SERIAL_OUT_MAX ((128 + BOOT_SERIAL_IMAGE_STATE_SIZE_MAX + \
102 BOOT_SERIAL_HASH_SIZE_MAX) * BOOT_IMAGE_NUMBER)
103
Piotr Dymaczf5e77532022-10-30 17:43:45 +0100104#define BOOT_SERIAL_FRAME_MTU 124 /* 127 - pkt start (2 bytes) and stop (1 byte) */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800105
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200106#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +0200107/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200108#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
109
110#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
111#define CRC_CITT_POLYMINAL 0x1021
112
113#define ntohs(x) sys_be16_to_cpu(x)
114#define htons(x) sys_cpu_to_be16(x)
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300115#elif __ESPRESSIF__
116#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
117#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
118
119#define ntohs(x) be16toh(x)
120#define htons(x) htobe16(x)
121
122#define base64_decode mbedtls_base64_decode
123#define base64_encode mbedtls_base64_encode
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200124#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +0100125
Fabio Utzig6f49c272019-08-23 11:42:58 -0300126#if (BOOT_IMAGE_NUMBER > 1)
127#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
128#else
129#define IMAGES_ITER(x)
130#endif
131
Jamie McCraead1fb3d2022-12-01 14:24:37 +0000132static char in_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
133static char dec_buf[MCUBOOT_SERIAL_MAX_RECEIVE_SIZE + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -0700134const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800135static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100136static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800137
138static char bs_obuf[BOOT_SERIAL_OUT_MAX];
139
Christopher Collins92ea77f2016-12-12 15:59:26 -0800140static void boot_serial_output(void);
141
Jamie McCrae827118f2023-03-10 13:24:57 +0000142#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
143static int boot_serial_get_hash(const struct image_header *hdr,
144 const struct flash_area *fap, uint8_t *hash);
145#endif
146
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100147static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800148
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000149void reset_cbor_state(void)
150{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100151 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
Daniel DeGrassec393b542023-05-23 21:52:09 +0000152 sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000153}
154
Dominik Ermel3d51e432021-06-25 17:29:50 +0000155/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000156 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
157 * used to process any groups that have not been processed by generic boot
158 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000159 *
160 * @param[in] hdr -- the decoded header of mcumgr message;
161 * @param[in] buffer -- buffer with first mcumgr message;
162 * @param[in] len -- length of of data in buffer;
163 * @param[out] *cs -- object with encoded response.
164 *
165 * @return 0 on success; non-0 error code otherwise.
166 */
167extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
168 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100169 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800170
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000171#define zcbor_tstr_put_lit_cast(state, string) \
Jamie McCrae393af792023-04-14 11:31:16 +0100172 zcbor_tstr_encode_ptr(state, (char *)string, sizeof(string) - 1)
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000173
174#ifndef MCUBOOT_USE_SNPRINTF
Christopher Collins92ea77f2016-12-12 15:59:26 -0800175/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300176 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800177 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300178static int
179u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800180{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300181 char *dst;
182 uint32_t d = 1;
183 uint32_t dgt;
184 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800185
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300186 dst = tgt;
187 while (val / d >= 10) {
188 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800189 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300190 while (d) {
191 dgt = val / d;
192 val %= d;
193 d /= 10;
194 if (n || dgt > 0 || d == 0) {
195 *dst++ = dgt + '0';
196 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800197 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800198 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300199 *dst = '\0';
200
201 return dst - tgt;
202}
203
204/*
205 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
206 */
207static void
208bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
209{
210 int off;
211
212 off = u32toa(dst, ver->iv_major);
213 dst[off++] = '.';
214 off += u32toa(dst + off, ver->iv_minor);
215 dst[off++] = '.';
216 off += u32toa(dst + off, ver->iv_revision);
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000217
218 if (ver->iv_build_num != 0) {
219 dst[off++] = '.';
220 off += u32toa(dst + off, ver->iv_build_num);
221 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800222}
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000223#else
224/*
225 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
226 */
227static void
228bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
229{
Jamie McCraee5c57dd2023-03-21 14:45:21 +0000230 int len;
231
232 len = snprintf(dst, maxlen, "%hu.%hu.%hu", (uint16_t)ver->iv_major,
233 (uint16_t)ver->iv_minor, ver->iv_revision);
234
235 if (ver->iv_build_num != 0 && len > 0 && len < maxlen) {
236 snprintf(&dst[len], (maxlen - len), "%u", ver->iv_build_num);
237 }
Dominik Ermeld49cfc12022-06-09 08:24:48 +0000238}
239#endif /* !MCUBOOT_USE_SNPRINTF */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800240
241/*
242 * List images.
243 */
244static void
245bs_list(char *buf, int len)
246{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800247 struct image_header hdr;
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100248 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800249 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300250 uint8_t image_index;
Jamie McCrae827118f2023-03-10 13:24:57 +0000251#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
252 uint8_t hash[32];
253#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800254
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100255 zcbor_map_start_encode(cbor_state, 1);
256 zcbor_tstr_put_lit_cast(cbor_state, "images");
257 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300258 image_index = 0;
259 IMAGES_ITER(image_index) {
Jamie McCraefac2cab2023-03-30 10:07:36 +0100260#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
261 int swap_status = boot_swap_type_multi(image_index);
262#endif
263
Fabio Utzig6f49c272019-08-23 11:42:58 -0300264 for (slot = 0; slot < 2; slot++) {
Jamie McCrae82feb9a2023-06-26 09:35:05 +0100265 FIH_DECLARE(fih_rc, FIH_FAILURE);
Jamie McCraefac2cab2023-03-30 10:07:36 +0100266 uint8_t tmpbuf[64];
267
268#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
269 bool active = false;
270 bool confirmed = false;
271 bool pending = false;
272 bool permanent = false;
273#endif
274
Fabio Utzig6f49c272019-08-23 11:42:58 -0300275 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
276 if (flash_area_open(area_id, &fap)) {
277 continue;
278 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800279
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200280 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
281 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
282 if (rc == BOOT_HOOK_REGULAR)
283 {
284 flash_area_read(fap, 0, &hdr, sizeof(hdr));
285 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800286
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200287 if (hdr.ih_magic == IMAGE_MAGIC)
288 {
289 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
Michael Grand5047f032022-11-24 16:49:56 +0100290 FIH_BOOT_HOOK_REGULAR,
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200291 fih_rc, image_index, slot);
Michael Grand5047f032022-11-24 16:49:56 +0100292 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200293 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200294#ifdef MCUBOOT_ENC_IMAGES
295 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
296 /* Clear the encrypted flag we didn't supply a key
297 * This flag could be set if there was a decryption in place
298 * performed before. We will try to validate the image without
299 * decryption by clearing the flag in the heder. If
300 * still encrypted the validation will fail.
301 */
302 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
303 }
304#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200305 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
306 NULL, 0, NULL);
307 }
Jamie McCrae82feb9a2023-06-26 09:35:05 +0100308 }
Jamie McCraefac2cab2023-03-30 10:07:36 +0100309
Jamie McCrae82feb9a2023-06-26 09:35:05 +0100310 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
311 flash_area_close(fap);
312 continue;
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200313 }
314
Jamie McCrae827118f2023-03-10 13:24:57 +0000315#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
316 /* Retrieve SHA256 hash of image for identification */
317 rc = boot_serial_get_hash(&hdr, fap, hash);
318#endif
319
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200320 flash_area_close(fap);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100321 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300322
323#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100324 zcbor_tstr_put_lit_cast(cbor_state, "image");
325 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300326#endif
327
Jamie McCraefac2cab2023-03-30 10:07:36 +0100328#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
329 if (swap_status == BOOT_SWAP_TYPE_NONE) {
330 if (slot == BOOT_PRIMARY_SLOT) {
331 confirmed = true;
332 active = true;
333 }
334 } else if (swap_status == BOOT_SWAP_TYPE_TEST) {
335 if (slot == BOOT_PRIMARY_SLOT) {
336 confirmed = true;
337 } else {
338 pending = true;
339 }
340 } else if (swap_status == BOOT_SWAP_TYPE_PERM) {
341 if (slot == BOOT_PRIMARY_SLOT) {
342 confirmed = true;
343 } else {
344 pending = true;
345 permanent = true;
346 }
347 } else if (swap_status == BOOT_SWAP_TYPE_REVERT) {
348 if (slot == BOOT_PRIMARY_SLOT) {
349 active = true;
350 } else {
351 confirmed = true;
352 }
353 }
354
355 if (!(hdr.ih_flags & IMAGE_F_NON_BOOTABLE)) {
356 zcbor_tstr_put_lit_cast(cbor_state, "bootable");
Jamie McCrae82feb9a2023-06-26 09:35:05 +0100357 zcbor_bool_put(cbor_state, true);
Jamie McCraefac2cab2023-03-30 10:07:36 +0100358 }
359
360 if (confirmed) {
361 zcbor_tstr_put_lit_cast(cbor_state, "confirmed");
362 zcbor_bool_put(cbor_state, true);
363 }
364
365 if (active) {
366 zcbor_tstr_put_lit_cast(cbor_state, "active");
367 zcbor_bool_put(cbor_state, true);
368 }
369
370 if (pending) {
371 zcbor_tstr_put_lit_cast(cbor_state, "pending");
372 zcbor_bool_put(cbor_state, true);
373 }
374
375 if (permanent) {
376 zcbor_tstr_put_lit_cast(cbor_state, "permanent");
377 zcbor_bool_put(cbor_state, true);
378 }
379#endif
380
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100381 zcbor_tstr_put_lit_cast(cbor_state, "slot");
382 zcbor_uint32_put(cbor_state, slot);
Jamie McCrae827118f2023-03-10 13:24:57 +0000383
384#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
385 if (rc == 0) {
386 zcbor_tstr_put_lit_cast(cbor_state, "hash");
387 zcbor_bstr_encode_ptr(cbor_state, hash, sizeof(hash));
388 }
389#endif
390
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100391 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300392
393 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Jamie McCrae827118f2023-03-10 13:24:57 +0000394
Jamie McCrae393af792023-04-14 11:31:16 +0100395 zcbor_tstr_encode_ptr(cbor_state, (char *)tmpbuf, strlen((char *)tmpbuf));
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100396 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800397 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800398 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100399 zcbor_list_end_encode(cbor_state, 5);
400 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800401 boot_serial_output();
402}
403
Jamie McCraefac2cab2023-03-30 10:07:36 +0100404#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
405/*
406 * Set image state.
407 */
408static void
409bs_set(char *buf, int len)
410{
411 /*
412 * Expected data format.
413 * {
414 * "confirm":<true for confirm, false for test>
415 * "hash":<hash of image (OPTIONAL for single image only)>
416 * }
417 */
418 uint8_t image_index = 0;
419 size_t decoded = 0;
420 uint8_t hash[32];
421 bool confirm;
422 struct zcbor_string img_hash;
423 bool ok;
424 int rc;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000425
Jamie McCraefac2cab2023-03-30 10:07:36 +0100426#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
427 bool found = false;
428#endif
429
430 zcbor_state_t zsd[4];
431 zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1);
432
433 struct zcbor_map_decode_key_val image_set_state_decode[] = {
434 ZCBOR_MAP_DECODE_KEY_DECODER("confirm", zcbor_uint32_decode, &confirm),
435#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
436 ZCBOR_MAP_DECODE_KEY_DECODER("hash", zcbor_bstr_decode, &img_hash),
437#endif
438 };
439
440 ok = zcbor_map_decode_bulk(zsd, image_set_state_decode, ARRAY_SIZE(image_set_state_decode),
441 &decoded) == 0;
442
443 if (!ok || len != decoded) {
444 rc = MGMT_ERR_EINVAL;
445 goto out;
446 }
447
448#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
449 if ((img_hash.len != sizeof(hash) && img_hash.len != 0) ||
450 (img_hash.len == 0 && BOOT_IMAGE_NUMBER > 1)) {
451 /* Hash is required and was not provided or is invalid size */
452 rc = MGMT_ERR_EINVAL;
453 goto out;
454 }
455
456 if (img_hash.len != 0) {
457 for (image_index = 0; image_index < BOOT_IMAGE_NUMBER; ++image_index) {
458 struct image_header hdr;
459 uint32_t area_id;
460 const struct flash_area *fap;
461 uint8_t tmpbuf[64];
462
463 area_id = flash_area_id_from_multi_image_slot(image_index, 1);
464 if (flash_area_open(area_id, &fap)) {
465 BOOT_LOG_ERR("Failed to open flash area ID %d", area_id);
466 continue;
467 }
468
469 rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
470 BOOT_HOOK_REGULAR, image_index, 1, &hdr);
471 if (rc == BOOT_HOOK_REGULAR)
472 {
473 flash_area_read(fap, 0, &hdr, sizeof(hdr));
474 }
475
476 if (hdr.ih_magic == IMAGE_MAGIC)
477 {
478 FIH_DECLARE(fih_rc, FIH_FAILURE);
479
480 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
481 FIH_BOOT_HOOK_REGULAR,
482 fih_rc, image_index, 1);
483 if (FIH_EQ(fih_rc, FIH_BOOT_HOOK_REGULAR))
484 {
485 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap,
486 tmpbuf, sizeof(tmpbuf), NULL, 0, NULL);
487 }
488
489 if (FIH_NOT_EQ(fih_rc, FIH_SUCCESS)) {
490 continue;
491 }
492 }
493
494 /* Retrieve SHA256 hash of image for identification */
495 rc = boot_serial_get_hash(&hdr, fap, hash);
496 flash_area_close(fap);
497
498 if (rc == 0 && memcmp(hash, img_hash.value, sizeof(hash)) == 0) {
499 /* Hash matches, set this slot for test or confirmation */
500 found = true;
501 break;
502 }
503 }
504
505 if (!found) {
506 /* Image was not found with specified hash */
507 BOOT_LOG_ERR("Did not find image with specified hash");
508 rc = MGMT_ERR_ENOENT;
509 goto out;
510 }
511 }
512#endif
513
514 rc = boot_set_pending_multi(image_index, confirm);
515
516out:
517 if (rc == 0) {
518 /* Success - return updated list of images */
519 bs_list(buf, len);
520 } else {
521 /* Error code, only return the error */
522 zcbor_map_start_encode(cbor_state, 10);
523 zcbor_tstr_put_lit_cast(cbor_state, "rc");
524 zcbor_int32_put(cbor_state, rc);
525 zcbor_map_end_encode(cbor_state, 10);
526
527 boot_serial_output();
528 }
529}
530#endif
531
532/*
533 * Send rc code only.
534 */
535static void
536bs_rc_rsp(int rc_code)
537{
538 zcbor_map_start_encode(cbor_state, 10);
539 zcbor_tstr_put_lit_cast(cbor_state, "rc");
540 zcbor_int32_put(cbor_state, rc_code);
541 zcbor_map_end_encode(cbor_state, 10);
542 boot_serial_output();
543}
544
545static void
546bs_list_set(uint8_t op, char *buf, int len)
547{
548 if (op == NMGR_OP_READ) {
549 bs_list(buf, len);
550 } else {
551#ifdef MCUBOOT_SERIAL_IMG_GRP_IMAGE_STATE
552 bs_set(buf, len);
553#else
554 bs_rc_rsp(MGMT_ERR_ENOTSUP);
555#endif
556 }
557}
558
559#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000560/** Erases range of flash, aligned to sector size
561 *
562 * Function will erase all sectors withing [start, end] range; it does not check
563 * the @p start for alignment, and it will use @p end to find boundaries of las
564 * sector to erase. Function returns offset of the first byte past the last
565 * erased sector, so basically offset of next sector to be erased if needed.
566 * The function is intended to be called iteratively with previously returned
567 * offset as @p start.
568 *
569 * @param start starting offset, aligned to sector offset;
570 * @param end ending offset, maybe anywhere within sector;
571 *
572 * @retval On success: offset of the first byte past last erased sector;
573 * On failure: -EINVAL.
574 */
575static off_t erase_range(const struct flash_area *fap, off_t start, off_t end)
576{
577 struct flash_sector sect;
578 size_t size;
579 int rc;
580
581 if (end >= flash_area_get_size(fap)) {
582 return -EINVAL;
583 }
584
585 if (end < start) {
586 return start;
587 }
588
Dominik Ermel24769882023-01-05 13:36:35 +0000589 if (flash_area_get_sector(fap, end, &sect)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000590 return -EINVAL;
591 }
592
593 size = flash_sector_get_off(&sect) + flash_sector_get_size(&sect) - start;
Stephanos Ioannidis09e2bd72022-07-11 22:01:49 +0900594 BOOT_LOG_INF("Erasing range 0x%jx:0x%jx", (intmax_t)start,
595 (intmax_t)(start + size - 1));
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000596
597 rc = flash_area_erase(fap, start, size);
598 if (rc != 0) {
599 BOOT_LOG_ERR("Error %d while erasing range", rc);
600 return -EINVAL;
601 }
602
603 return start + size;
604}
605#endif
606
Christopher Collins92ea77f2016-12-12 15:59:26 -0800607/*
608 * Image upload request.
609 */
610static void
611bs_upload(char *buf, int len)
612{
Dominik Ermel5bd87442022-06-13 15:14:01 +0000613 static size_t img_size; /* Total image size, held for duration of upload */
614 static uint32_t curr_off; /* Expected current offset */
615 const uint8_t *img_chunk = NULL; /* Pointer to buffer with received image chunk */
616 size_t img_chunk_len = 0; /* Length of received image chunk */
617 size_t img_chunk_off = SIZE_MAX; /* Offset of image chunk within image */
618 uint8_t rem_bytes; /* Reminder bytes after aligning chunk write to
619 * to flash alignment */
Jamie McCraecb07e882023-04-14 09:28:24 +0100620 uint32_t img_num;
Dominik Ermel5bd87442022-06-13 15:14:01 +0000621 size_t img_size_tmp = SIZE_MAX; /* Temp variable for image size */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800622 const struct flash_area *fap = NULL;
623 int rc;
Jamie McCraecb07e882023-04-14 09:28:24 +0100624 struct zcbor_string img_chunk_data;
625 size_t decoded = 0;
626 bool ok;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000627#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000628 static off_t not_yet_erased = 0; /* Offset of next byte to erase; writes to flash
629 * are done in consecutive manner and erases are done
630 * to allow currently received chunk to be written;
631 * this state variable holds information where last
632 * erase has stopped to let us know whether erase
633 * is needed to be able to write current chunk.
634 */
635 static struct flash_sector status_sector;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200636#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800637
Jamie McCraecb07e882023-04-14 09:28:24 +0100638 zcbor_state_t zsd[4];
639 zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1);
640
641 struct zcbor_map_decode_key_val image_upload_decode[] = {
642 ZCBOR_MAP_DECODE_KEY_DECODER("image", zcbor_uint32_decode, &img_num),
643 ZCBOR_MAP_DECODE_KEY_DECODER("data", zcbor_bstr_decode, &img_chunk_data),
644 ZCBOR_MAP_DECODE_KEY_DECODER("len", zcbor_size_decode, &img_size_tmp),
645 ZCBOR_MAP_DECODE_KEY_DECODER("off", zcbor_size_decode, &img_chunk_off),
646 };
647
648 ok = zcbor_map_decode_bulk(zsd, image_upload_decode, ARRAY_SIZE(image_upload_decode),
649 &decoded) == 0;
650
651 if (!ok) {
652 goto out_invalid_data;
653 }
654
655 img_chunk = img_chunk_data.value;
656 img_chunk_len = img_chunk_data.len;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300657
658 /*
659 * Expected data format.
660 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300661 * "image":<image number in a multi-image set (OPTIONAL)>
662 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300663 * "len":<image len>
664 * "off":<current offset of image data>
665 * }
666 */
667
Dominik Ermel5bd87442022-06-13 15:14:01 +0000668 if (img_chunk_off == SIZE_MAX || img_chunk == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300669 /*
670 * Offset must be set in every block.
671 */
672 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800673 }
674
Dominik Ermel48decca2021-07-09 10:23:58 +0000675#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300676 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000677#else
678 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
679#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800680 if (rc) {
681 rc = MGMT_ERR_EINVAL;
682 goto out;
683 }
684
Dominik Ermel5bd87442022-06-13 15:14:01 +0000685 if (img_chunk_off == 0) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000686 /* Receiving chunk with 0 offset resets the upload state; this basically
687 * means that upload has started from beginning.
688 */
689 const size_t area_size = flash_area_get_size(fap);
Dominik Ermel5bd87442022-06-13 15:14:01 +0000690
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000691 curr_off = 0;
692#ifdef MCUBOOT_ERASE_PROGRESSIVELY
693 /* Get trailer sector information; this is done early because inability to get
694 * that sector information means that upload will not work anyway.
695 * TODO: This is single occurrence issue, it should get detected during tests
696 * and fixed otherwise you are deploying broken mcuboot.
697 */
Dominik Ermel24769882023-01-05 13:36:35 +0000698 if (flash_area_get_sector(fap, boot_status_off(fap), &status_sector)) {
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000699 rc = MGMT_ERR_EUNKNOWN;
700 BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
701 goto out;
702 }
703#endif
704
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200705#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
706 /* We are using swap state at end of flash area to store validation
707 * result. Make sure the user cannot write it from an image to skip validation.
708 */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000709 if (img_size_tmp > (area_size - BOOT_MAGIC_SZ)) {
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200710 goto out_invalid_data;
711 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000712#else
713 if (img_size_tmp > area_size) {
714 goto out_invalid_data;
715 }
716
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200717#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000718
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000719#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000720 /* Non-progressive erase erases entire image slot when first chunk of
721 * an image is received.
722 */
723 rc = flash_area_erase(fap, 0, area_size);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800724 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300725 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800726 }
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000727#else
728 not_yet_erased = 0;
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200729#endif
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000730
Dominik Ermel5bd87442022-06-13 15:14:01 +0000731 img_size = img_size_tmp;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000732 } else if (img_chunk_off != curr_off) {
733 /* If received chunk offset does not match expected one jump, pretend
734 * success and jump to out; out will respond to client with success
735 * and request the expected offset, held by curr_off.
736 */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800737 rc = 0;
738 goto out;
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000739 } else if (curr_off + img_chunk_len > img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200740 rc = MGMT_ERR_EINVAL;
741 goto out;
742 }
743
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000744#ifdef MCUBOOT_ERASE_PROGRESSIVELY
745 /* Progressive erase will erase enough flash, aligned to sector size,
746 * as needed for the current chunk to be written.
747 */
748 not_yet_erased = erase_range(fap, not_yet_erased,
749 curr_off + img_chunk_len - 1);
750
751 if (not_yet_erased < 0) {
752 rc = MGMT_ERR_EINVAL;
753 goto out;
754 }
755#endif
756
757 /* Writes are aligned to flash write alignment, so may drop a few bytes
758 * from the end of the buffer; we will request these bytes again with
759 * new buffer by responding with request for offset after the last aligned
760 * write.
761 */
Dominik Ermel5bd87442022-06-13 15:14:01 +0000762 rem_bytes = img_chunk_len % flash_area_align(fap);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000763 img_chunk_len -= rem_bytes;
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200764
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000765 if (curr_off + img_chunk_len + rem_bytes < img_size) {
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200766 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300767 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200768
Dominik Ermel5bd87442022-06-13 15:14:01 +0000769 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_chunk_len);
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000770 /* Write flash aligned chunk, note that img_chunk_len now holds aligned length */
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000771#if defined(MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE) && MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE > 0
772 if (flash_area_align(fap) > 1 &&
773 (((size_t)img_chunk) & (flash_area_align(fap) - 1)) != 0) {
774 /* Buffer address incompatible with write address, use buffer to write */
775 uint8_t write_size = MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE;
776 uint8_t wbs_aligned[MCUBOOT_SERIAL_UNALIGNED_BUFFER_SIZE];
777
778 while (img_chunk_len >= flash_area_align(fap)) {
779 if (write_size > img_chunk_len) {
780 write_size = img_chunk_len;
781 }
782
783 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
784 memcpy(wbs_aligned, img_chunk, write_size);
785
786 rc = flash_area_write(fap, curr_off, wbs_aligned, write_size);
787
788 if (rc != 0) {
789 goto out;
790 }
791
792 curr_off += write_size;
793 img_chunk += write_size;
794 img_chunk_len -= write_size;
795 }
796 } else {
797 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
798 }
799#else
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000800 rc = flash_area_write(fap, curr_off, img_chunk, img_chunk_len);
Jamie McCrae9d3fd7f2022-11-30 15:44:44 +0000801#endif
802
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000803 if (rc == 0 && rem_bytes) {
804 /* Non-zero rem_bytes means that last chunk needs alignment; the aligned
805 * part, in the img_chunk_len - rem_bytes count bytes, has already been
806 * written by the above write, so we are left with the rem_bytes.
807 */
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200808 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200809
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000810 memset(wbs_aligned, flash_area_erased_val(fap), sizeof(wbs_aligned));
811 memcpy(wbs_aligned, img_chunk + img_chunk_len, rem_bytes);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200812
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000813 rc = flash_area_write(fap, curr_off + img_chunk_len, wbs_aligned,
814 flash_area_align(fap));
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200815 }
816
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300817 if (rc == 0) {
Dominik Ermel7d2f0bf2022-06-21 16:15:34 +0000818 curr_off += img_chunk_len + rem_bytes;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200819 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200820#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200821 /* Assure that sector for image trailer was erased. */
822 /* Check whether it was erased during previous upload. */
Dominik Ermelbcc17b42022-06-15 15:33:04 +0000823 off_t start = flash_sector_get_off(&status_sector);
824
825 if (erase_range(fap, start, start) < 0) {
826 rc = MGMT_ERR_EUNKNOWN;
827 goto out;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200828 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200829#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200830 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
831 img_size);
832 if (rc) {
833 BOOT_LOG_ERR("Error %d post upload hook", rc);
834 goto out;
835 }
836 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300837 } else {
838 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800839 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800840 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200841
Christopher Collins92ea77f2016-12-12 15:59:26 -0800842out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200843 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100844 zcbor_map_start_encode(cbor_state, 10);
845 zcbor_tstr_put_lit_cast(cbor_state, "rc");
Jamie McCrae0b6d3432022-12-02 09:24:10 +0000846 zcbor_int32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800847 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100848 zcbor_tstr_put_lit_cast(cbor_state, "off");
849 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800850 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100851 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800852
853 boot_serial_output();
854 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200855
856#ifdef MCUBOOT_ENC_IMAGES
857 if (curr_off == img_size) {
858 /* Last sector received, now start a decryption on the image if it is encrypted*/
859 rc = boot_handle_enc_fw();
860 }
861#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800862}
863
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200864#ifdef MCUBOOT_BOOT_MGMT_ECHO
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200865static void
866bs_echo(char *buf, int len)
867{
Jamie McCraecb07e882023-04-14 09:28:24 +0100868 struct zcbor_string value = { 0 };
869 struct zcbor_string key;
870 bool ok;
Dominik Ermel88bd5672022-06-07 15:17:06 +0000871 uint32_t rc = MGMT_ERR_EINVAL;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200872
Jamie McCraecb07e882023-04-14 09:28:24 +0100873 zcbor_state_t zsd[4];
874 zcbor_new_state(zsd, sizeof(zsd) / sizeof(zcbor_state_t), (uint8_t *)buf, len, 1);
875
876 if (!zcbor_map_start_decode(zsd)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000877 goto out;
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200878 }
Dominik Ermel88bd5672022-06-07 15:17:06 +0000879
Jamie McCraecb07e882023-04-14 09:28:24 +0100880 do {
881 ok = zcbor_tstr_decode(zsd, &key);
882
883 if (ok) {
884 if (key.len == 1 && *key.value == 'd') {
885 ok = zcbor_tstr_decode(zsd, &value);
886 break;
887 }
888
889 ok = zcbor_any_skip(zsd, NULL);
890 }
891 } while (ok);
892
893 if (!ok || !zcbor_map_end_decode(zsd)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000894 goto out;
895 }
896
897 zcbor_map_start_encode(cbor_state, 10);
898 zcbor_tstr_put_term(cbor_state, "r");
Jamie McCraecb07e882023-04-14 09:28:24 +0100899 if (zcbor_tstr_encode(cbor_state, &value) && zcbor_map_end_encode(cbor_state, 10)) {
Dominik Ermel88bd5672022-06-07 15:17:06 +0000900 boot_serial_output();
901 return;
902 } else {
903 rc = MGMT_ERR_ENOMEM;
904 }
905
906out:
907 reset_cbor_state();
908 bs_rc_rsp(rc);
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200909}
910#endif
911
Christopher Collins92ea77f2016-12-12 15:59:26 -0800912/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800913 * Reset, and (presumably) boot to newly uploaded image. Flush console
914 * before restarting.
915 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200916static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800917bs_reset(char *buf, int len)
918{
Dominik Ermelb26fc482022-12-09 17:10:20 +0000919 int rc = BOOT_HOOK_CALL(boot_reset_request_hook, 0, false);
920 if (rc == BOOT_RESET_REQUEST_HOOK_BUSY) {
921 rc = MGMT_ERR_EBUSY;
922 } else {
923 /* Currently whatever else is returned it is just converted
924 * to 0/no error. Boot serial starts accepting "force" parameter
925 * in command this needs to change.
926 */
927 rc = 0;
928 }
929 bs_rc_rsp(rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800930
Dominik Ermelb26fc482022-12-09 17:10:20 +0000931 if (rc == 0) {
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200932#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200933#ifdef CONFIG_MULTITHREADING
Dominik Ermelb26fc482022-12-09 17:10:20 +0000934 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200935#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000936 k_busy_wait(250000);
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200937#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000938 sys_reboot(SYS_REBOOT_COLD);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -0300939#elif __ESPRESSIF__
Dominik Ermelb26fc482022-12-09 17:10:20 +0000940 esp_rom_delay_us(250000);
941 bootloader_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200942#else
Dominik Ermelb26fc482022-12-09 17:10:20 +0000943 os_cputime_delay_usecs(250000);
944 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200945#endif
Dominik Ermelb26fc482022-12-09 17:10:20 +0000946 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800947}
948
949/*
950 * Parse incoming line of input from console.
951 * Expect newtmgr protocol with serial transport.
952 */
953void
954boot_serial_input(char *buf, int len)
955{
956 struct nmgr_hdr *hdr;
957
958 hdr = (struct nmgr_hdr *)buf;
959 if (len < sizeof(*hdr) ||
960 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
961 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
962 return;
963 }
964 bs_hdr = hdr;
965 hdr->nh_group = ntohs(hdr->nh_group);
966
967 buf += sizeof(*hdr);
968 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300969
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000970 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800971
972 /*
973 * Limited support for commands.
974 */
975 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
976 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300977 case IMGMGR_NMGR_ID_STATE:
Jamie McCraefac2cab2023-03-30 10:07:36 +0100978 bs_list_set(hdr->nh_op, buf, len);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800979 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300980 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800981 bs_upload(buf, len);
982 break;
983 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000984 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800985 break;
986 }
987 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
988 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200989 case NMGR_ID_ECHO:
990#ifdef MCUBOOT_BOOT_MGMT_ECHO
991 bs_echo(buf, len);
992#endif
993 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800994 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000995 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800996 break;
997 case NMGR_ID_RESET:
998 bs_reset(buf, len);
999 break;
1000 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +00001001 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001002 break;
1003 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +00001004 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +01001005 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +00001006 boot_serial_output();
1007 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +00001008 } else {
1009 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001010 }
Wouter Cappellee3822f82022-01-19 15:39:43 +01001011#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1012 bs_entry = true;
1013#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -08001014}
1015
1016static void
1017boot_serial_output(void)
1018{
1019 char *data;
Piotr Dymaczf5e77532022-10-30 17:43:45 +01001020 int len, out;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001021 uint16_t crc;
1022 uint16_t totlen;
Piotr Dymaczf5e77532022-10-30 17:43:45 +01001023 char pkt_cont[2] = { SHELL_NLIP_DATA_START1, SHELL_NLIP_DATA_START2 };
Christopher Collins92ea77f2016-12-12 15:59:26 -08001024 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +00001025 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
1026 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -08001027
1028 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +01001029 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001030
1031 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +03001032 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001033 bs_hdr->nh_len = htons(len);
1034 bs_hdr->nh_group = htons(bs_hdr->nh_group);
1035
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001036#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +01001037 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
1038 crc = crc16_itu_t(crc, data, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -03001039#elif __ESPRESSIF__
1040 /* For ESP32 it was used the CRC API in rom/crc.h */
Almir Okato7d3622f2022-10-20 12:44:58 -03001041 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
1042 crc = ~esp_crc16_be(~crc, (uint8_t *)data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001043#else
Christopher Collins92ea77f2016-12-12 15:59:26 -08001044 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
1045 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001046#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -08001047 crc = htons(crc);
1048
Christopher Collins92ea77f2016-12-12 15:59:26 -08001049 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
1050 totlen = htons(totlen);
1051
1052 memcpy(buf, &totlen, sizeof(totlen));
1053 totlen = sizeof(totlen);
1054 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
1055 totlen += sizeof(*bs_hdr);
1056 memcpy(&buf[totlen], data, len);
1057 totlen += len;
1058 memcpy(&buf[totlen], &crc, sizeof(crc));
1059 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001060#ifdef __ZEPHYR__
1061 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +02001062 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001063 totlen = enc_len;
Almir Okatoe8cbc0d2022-06-13 10:45:39 -03001064#elif __ESPRESSIF__
1065 size_t enc_len;
1066 base64_encode((unsigned char *)encoded_buf, sizeof(encoded_buf), &enc_len, (unsigned char *)buf, totlen);
1067 totlen = enc_len;
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001068#else
Christopher Collins92ea77f2016-12-12 15:59:26 -08001069 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001070#endif
Piotr Dymaczf5e77532022-10-30 17:43:45 +01001071
1072 out = 0;
1073 while (out < totlen) {
1074 if (out == 0) {
1075 boot_uf->write(pkt_start, sizeof(pkt_start));
1076 } else {
1077 boot_uf->write(pkt_cont, sizeof(pkt_cont));
1078 }
1079
1080 len = MIN(BOOT_SERIAL_FRAME_MTU, totlen - out);
1081 boot_uf->write(&encoded_buf[out], len);
1082
1083 out += len;
1084
1085 boot_uf->write("\n", 1);
1086 }
1087
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001088 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -08001089}
1090
1091/*
1092 * Returns 1 if full packet has been received.
1093 */
1094static int
1095boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
1096{
1097 int rc;
1098 uint16_t crc;
1099 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +02001100
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001101#ifdef __ZEPHYR__
1102 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001103 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001104 if (err) {
1105 return -1;
1106 }
Almir Okatoe8cbc0d2022-06-13 10:45:39 -03001107#elif __ESPRESSIF__
1108 int err;
1109 err = base64_decode((unsigned char *)&out[*out_off], maxout - *out_off, (size_t *)&rc, (unsigned char *)in, inlen);
1110 if (err) {
1111 return -1;
1112 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001113#else
Christopher Collins92ea77f2016-12-12 15:59:26 -08001114 if (*out_off + base64_decode_len(in) >= maxout) {
1115 return -1;
1116 }
1117 rc = base64_decode(in, &out[*out_off]);
1118 if (rc < 0) {
1119 return -1;
1120 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +02001121#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -03001122
Christopher Collins92ea77f2016-12-12 15:59:26 -08001123 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -03001124 if (*out_off <= sizeof(uint16_t)) {
1125 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001126 }
Fabio Utzig6f49c272019-08-23 11:42:58 -03001127
1128 len = ntohs(*(uint16_t *)out);
1129 if (len != *out_off - sizeof(uint16_t)) {
1130 return 0;
1131 }
1132
1133 if (len > *out_off - sizeof(uint16_t)) {
1134 len = *out_off - sizeof(uint16_t);
1135 }
1136
1137 out += sizeof(uint16_t);
1138#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +01001139 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Almir Okatoe8cbc0d2022-06-13 10:45:39 -03001140#elif __ESPRESSIF__
Almir Okato7d3622f2022-10-20 12:44:58 -03001141 crc = ~esp_crc16_be(~CRC16_INITIAL_CRC, (uint8_t *)out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -03001142#else
1143 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
1144#endif
1145 if (crc || len <= sizeof(crc)) {
1146 return 0;
1147 }
1148 *out_off -= sizeof(crc);
1149 out[*out_off] = '\0';
1150
1151 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001152}
1153
1154/*
1155 * Task which waits reading console, expecting to get image over
1156 * serial port.
1157 */
Wouter Cappellee3822f82022-01-19 15:39:43 +01001158static void
1159boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -08001160{
1161 int rc;
1162 int off;
David Brown57f0df32020-05-12 08:39:21 -06001163 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001164 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +03001165 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +01001166 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001167
Marko Kiiskila149b4572018-06-06 14:18:54 +03001168 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +03001169 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001170
1171 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +01001172 while (timeout_in_ms > 0 || bs_entry) {
Piotr Dymacz067f30a2022-08-12 18:25:34 +02001173 /*
1174 * Don't enter CPU idle state here if timeout based serial recovery is
1175 * used as otherwise the boot process hangs forever, waiting for input
1176 * from serial console (if single-thread mode is used).
1177 */
Piotr Dymacz3942e9b2022-07-18 10:19:25 +02001178#ifndef MCUBOOT_SERIAL_WAIT_FOR_DFU
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +02001179 MCUBOOT_CPU_IDLE();
Piotr Dymacz3942e9b2022-07-18 10:19:25 +02001180#endif
Hein Wessels56d28f02021-11-19 08:42:08 +01001181 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +01001182#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1183 uint32_t start = k_uptime_get_32();
1184#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001185 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001186 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +01001187 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001188 }
1189 off += rc;
1190 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +03001191 if (off == max_input) {
1192 /*
1193 * Full line, no newline yet. Reset the input buffer.
1194 */
1195 off = 0;
1196 }
Wouter Cappellee3822f82022-01-19 15:39:43 +01001197 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001198 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001199 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
1200 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -08001201 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001202 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
1203 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
1204 in_buf[1] == SHELL_NLIP_DATA_START2) {
1205 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001206 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001207
1208 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -08001209 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +02001210 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -08001211 }
1212 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +01001213check_timeout:
1214 /* Subtract elapsed time */
1215#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1216 elapsed_in_ms = (k_uptime_get_32() - start);
1217#endif
1218 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -08001219 }
1220}
Wouter Cappellee3822f82022-01-19 15:39:43 +01001221
1222/*
1223 * Task which waits reading console, expecting to get image over
1224 * serial port.
1225 */
1226void
1227boot_serial_start(const struct boot_uart_funcs *f)
1228{
1229 bs_entry = true;
1230 boot_serial_read_console(f,0);
1231}
1232
1233#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
1234/*
1235 * Task which waits reading console for a certain amount of timeout.
1236 * If within this timeout no mcumgr command is received, the function is
1237 * returning, else the serial boot is never exited
1238 */
1239void
1240boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
1241{
1242 bs_entry = false;
1243 boot_serial_read_console(f,timeout_in_ms);
1244}
1245#endif
Jamie McCrae827118f2023-03-10 13:24:57 +00001246
1247#ifdef MCUBOOT_SERIAL_IMG_GRP_HASH
1248/* Function to find the hash of an image, returns 0 on success. */
1249static int boot_serial_get_hash(const struct image_header *hdr,
1250 const struct flash_area *fap, uint8_t *hash)
1251{
1252 struct image_tlv_iter it;
1253 uint32_t offset;
1254 uint16_t len;
1255 uint16_t type;
1256 int rc;
1257
1258 /* Manifest data is concatenated to the end of the image.
1259 * It is encoded in TLV format.
1260 */
1261 rc = bootutil_tlv_iter_begin(&it, hdr, fap, IMAGE_TLV_ANY, false);
1262 if (rc) {
1263 return -1;
1264 }
1265
1266 /* Traverse through the TLV area to find the image hash TLV. */
1267 while (true) {
1268 rc = bootutil_tlv_iter_next(&it, &offset, &len, &type);
1269 if (rc < 0) {
1270 return -1;
1271 } else if (rc > 0) {
1272 break;
1273 }
1274
1275 if (type == IMAGE_TLV_SHA256) {
1276 /* Get the image's hash value from the manifest section. */
1277 if (len != 32) {
1278 return -1;
1279 }
1280
1281 rc = flash_area_read(fap, offset, hash, len);
1282 if (rc) {
1283 return -1;
1284 }
1285
1286 return 0;
1287 }
1288 }
1289
1290 return -1;
1291}
1292#endif