blob: 4a4a63de051150a80295eaf8c03658b9da719752 [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>
24
25#include "sysflash/sysflash.h"
26
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020027#include "bootutil/bootutil_log.h"
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +010028#include "zcbor_encode.h"
Fabio Utzig1a2e41a2017-11-17 12:13:09 -020029
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020030#ifdef __ZEPHYR__
Dominik Ermel1eedec32021-12-16 12:55:02 +000031#include <sys/reboot.h>
Andrzej Puzdrowskif1d189c2019-12-12 09:34:11 +010032#include <sys/byteorder.h>
33#include <sys/__assert.h>
Peter Bigot54c1e3f2020-01-25 05:50:12 -060034#include <drivers/flash.h>
Andrzej Puzdrowskif1d189c2019-12-12 09:34:11 +010035#include <sys/crc.h>
36#include <sys/base64.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020037#else
Christopher Collins92ea77f2016-12-12 15:59:26 -080038#include <bsp/bsp.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080039#include <hal/hal_system.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080040#include <os/endian.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080041#include <os/os_cputime.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020042#include <crc/crc16.h>
43#include <base64/base64.h>
Andrzej Puzdrowski386b5922018-04-06 19:26:24 +020044#endif /* __ZEPHYR__ */
45
Andrzej Puzdrowskib788c712018-04-12 12:42:49 +020046#include <flash_map_backend/flash_map_backend.h>
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020047#include <hal/hal_flash.h>
48#include <os/os.h>
49#include <os/os_malloc.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080050
51#include <bootutil/image.h>
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +020052#include <bootutil/bootutil.h>
Christopher Collins92ea77f2016-12-12 15:59:26 -080053
54#include "boot_serial/boot_serial.h"
55#include "boot_serial_priv.h"
56
Dominik Ermel3d4e55d2021-07-09 11:14:10 +000057#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +020058#include "bootutil_priv.h"
59#endif
60
Wouter Cappelle953a7612021-05-03 16:53:05 +020061#ifdef MCUBOOT_ENC_IMAGES
62#include "single_loader.h"
63#endif
64
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010065#include "serial_recovery_cbor.h"
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +020066#include "bootutil/boot_hooks.h"
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +010067
Carlos Falgueras Garcíaa4b4b0f2021-06-22 10:00:22 +020068BOOT_LOG_MODULE_DECLARE(mcuboot);
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010069
Marko Kiiskila149b4572018-06-06 14:18:54 +030070#define BOOT_SERIAL_INPUT_MAX 512
Andrzej Puzdrowskic9ac5cc2021-11-19 11:58:05 +010071#define BOOT_SERIAL_OUT_MAX (128 * BOOT_IMAGE_NUMBER)
Christopher Collins92ea77f2016-12-12 15:59:26 -080072
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020073#ifdef __ZEPHYR__
Carles Cufi0165be82018-03-26 17:43:51 +020074/* base64 lib encodes data to null-terminated string */
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020075#define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
76
77#define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
78#define CRC_CITT_POLYMINAL 0x1021
79
80#define ntohs(x) sys_be16_to_cpu(x)
81#define htons(x) sys_cpu_to_be16(x)
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +020082#endif
Emanuele Di Santo9f1933d2018-11-20 10:59:59 +010083
Fabio Utzig6f49c272019-08-23 11:42:58 -030084#if (BOOT_IMAGE_NUMBER > 1)
85#define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
86#else
87#define IMAGES_ITER(x)
88#endif
89
Marko Kiiskila149b4572018-06-06 14:18:54 +030090static char in_buf[BOOT_SERIAL_INPUT_MAX + 1];
91static char dec_buf[BOOT_SERIAL_INPUT_MAX + 1];
Marko Kiiskila8b1ce3a2018-06-14 13:20:46 -070092const struct boot_uart_funcs *boot_uf;
Christopher Collins92ea77f2016-12-12 15:59:26 -080093static uint32_t curr_off;
94static uint32_t img_size;
95static struct nmgr_hdr *bs_hdr;
Wouter Cappellee3822f82022-01-19 15:39:43 +010096static bool bs_entry;
Christopher Collins92ea77f2016-12-12 15:59:26 -080097
98static char bs_obuf[BOOT_SERIAL_OUT_MAX];
99
Christopher Collins92ea77f2016-12-12 15:59:26 -0800100static void boot_serial_output(void);
101
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100102static zcbor_state_t cbor_state[2];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800103
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000104void reset_cbor_state(void)
105{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100106 zcbor_new_encode_state(cbor_state, 2, (uint8_t *)bs_obuf,
107 (size_t)bs_obuf + sizeof(bs_obuf), 0);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000108}
109
Dominik Ermel3d51e432021-06-25 17:29:50 +0000110/**
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000111 * Function that processes MGMT_GROUP_ID_PERUSER mcumgr group and may be
112 * used to process any groups that have not been processed by generic boot
113 * serial implementation.
Dominik Ermel3d51e432021-06-25 17:29:50 +0000114 *
115 * @param[in] hdr -- the decoded header of mcumgr message;
116 * @param[in] buffer -- buffer with first mcumgr message;
117 * @param[in] len -- length of of data in buffer;
118 * @param[out] *cs -- object with encoded response.
119 *
120 * @return 0 on success; non-0 error code otherwise.
121 */
122extern int bs_peruser_system_specific(const struct nmgr_hdr *hdr,
123 const char *buffer,
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100124 int len, zcbor_state_t *cs);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800125
126/*
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300127 * Convert version into string without use of snprintf().
Christopher Collins92ea77f2016-12-12 15:59:26 -0800128 */
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300129static int
130u32toa(char *tgt, uint32_t val)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800131{
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300132 char *dst;
133 uint32_t d = 1;
134 uint32_t dgt;
135 int n = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800136
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300137 dst = tgt;
138 while (val / d >= 10) {
139 d *= 10;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800140 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300141 while (d) {
142 dgt = val / d;
143 val %= d;
144 d /= 10;
145 if (n || dgt > 0 || d == 0) {
146 *dst++ = dgt + '0';
147 ++n;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800148 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800149 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300150 *dst = '\0';
151
152 return dst - tgt;
153}
154
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100155#define zcbor_tstr_put_lit_cast(state, string) \
156 zcbor_tstr_encode_ptr(state, (uint8_t *)string, sizeof(string) - 1)
157
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300158/*
159 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
160 */
161static void
162bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
163{
164 int off;
165
166 off = u32toa(dst, ver->iv_major);
167 dst[off++] = '.';
168 off += u32toa(dst + off, ver->iv_minor);
169 dst[off++] = '.';
170 off += u32toa(dst + off, ver->iv_revision);
171 dst[off++] = '.';
172 off += u32toa(dst + off, ver->iv_build_num);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800173}
174
175/*
176 * List images.
177 */
178static void
179bs_list(char *buf, int len)
180{
Christopher Collins92ea77f2016-12-12 15:59:26 -0800181 struct image_header hdr;
182 uint8_t tmpbuf[64];
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100183 uint32_t slot, area_id;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800184 const struct flash_area *fap;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300185 uint8_t image_index;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800186
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100187 zcbor_map_start_encode(cbor_state, 1);
188 zcbor_tstr_put_lit_cast(cbor_state, "images");
189 zcbor_list_start_encode(cbor_state, 5);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300190 image_index = 0;
191 IMAGES_ITER(image_index) {
192 for (slot = 0; slot < 2; slot++) {
193 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
194 if (flash_area_open(area_id, &fap)) {
195 continue;
196 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800197
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200198 int rc = BOOT_HOOK_CALL(boot_read_image_header_hook,
199 BOOT_HOOK_REGULAR, image_index, slot, &hdr);
200 if (rc == BOOT_HOOK_REGULAR)
201 {
202 flash_area_read(fap, 0, &hdr, sizeof(hdr));
203 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800204
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200205 fih_int fih_rc = FIH_FAILURE;
206
207 if (hdr.ih_magic == IMAGE_MAGIC)
208 {
209 BOOT_HOOK_CALL_FIH(boot_image_check_hook,
210 fih_int_encode(BOOT_HOOK_REGULAR),
211 fih_rc, image_index, slot);
212 if (fih_eq(fih_rc, BOOT_HOOK_REGULAR))
213 {
Wouter Cappelle953a7612021-05-03 16:53:05 +0200214#ifdef MCUBOOT_ENC_IMAGES
215 if (slot == 0 && IS_ENCRYPTED(&hdr)) {
216 /* Clear the encrypted flag we didn't supply a key
217 * This flag could be set if there was a decryption in place
218 * performed before. We will try to validate the image without
219 * decryption by clearing the flag in the heder. If
220 * still encrypted the validation will fail.
221 */
222 hdr.ih_flags &= ~(ENCRYPTIONFLAGS);
223 }
224#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200225 FIH_CALL(bootutil_img_validate, fih_rc, NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
226 NULL, 0, NULL);
227 }
228 }
229
230 flash_area_close(fap);
231
232 if (fih_not_eq(fih_rc, FIH_SUCCESS)) {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300233 continue;
234 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300235
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100236 zcbor_map_start_encode(cbor_state, 20);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300237
238#if (BOOT_IMAGE_NUMBER > 1)
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100239 zcbor_tstr_put_lit_cast(cbor_state, "image");
240 zcbor_uint32_put(cbor_state, image_index);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300241#endif
242
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100243 zcbor_tstr_put_lit_cast(cbor_state, "slot");
244 zcbor_uint32_put(cbor_state, slot);
245 zcbor_tstr_put_lit_cast(cbor_state, "version");
Fabio Utzig6f49c272019-08-23 11:42:58 -0300246
247 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100248 zcbor_tstr_encode_ptr(cbor_state, tmpbuf, strlen((char *)tmpbuf));
249 zcbor_map_end_encode(cbor_state, 20);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800250 }
Christopher Collins92ea77f2016-12-12 15:59:26 -0800251 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100252 zcbor_list_end_encode(cbor_state, 5);
253 zcbor_map_end_encode(cbor_state, 1);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800254 boot_serial_output();
255}
256
257/*
258 * Image upload request.
259 */
260static void
261bs_upload(char *buf, int len)
262{
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100263 const uint8_t *img_data = NULL;
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100264 long long int off = UINT64_MAX;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800265 size_t img_blen = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300266 uint8_t rem_bytes;
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100267 long long int data_len = UINT64_MAX;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300268 int img_num;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300269 size_t slen;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800270 const struct flash_area *fap = NULL;
271 int rc;
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000272#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200273 static off_t off_last = -1;
274 struct flash_sector sector;
275#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800276
Fabio Utzig6f49c272019-08-23 11:42:58 -0300277 img_num = 0;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300278
279 /*
280 * Expected data format.
281 * {
Fabio Utzig6f49c272019-08-23 11:42:58 -0300282 * "image":<image number in a multi-image set (OPTIONAL)>
283 * "data":<image data>
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300284 * "len":<image len>
285 * "off":<current offset of image data>
286 * }
287 */
288
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200289 struct Upload upload;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100290 size_t decoded_len;
291 uint_fast8_t result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
Øyvind Rønningstad212a35b2021-05-07 21:06:48 +0200292
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100293 if ((result != ZCBOR_SUCCESS) || (len != decoded_len)) {
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100294 goto out_invalid_data;
295 }
Dominik Ermel470e2f32020-01-10 13:28:48 +0000296
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100297 for (int i = 0; i < upload._Upload_members_count; i++) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100298 struct Member_ *member = &upload._Upload_members[i]._Upload_members;
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100299 switch(member->_Member_choice) {
300 case _Member_image:
301 img_num = member->_Member_image;
302 break;
303 case _Member_data:
304 img_data = member->_Member_data.value;
305 slen = member->_Member_data.len;
306 img_blen = slen;
307 break;
308 case _Member_len:
309 data_len = member->_Member_len;
310 break;
311 case _Member_off:
312 off = member->_Member_off;
313 break;
314 case _Member_sha:
315 default:
316 /* Nothing to do. */
317 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300318 }
319 }
Øyvind Rønningstadf42a8202019-12-13 03:27:54 +0100320
Øyvind Rønningstad9f4aefd2021-03-08 21:11:25 +0100321 if (off == UINT64_MAX || img_data == NULL) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300322 /*
323 * Offset must be set in every block.
324 */
325 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800326 }
327
Dominik Ermel48decca2021-07-09 10:23:58 +0000328#if !defined(MCUBOOT_SERIAL_DIRECT_IMAGE_UPLOAD)
Fabio Utzig6f49c272019-08-23 11:42:58 -0300329 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
Dominik Ermel48decca2021-07-09 10:23:58 +0000330#else
331 rc = flash_area_open(flash_area_id_from_direct_image(img_num), &fap);
332#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800333 if (rc) {
334 rc = MGMT_ERR_EINVAL;
335 goto out;
336 }
337
338 if (off == 0) {
339 curr_off = 0;
Dominik Ermel260ae092021-04-23 05:38:45 +0000340 if (data_len > flash_area_get_size(fap)) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300341 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800342 }
Wouter Cappellebb7a39d2021-05-03 16:44:44 +0200343#if defined(MCUBOOT_VALIDATE_PRIMARY_SLOT_ONCE)
344 /* We are using swap state at end of flash area to store validation
345 * result. Make sure the user cannot write it from an image to skip validation.
346 */
347 if (data_len > (flash_area_get_size(fap) - BOOT_MAGIC_SZ)) {
348 goto out_invalid_data;
349 }
350#endif
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000351#ifndef MCUBOOT_ERASE_PROGRESSIVELY
Dominik Ermel260ae092021-04-23 05:38:45 +0000352 rc = flash_area_erase(fap, 0, flash_area_get_size(fap));
Christopher Collins92ea77f2016-12-12 15:59:26 -0800353 if (rc) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300354 goto out_invalid_data;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800355 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200356#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800357 img_size = data_len;
358 }
359 if (off != curr_off) {
360 rc = 0;
361 goto out;
362 }
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200363
364 if (curr_off + img_blen > img_size) {
365 rc = MGMT_ERR_EINVAL;
366 goto out;
367 }
368
369 rem_bytes = img_blen % flash_area_align(fap);
370
371 if ((curr_off + img_blen < img_size) && rem_bytes) {
372 img_blen -= rem_bytes;
373 rem_bytes = 0;
Fabio Utzig30f6b2a2018-03-29 16:18:53 -0300374 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200375
Dominik Ermel3d4e55d2021-07-09 11:14:10 +0000376#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200377 rc = flash_area_sector_from_off(curr_off + img_blen, &sector);
378 if (rc) {
379 BOOT_LOG_ERR("Unable to determine flash sector size");
380 goto out;
381 }
Dominik Ermel260ae092021-04-23 05:38:45 +0000382 if (off_last != flash_sector_get_off(&sector)) {
383 off_last = flash_sector_get_off(&sector);
384 BOOT_LOG_INF("Erasing sector at offset 0x%x", flash_sector_get_off(&sector));
385 rc = flash_area_erase(fap, flash_sector_get_off(&sector),
386 flash_sector_get_size(&sector));
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200387 if (rc) {
388 BOOT_LOG_ERR("Error %d while erasing sector", rc);
389 goto out;
390 }
391 }
392#endif
393
394 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_blen);
Andrzej Puzdrowskif48de7a2020-10-19 09:42:02 +0200395 if (rem_bytes) {
396 /* the last chunk of the image might be unaligned */
397 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
398 size_t w_size = img_blen - rem_bytes;
399
400 if (w_size) {
401 rc = flash_area_write(fap, curr_off, img_data, w_size);
402 if (rc) {
403 goto out_invalid_data;
404 }
405 curr_off += w_size;
406 img_blen -= w_size;
407 img_data += w_size;
408 }
409
410 if (img_blen) {
411 memcpy(wbs_aligned, img_data, rem_bytes);
412 memset(wbs_aligned + rem_bytes, flash_area_erased_val(fap),
413 sizeof(wbs_aligned) - rem_bytes);
414 rc = flash_area_write(fap, curr_off, wbs_aligned, flash_area_align(fap));
415 }
416
417 } else {
418 rc = flash_area_write(fap, curr_off, img_data, img_blen);
419 }
420
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300421 if (rc == 0) {
422 curr_off += img_blen;
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200423 if (curr_off == img_size) {
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200424#ifdef MCUBOOT_ERASE_PROGRESSIVELY
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200425 /* get the last sector offset */
426 rc = flash_area_sector_from_off(boot_status_off(fap), &sector);
427 if (rc) {
428 BOOT_LOG_ERR("Unable to determine flash sector of"
429 "the image trailer");
430 goto out;
431 }
432 /* Assure that sector for image trailer was erased. */
433 /* Check whether it was erased during previous upload. */
Dominik Ermel260ae092021-04-23 05:38:45 +0000434 if (off_last < flash_sector_get_off(&sector)) {
435 BOOT_LOG_INF("Erasing sector at offset 0x%x",
436 flash_sector_get_off(&sector));
437 rc = flash_area_erase(fap, flash_sector_get_off(&sector),
438 flash_sector_get_size(&sector));
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200439 if (rc) {
440 BOOT_LOG_ERR("Error %d while erasing sector", rc);
441 goto out;
442 }
443 }
Andrzej Puzdrowskic2e30cf2018-07-20 16:19:09 +0200444#endif
Andrzej Puzdrowski4f9c7302021-07-16 17:34:43 +0200445 rc = BOOT_HOOK_CALL(boot_serial_uploaded_hook, 0, img_num, fap,
446 img_size);
447 if (rc) {
448 BOOT_LOG_ERR("Error %d post upload hook", rc);
449 goto out;
450 }
451 }
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300452 } else {
453 out_invalid_data:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800454 rc = MGMT_ERR_EINVAL;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800455 }
Emanuele Di Santo205c8c62018-07-20 11:42:31 +0200456
Christopher Collins92ea77f2016-12-12 15:59:26 -0800457out:
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200458 BOOT_LOG_INF("RX: 0x%x", rc);
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100459 zcbor_map_start_encode(cbor_state, 10);
460 zcbor_tstr_put_lit_cast(cbor_state, "rc");
461 zcbor_uint32_put(cbor_state, rc);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800462 if (rc == 0) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100463 zcbor_tstr_put_lit_cast(cbor_state, "off");
464 zcbor_uint32_put(cbor_state, curr_off);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800465 }
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100466 zcbor_map_end_encode(cbor_state, 10);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800467
468 boot_serial_output();
469 flash_area_close(fap);
Wouter Cappelle953a7612021-05-03 16:53:05 +0200470
471#ifdef MCUBOOT_ENC_IMAGES
472 if (curr_off == img_size) {
473 /* Last sector received, now start a decryption on the image if it is encrypted*/
474 rc = boot_handle_enc_fw();
475 }
476#endif //#ifdef MCUBOOT_ENC_IMAGES
Christopher Collins92ea77f2016-12-12 15:59:26 -0800477}
478
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000479/*
480 * Send rc code only.
481 */
482static void
483bs_rc_rsp(int rc_code)
484{
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100485 zcbor_map_start_encode(cbor_state, 10);
486 zcbor_tstr_put_lit_cast(cbor_state, "rc");
487 zcbor_uint32_put(cbor_state, rc_code);
488 zcbor_map_end_encode(cbor_state, 10);
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000489 boot_serial_output();
490}
491
492
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200493#ifdef MCUBOOT_BOOT_MGMT_ECHO
494static bool
495decode_echo(cbor_state_t *state, cbor_string_type_t *result)
496{
497 size_t bsstrdecoded;
498 int ret;
499
500 if (!map_start_decode(state)) {
501 return false;
502 }
503 ret = multi_decode(2, 2, &bsstrdecoded, (void *)tstrx_decode, state, result, sizeof(cbor_string_type_t));
504 map_end_decode(state);
505 return ret;
506}
507
508
509static void
510bs_echo(char *buf, int len)
511{
512 size_t bsstrdecoded;
513 cbor_string_type_t str[2];
514
515 if (entry_function((const uint8_t *)buf, len, str, &bsstrdecoded, (void *)decode_echo, 1, 2)) {
516 map_start_encode(&cbor_state, 10);
517 tstrx_put(&cbor_state, "r");
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000518 if (tstrx_encode(&cbor_state, &str[1]) && map_end_encode(&cbor_state, 10)) {
519 boot_serial_output();
520 } else {
521 reset_cbor_state();
522 bs_rc_rsp(MGMT_ERR_ENOMEM);
523 }
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200524 }
525}
526#endif
527
Christopher Collins92ea77f2016-12-12 15:59:26 -0800528/*
Christopher Collins92ea77f2016-12-12 15:59:26 -0800529 * Reset, and (presumably) boot to newly uploaded image. Flush console
530 * before restarting.
531 */
Andrzej Puzdrowski268cdd02018-04-10 12:57:54 +0200532static void
Christopher Collins92ea77f2016-12-12 15:59:26 -0800533bs_reset(char *buf, int len)
534{
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000535 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800536
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200537#ifdef __ZEPHYR__
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200538#ifdef CONFIG_MULTITHREADING
Carles Cufi7e7b4ad2020-03-30 19:12:02 +0200539 k_sleep(K_MSEC(250));
Andrzej Puzdrowski0cf0dbd2021-05-14 11:55:57 +0200540#else
541 k_busy_wait(250000);
542#endif
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200543 sys_reboot(SYS_REBOOT_COLD);
544#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800545 os_cputime_delay_usecs(250000);
546 hal_system_reset();
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200547#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800548}
549
550/*
551 * Parse incoming line of input from console.
552 * Expect newtmgr protocol with serial transport.
553 */
554void
555boot_serial_input(char *buf, int len)
556{
557 struct nmgr_hdr *hdr;
558
559 hdr = (struct nmgr_hdr *)buf;
560 if (len < sizeof(*hdr) ||
561 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
562 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
563 return;
564 }
565 bs_hdr = hdr;
566 hdr->nh_group = ntohs(hdr->nh_group);
567
568 buf += sizeof(*hdr);
569 len -= sizeof(*hdr);
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300570
Dominik Ermel4c0f6c12022-03-04 15:47:37 +0000571 reset_cbor_state();
Christopher Collins92ea77f2016-12-12 15:59:26 -0800572
573 /*
574 * Limited support for commands.
575 */
576 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
577 switch (hdr->nh_id) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300578 case IMGMGR_NMGR_ID_STATE:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800579 bs_list(buf, len);
580 break;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300581 case IMGMGR_NMGR_ID_UPLOAD:
Christopher Collins92ea77f2016-12-12 15:59:26 -0800582 bs_upload(buf, len);
583 break;
584 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000585 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800586 break;
587 }
588 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
589 switch (hdr->nh_id) {
Wouter Cappellee3ff1752021-05-03 16:36:22 +0200590 case NMGR_ID_ECHO:
591#ifdef MCUBOOT_BOOT_MGMT_ECHO
592 bs_echo(buf, len);
593#endif
594 break;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800595 case NMGR_ID_CONS_ECHO_CTRL:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000596 bs_rc_rsp(0);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800597 break;
598 case NMGR_ID_RESET:
599 bs_reset(buf, len);
600 break;
601 default:
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000602 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800603 break;
604 }
Dominik Ermelbd69c3d2021-07-28 11:27:31 +0000605 } else if (MCUBOOT_PERUSER_MGMT_GROUP_ENABLED == 1) {
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100606 if (bs_peruser_system_specific(hdr, buf, len, cbor_state) == 0) {
Dominik Ermel3d51e432021-06-25 17:29:50 +0000607 boot_serial_output();
608 }
Dominik Ermelc9dc2242021-07-28 17:08:23 +0000609 } else {
610 bs_rc_rsp(MGMT_ERR_ENOTSUP);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800611 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100612#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
613 bs_entry = true;
614#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800615}
616
617static void
618boot_serial_output(void)
619{
620 char *data;
621 int len;
622 uint16_t crc;
623 uint16_t totlen;
624 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
Dominik Ermel5ff89582022-03-03 17:09:07 +0000625 char buf[BOOT_SERIAL_OUT_MAX + sizeof(*bs_hdr) + sizeof(crc) + sizeof(totlen)];
626 char encoded_buf[BASE64_ENCODE_SIZE(sizeof(buf))];
Christopher Collins92ea77f2016-12-12 15:59:26 -0800627
628 data = bs_obuf;
Øyvind Rønningstada7d34ca2022-02-28 13:47:57 +0100629 len = (uint32_t)cbor_state->payload_mut - (uint32_t)bs_obuf;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800630
631 bs_hdr->nh_op++;
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300632 bs_hdr->nh_flags = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800633 bs_hdr->nh_len = htons(len);
634 bs_hdr->nh_group = htons(bs_hdr->nh_group);
635
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200636#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100637 crc = crc16_itu_t(CRC16_INITIAL_CRC, (uint8_t *)bs_hdr, sizeof(*bs_hdr));
638 crc = crc16_itu_t(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200639#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800640 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
641 crc = crc16_ccitt(crc, data, len);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200642#endif
Christopher Collins92ea77f2016-12-12 15:59:26 -0800643 crc = htons(crc);
644
Marko Kiiskila149b4572018-06-06 14:18:54 +0300645 boot_uf->write(pkt_start, sizeof(pkt_start));
Christopher Collins92ea77f2016-12-12 15:59:26 -0800646
647 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
648 totlen = htons(totlen);
649
650 memcpy(buf, &totlen, sizeof(totlen));
651 totlen = sizeof(totlen);
652 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
653 totlen += sizeof(*bs_hdr);
654 memcpy(&buf[totlen], data, len);
655 totlen += len;
656 memcpy(&buf[totlen], &crc, sizeof(crc));
657 totlen += sizeof(crc);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200658#ifdef __ZEPHYR__
659 size_t enc_len;
Carles Cufi0165be82018-03-26 17:43:51 +0200660 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200661 totlen = enc_len;
662#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800663 totlen = base64_encode(buf, totlen, encoded_buf, 1);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200664#endif
Marko Kiiskila149b4572018-06-06 14:18:54 +0300665 boot_uf->write(encoded_buf, totlen);
666 boot_uf->write("\n\r", 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200667 BOOT_LOG_INF("TX");
Christopher Collins92ea77f2016-12-12 15:59:26 -0800668}
669
670/*
671 * Returns 1 if full packet has been received.
672 */
673static int
674boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
675{
676 int rc;
677 uint16_t crc;
678 uint16_t len;
Marko Kiiskilae5aeee42018-12-21 15:00:16 +0200679
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200680#ifdef __ZEPHYR__
681 int err;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200682 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200683 if (err) {
684 return -1;
685 }
686#else
Christopher Collins92ea77f2016-12-12 15:59:26 -0800687 if (*out_off + base64_decode_len(in) >= maxout) {
688 return -1;
689 }
690 rc = base64_decode(in, &out[*out_off]);
691 if (rc < 0) {
692 return -1;
693 }
Andrzej Puzdrowski8e96b832017-09-08 16:49:14 +0200694#endif
Fabio Utzig6f49c272019-08-23 11:42:58 -0300695
Christopher Collins92ea77f2016-12-12 15:59:26 -0800696 *out_off += rc;
Fabio Utzig6f49c272019-08-23 11:42:58 -0300697 if (*out_off <= sizeof(uint16_t)) {
698 return 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800699 }
Fabio Utzig6f49c272019-08-23 11:42:58 -0300700
701 len = ntohs(*(uint16_t *)out);
702 if (len != *out_off - sizeof(uint16_t)) {
703 return 0;
704 }
705
706 if (len > *out_off - sizeof(uint16_t)) {
707 len = *out_off - sizeof(uint16_t);
708 }
709
710 out += sizeof(uint16_t);
711#ifdef __ZEPHYR__
Carles Cufib9192a42022-02-10 11:41:57 +0100712 crc = crc16_itu_t(CRC16_INITIAL_CRC, out, len);
Fabio Utzig6f49c272019-08-23 11:42:58 -0300713#else
714 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
715#endif
716 if (crc || len <= sizeof(crc)) {
717 return 0;
718 }
719 *out_off -= sizeof(crc);
720 out[*out_off] = '\0';
721
722 return 1;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800723}
724
725/*
726 * Task which waits reading console, expecting to get image over
727 * serial port.
728 */
Wouter Cappellee3822f82022-01-19 15:39:43 +0100729static void
730boot_serial_read_console(const struct boot_uart_funcs *f,int timeout_in_ms)
Christopher Collins92ea77f2016-12-12 15:59:26 -0800731{
732 int rc;
733 int off;
David Brown57f0df32020-05-12 08:39:21 -0600734 int dec_off = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800735 int full_line;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300736 int max_input;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100737 int elapsed_in_ms = 0;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800738
Marko Kiiskila149b4572018-06-06 14:18:54 +0300739 boot_uf = f;
Marko Kiiskila149b4572018-06-06 14:18:54 +0300740 max_input = sizeof(in_buf);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800741
742 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100743 while (timeout_in_ms > 0 || bs_entry) {
Andrzej Puzdrowskiaea38eb2021-06-11 12:28:59 +0200744 MCUBOOT_CPU_IDLE();
Hein Wessels56d28f02021-11-19 08:42:08 +0100745 MCUBOOT_WATCHDOG_FEED();
Wouter Cappellee3822f82022-01-19 15:39:43 +0100746#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
747 uint32_t start = k_uptime_get_32();
748#endif
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200749 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800750 if (rc <= 0 && !full_line) {
Wouter Cappellee3822f82022-01-19 15:39:43 +0100751 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800752 }
753 off += rc;
754 if (!full_line) {
Marko Kiiskilace50ab02018-06-06 11:33:33 +0300755 if (off == max_input) {
756 /*
757 * Full line, no newline yet. Reset the input buffer.
758 */
759 off = 0;
760 }
Wouter Cappellee3822f82022-01-19 15:39:43 +0100761 goto check_timeout;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800762 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200763 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
764 in_buf[1] == SHELL_NLIP_PKT_START2) {
Christopher Collins92ea77f2016-12-12 15:59:26 -0800765 dec_off = 0;
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200766 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
767 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
768 in_buf[1] == SHELL_NLIP_DATA_START2) {
769 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800770 }
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200771
772 /* serve errors: out of decode memory, or bad encoding */
Christopher Collins92ea77f2016-12-12 15:59:26 -0800773 if (rc == 1) {
Andrzej Puzdrowskiec1e4d12018-06-18 14:36:14 +0200774 boot_serial_input(&dec_buf[2], dec_off - 2);
Christopher Collins92ea77f2016-12-12 15:59:26 -0800775 }
776 off = 0;
Wouter Cappellee3822f82022-01-19 15:39:43 +0100777check_timeout:
778 /* Subtract elapsed time */
779#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
780 elapsed_in_ms = (k_uptime_get_32() - start);
781#endif
782 timeout_in_ms -= elapsed_in_ms;
Christopher Collins92ea77f2016-12-12 15:59:26 -0800783 }
784}
Wouter Cappellee3822f82022-01-19 15:39:43 +0100785
786/*
787 * Task which waits reading console, expecting to get image over
788 * serial port.
789 */
790void
791boot_serial_start(const struct boot_uart_funcs *f)
792{
793 bs_entry = true;
794 boot_serial_read_console(f,0);
795}
796
797#ifdef MCUBOOT_SERIAL_WAIT_FOR_DFU
798/*
799 * Task which waits reading console for a certain amount of timeout.
800 * If within this timeout no mcumgr command is received, the function is
801 * returning, else the serial boot is never exited
802 */
803void
804boot_serial_check_start(const struct boot_uart_funcs *f, int timeout_in_ms)
805{
806 bs_entry = false;
807 boot_serial_read_console(f,timeout_in_ms);
808}
809#endif