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
25 #include "sysflash/sysflash.h"
26
27 #include "bootutil/bootutil_log.h"
28 #include "cbor_encode.h"
29
30 #ifdef __ZEPHYR__
31 #include <power/reboot.h>
32 #include <sys/byteorder.h>
33 #include <sys/__assert.h>
34 #include <drivers/flash.h>
35 #include <sys/crc.h>
36 #include <sys/base64.h>
37 #else
38 #include <bsp/bsp.h>
39 #include <hal/hal_system.h>
40 #include <os/endian.h>
41 #include <os/os_cputime.h>
42 #include <crc/crc16.h>
43 #include <base64/base64.h>
44 #endif /* __ZEPHYR__ */
45
46 #include <flash_map_backend/flash_map_backend.h>
47 #include <hal/hal_flash.h>
48 #include <os/os.h>
49 #include <os/os_malloc.h>
50
51 #include <bootutil/image.h>
52 #include <bootutil/bootutil.h>
53
54 #include "boot_serial/boot_serial.h"
55 #include "boot_serial_priv.h"
56
57 #ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
58 #include "bootutil_priv.h"
59 #endif
60
61 #include "serial_recovery_cbor.h"
62
63 MCUBOOT_LOG_MODULE_DECLARE(mcuboot);
64
65 #define BOOT_SERIAL_INPUT_MAX 512
66 #define BOOT_SERIAL_OUT_MAX 128
67
68 #ifdef __ZEPHYR__
69 /* base64 lib encodes data to null-terminated string */
70 #define BASE64_ENCODE_SIZE(in_size) ((((((in_size) - 1) / 3) * 4) + 4) + 1)
71
72 #define CRC16_INITIAL_CRC 0 /* what to seed crc16 with */
73 #define CRC_CITT_POLYMINAL 0x1021
74
75 #define ntohs(x) sys_be16_to_cpu(x)
76 #define htons(x) sys_cpu_to_be16(x)
77 #endif
78
79 #ifndef BOOT_IMAGE_NUMBER
80 #define BOOT_IMAGE_NUMBER MCUBOOT_IMAGE_NUMBER
81 #endif
82
83 #if (BOOT_IMAGE_NUMBER > 1)
84 #define IMAGES_ITER(x) for ((x) = 0; (x) < BOOT_IMAGE_NUMBER; ++(x))
85 #else
86 #define IMAGES_ITER(x)
87 #endif
88
89 static char in_buf[BOOT_SERIAL_INPUT_MAX + 1];
90 static char dec_buf[BOOT_SERIAL_INPUT_MAX + 1];
91 const struct boot_uart_funcs *boot_uf;
92 static uint32_t curr_off;
93 static uint32_t img_size;
94 static struct nmgr_hdr *bs_hdr;
95
96 static char bs_obuf[BOOT_SERIAL_OUT_MAX];
97
98 static void boot_serial_output(void);
99
100 static cbor_state_backups_t dummy_backups;
101 static cbor_state_t cbor_state = {
102 .backups = &dummy_backups
103 };
104
105
106 /*
107 * Convert version into string without use of snprintf().
108 */
109 static int
u32toa(char * tgt,uint32_t val)110 u32toa(char *tgt, uint32_t val)
111 {
112 char *dst;
113 uint32_t d = 1;
114 uint32_t dgt;
115 int n = 0;
116
117 dst = tgt;
118 while (val / d >= 10) {
119 d *= 10;
120 }
121 while (d) {
122 dgt = val / d;
123 val %= d;
124 d /= 10;
125 if (n || dgt > 0 || d == 0) {
126 *dst++ = dgt + '0';
127 ++n;
128 }
129 }
130 *dst = '\0';
131
132 return dst - tgt;
133 }
134
135 /*
136 * dst has to be able to fit "255.255.65535.4294967295" (25 characters).
137 */
138 static void
bs_list_img_ver(char * dst,int maxlen,struct image_version * ver)139 bs_list_img_ver(char *dst, int maxlen, struct image_version *ver)
140 {
141 int off;
142
143 off = u32toa(dst, ver->iv_major);
144 dst[off++] = '.';
145 off += u32toa(dst + off, ver->iv_minor);
146 dst[off++] = '.';
147 off += u32toa(dst + off, ver->iv_revision);
148 dst[off++] = '.';
149 off += u32toa(dst + off, ver->iv_build_num);
150 }
151
152 /*
153 * List images.
154 */
155 static void
bs_list(char * buf,int len)156 bs_list(char *buf, int len)
157 {
158 struct image_header hdr;
159 uint8_t tmpbuf[64];
160 uint32_t slot, area_id;
161 const struct flash_area *fap;
162 uint8_t image_index;
163
164 map_start_encode(&cbor_state, 1);
165 tstrx_put(&cbor_state, "images");
166 list_start_encode(&cbor_state, 5);
167 image_index = 0;
168 IMAGES_ITER(image_index) {
169 for (slot = 0; slot < 2; slot++) {
170 area_id = flash_area_id_from_multi_image_slot(image_index, slot);
171 if (flash_area_open(area_id, &fap)) {
172 continue;
173 }
174
175 flash_area_read(fap, 0, &hdr, sizeof(hdr));
176
177 if (hdr.ih_magic != IMAGE_MAGIC ||
178 bootutil_img_validate(NULL, 0, &hdr, fap, tmpbuf, sizeof(tmpbuf),
179 NULL, 0, NULL)) {
180 flash_area_close(fap);
181 continue;
182 }
183 flash_area_close(fap);
184
185 map_start_encode(&cbor_state, 20);
186
187 #if (BOOT_IMAGE_NUMBER > 1)
188 tstrx_put(&cbor_state, "image");
189 uintx32_put(&cbor_state, image_index);
190 #endif
191
192 tstrx_put(&cbor_state, "slot");
193 uintx32_put(&cbor_state, slot);
194 tstrx_put(&cbor_state, "version");
195
196 bs_list_img_ver((char *)tmpbuf, sizeof(tmpbuf), &hdr.ih_ver);
197 tstrx_put_term(&cbor_state, (char *)tmpbuf);
198 map_end_encode(&cbor_state, 20);
199 }
200 }
201 list_end_encode(&cbor_state, 5);
202 map_end_encode(&cbor_state, 1);
203 boot_serial_output();
204 }
205
206 /*
207 * Image upload request.
208 */
209 static void
bs_upload(char * buf,int len)210 bs_upload(char *buf, int len)
211 {
212 const uint8_t *img_data = NULL;
213 long long int off = UINT64_MAX;
214 size_t img_blen = 0;
215 uint8_t rem_bytes;
216 long long int data_len = UINT64_MAX;
217 int img_num;
218 size_t slen;
219 const struct flash_area *fap = NULL;
220 int rc;
221 #ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
222 static off_t off_last = -1;
223 struct flash_sector sector;
224 #endif
225
226 img_num = 0;
227
228 /*
229 * Expected data format.
230 * {
231 * "image":<image number in a multi-image set (OPTIONAL)>
232 * "data":<image data>
233 * "len":<image len>
234 * "off":<current offset of image data>
235 * }
236 */
237
238 struct Upload upload;
239 uint32_t decoded_len;
240 bool result = cbor_decode_Upload((const uint8_t *)buf, len, &upload, &decoded_len);
241
242 if (!result || (len != decoded_len)) {
243 goto out_invalid_data;
244 }
245
246 for (int i = 0; i < upload._Upload_members_count; i++) {
247 struct Member_ *member = &upload._Upload_members[i];
248 switch(member->_Member_choice) {
249 case _Member_image:
250 img_num = member->_Member_image;
251 break;
252 case _Member_data:
253 img_data = member->_Member_data.value;
254 slen = member->_Member_data.len;
255 img_blen = slen;
256 break;
257 case _Member_len:
258 data_len = member->_Member_len;
259 break;
260 case _Member_off:
261 off = member->_Member_off;
262 break;
263 case _Member_sha:
264 default:
265 /* Nothing to do. */
266 break;
267 }
268 }
269
270 if (off == UINT64_MAX || img_data == NULL) {
271 /*
272 * Offset must be set in every block.
273 */
274 goto out_invalid_data;
275 }
276
277 rc = flash_area_open(flash_area_id_from_multi_image_slot(img_num, 0), &fap);
278 if (rc) {
279 rc = MGMT_ERR_EINVAL;
280 goto out;
281 }
282
283 if (off == 0) {
284 curr_off = 0;
285 if (data_len > fap->fa_size) {
286 goto out_invalid_data;
287 }
288 #ifndef CONFIG_BOOT_ERASE_PROGRESSIVELY
289 rc = flash_area_erase(fap, 0, fap->fa_size);
290 if (rc) {
291 goto out_invalid_data;
292 }
293 #endif
294 img_size = data_len;
295 }
296 if (off != curr_off) {
297 rc = 0;
298 goto out;
299 }
300
301 if (curr_off + img_blen > img_size) {
302 rc = MGMT_ERR_EINVAL;
303 goto out;
304 }
305
306 rem_bytes = img_blen % flash_area_align(fap);
307
308 if ((curr_off + img_blen < img_size) && rem_bytes) {
309 img_blen -= rem_bytes;
310 rem_bytes = 0;
311 }
312
313 #ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
314 rc = flash_area_sector_from_off(curr_off + img_blen, §or);
315 if (rc) {
316 BOOT_LOG_ERR("Unable to determine flash sector size");
317 goto out;
318 }
319 if (off_last != sector.fs_off) {
320 off_last = sector.fs_off;
321 BOOT_LOG_INF("Erasing sector at offset 0x%x", sector.fs_off);
322 rc = flash_area_erase(fap, sector.fs_off, sector.fs_size);
323 if (rc) {
324 BOOT_LOG_ERR("Error %d while erasing sector", rc);
325 goto out;
326 }
327 }
328 #endif
329
330 BOOT_LOG_INF("Writing at 0x%x until 0x%x", curr_off, curr_off + img_blen);
331 if (rem_bytes) {
332 /* the last chunk of the image might be unaligned */
333 uint8_t wbs_aligned[BOOT_MAX_ALIGN];
334 size_t w_size = img_blen - rem_bytes;
335
336 if (w_size) {
337 rc = flash_area_write(fap, curr_off, img_data, w_size);
338 if (rc) {
339 goto out_invalid_data;
340 }
341 curr_off += w_size;
342 img_blen -= w_size;
343 img_data += w_size;
344 }
345
346 if (img_blen) {
347 memcpy(wbs_aligned, img_data, rem_bytes);
348 memset(wbs_aligned + rem_bytes, flash_area_erased_val(fap),
349 sizeof(wbs_aligned) - rem_bytes);
350 rc = flash_area_write(fap, curr_off, wbs_aligned, flash_area_align(fap));
351 }
352
353 } else {
354 rc = flash_area_write(fap, curr_off, img_data, img_blen);
355 }
356
357 if (rc == 0) {
358 curr_off += img_blen;
359 #ifdef CONFIG_BOOT_ERASE_PROGRESSIVELY
360 if (curr_off == img_size) {
361 /* get the last sector offset */
362 rc = flash_area_sector_from_off(boot_status_off(fap), §or);
363 if (rc) {
364 BOOT_LOG_ERR("Unable to determine flash sector of"
365 "the image trailer");
366 goto out;
367 }
368 /* Assure that sector for image trailer was erased. */
369 /* Check whether it was erased during previous upload. */
370 if (off_last < sector.fs_off) {
371 BOOT_LOG_INF("Erasing sector at offset 0x%x", sector.fs_off);
372 rc = flash_area_erase(fap, sector.fs_off, sector.fs_size);
373 if (rc) {
374 BOOT_LOG_ERR("Error %d while erasing sector", rc);
375 goto out;
376 }
377 }
378 }
379 #endif
380 } else {
381 out_invalid_data:
382 rc = MGMT_ERR_EINVAL;
383 }
384
385 out:
386 BOOT_LOG_INF("RX: 0x%x", rc);
387 map_start_encode(&cbor_state, 10);
388 tstrx_put(&cbor_state, "rc");
389 uintx32_put(&cbor_state, rc);
390 if (rc == 0) {
391 tstrx_put(&cbor_state, "off");
392 uintx32_put(&cbor_state, curr_off);
393 }
394 map_end_encode(&cbor_state, 10);
395
396 boot_serial_output();
397 flash_area_close(fap);
398 }
399
400 /*
401 * Console echo control/image erase. Send empty response, don't do anything.
402 */
403 static void
bs_empty_rsp(char * buf,int len)404 bs_empty_rsp(char *buf, int len)
405 {
406 map_start_encode(&cbor_state, 10);
407 tstrx_put(&cbor_state, "rc");
408 uintx32_put(&cbor_state, 0);
409 map_end_encode(&cbor_state, 10);
410 boot_serial_output();
411 }
412
413 /*
414 * Reset, and (presumably) boot to newly uploaded image. Flush console
415 * before restarting.
416 */
417 static void
bs_reset(char * buf,int len)418 bs_reset(char *buf, int len)
419 {
420 bs_empty_rsp(buf, len);
421
422 #ifdef __ZEPHYR__
423 #ifdef CONFIG_MULTITHREADING
424 k_sleep(K_MSEC(250));
425 #else
426 k_busy_wait(250000);
427 #endif
428 sys_reboot(SYS_REBOOT_COLD);
429 #else
430 os_cputime_delay_usecs(250000);
431 hal_system_reset();
432 #endif
433 }
434
435 /*
436 * Parse incoming line of input from console.
437 * Expect newtmgr protocol with serial transport.
438 */
439 void
boot_serial_input(char * buf,int len)440 boot_serial_input(char *buf, int len)
441 {
442 struct nmgr_hdr *hdr;
443
444 hdr = (struct nmgr_hdr *)buf;
445 if (len < sizeof(*hdr) ||
446 (hdr->nh_op != NMGR_OP_READ && hdr->nh_op != NMGR_OP_WRITE) ||
447 (ntohs(hdr->nh_len) < len - sizeof(*hdr))) {
448 return;
449 }
450 bs_hdr = hdr;
451 hdr->nh_group = ntohs(hdr->nh_group);
452
453 buf += sizeof(*hdr);
454 len -= sizeof(*hdr);
455
456 cbor_state.payload_mut = (uint8_t *)bs_obuf;
457 cbor_state.payload_end = (const uint8_t *)bs_obuf
458 + sizeof(bs_obuf);
459
460 /*
461 * Limited support for commands.
462 */
463 if (hdr->nh_group == MGMT_GROUP_ID_IMAGE) {
464 switch (hdr->nh_id) {
465 case IMGMGR_NMGR_ID_STATE:
466 bs_list(buf, len);
467 break;
468 case IMGMGR_NMGR_ID_UPLOAD:
469 bs_upload(buf, len);
470 break;
471 default:
472 bs_empty_rsp(buf, len);
473 break;
474 }
475 } else if (hdr->nh_group == MGMT_GROUP_ID_DEFAULT) {
476 switch (hdr->nh_id) {
477 case NMGR_ID_CONS_ECHO_CTRL:
478 bs_empty_rsp(buf, len);
479 break;
480 case NMGR_ID_RESET:
481 bs_reset(buf, len);
482 break;
483 default:
484 break;
485 }
486 }
487 }
488
489 static void
boot_serial_output(void)490 boot_serial_output(void)
491 {
492 char *data;
493 int len;
494 uint16_t crc;
495 uint16_t totlen;
496 char pkt_start[2] = { SHELL_NLIP_PKT_START1, SHELL_NLIP_PKT_START2 };
497 char buf[BOOT_SERIAL_OUT_MAX];
498 char encoded_buf[BASE64_ENCODE_SIZE(BOOT_SERIAL_OUT_MAX)];
499
500 data = bs_obuf;
501 len = (uint32_t)cbor_state.payload_mut - (uint32_t)bs_obuf;
502
503 bs_hdr->nh_op++;
504 bs_hdr->nh_flags = 0;
505 bs_hdr->nh_len = htons(len);
506 bs_hdr->nh_group = htons(bs_hdr->nh_group);
507
508 #ifdef __ZEPHYR__
509 crc = crc16((uint8_t *)bs_hdr, sizeof(*bs_hdr), CRC_CITT_POLYMINAL,
510 CRC16_INITIAL_CRC, false);
511 crc = crc16(data, len, CRC_CITT_POLYMINAL, crc, true);
512 #else
513 crc = crc16_ccitt(CRC16_INITIAL_CRC, bs_hdr, sizeof(*bs_hdr));
514 crc = crc16_ccitt(crc, data, len);
515 #endif
516 crc = htons(crc);
517
518 boot_uf->write(pkt_start, sizeof(pkt_start));
519
520 totlen = len + sizeof(*bs_hdr) + sizeof(crc);
521 totlen = htons(totlen);
522
523 memcpy(buf, &totlen, sizeof(totlen));
524 totlen = sizeof(totlen);
525 memcpy(&buf[totlen], bs_hdr, sizeof(*bs_hdr));
526 totlen += sizeof(*bs_hdr);
527 memcpy(&buf[totlen], data, len);
528 totlen += len;
529 memcpy(&buf[totlen], &crc, sizeof(crc));
530 totlen += sizeof(crc);
531 #ifdef __ZEPHYR__
532 size_t enc_len;
533 base64_encode(encoded_buf, sizeof(encoded_buf), &enc_len, buf, totlen);
534 totlen = enc_len;
535 #else
536 totlen = base64_encode(buf, totlen, encoded_buf, 1);
537 #endif
538 boot_uf->write(encoded_buf, totlen);
539 boot_uf->write("\n\r", 2);
540 BOOT_LOG_INF("TX");
541 }
542
543 /*
544 * Returns 1 if full packet has been received.
545 */
546 static int
boot_serial_in_dec(char * in,int inlen,char * out,int * out_off,int maxout)547 boot_serial_in_dec(char *in, int inlen, char *out, int *out_off, int maxout)
548 {
549 int rc;
550 uint16_t crc;
551 uint16_t len;
552
553 #ifdef __ZEPHYR__
554 int err;
555 err = base64_decode( &out[*out_off], maxout - *out_off, &rc, in, inlen - 2);
556 if (err) {
557 return -1;
558 }
559 #else
560 if (*out_off + base64_decode_len(in) >= maxout) {
561 return -1;
562 }
563 rc = base64_decode(in, &out[*out_off]);
564 if (rc < 0) {
565 return -1;
566 }
567 #endif
568
569 *out_off += rc;
570 if (*out_off <= sizeof(uint16_t)) {
571 return 0;
572 }
573
574 len = ntohs(*(uint16_t *)out);
575 if (len != *out_off - sizeof(uint16_t)) {
576 return 0;
577 }
578
579 if (len > *out_off - sizeof(uint16_t)) {
580 len = *out_off - sizeof(uint16_t);
581 }
582
583 out += sizeof(uint16_t);
584 #ifdef __ZEPHYR__
585 crc = crc16(out, len, CRC_CITT_POLYMINAL, CRC16_INITIAL_CRC, true);
586 #else
587 crc = crc16_ccitt(CRC16_INITIAL_CRC, out, len);
588 #endif
589 if (crc || len <= sizeof(crc)) {
590 return 0;
591 }
592 *out_off -= sizeof(crc);
593 out[*out_off] = '\0';
594
595 return 1;
596 }
597
598 /*
599 * Task which waits reading console, expecting to get image over
600 * serial port.
601 */
602 void
boot_serial_start(const struct boot_uart_funcs * f)603 boot_serial_start(const struct boot_uart_funcs *f)
604 {
605 int rc;
606 int off;
607 int dec_off = 0;
608 int full_line;
609 int max_input;
610
611 boot_uf = f;
612 max_input = sizeof(in_buf);
613
614 off = 0;
615 while (1) {
616 MCUBOOT_CPU_IDLE();
617 rc = f->read(in_buf + off, sizeof(in_buf) - off, &full_line);
618 if (rc <= 0 && !full_line) {
619 continue;
620 }
621 off += rc;
622 if (!full_line) {
623 if (off == max_input) {
624 /*
625 * Full line, no newline yet. Reset the input buffer.
626 */
627 off = 0;
628 }
629 continue;
630 }
631 if (in_buf[0] == SHELL_NLIP_PKT_START1 &&
632 in_buf[1] == SHELL_NLIP_PKT_START2) {
633 dec_off = 0;
634 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
635 } else if (in_buf[0] == SHELL_NLIP_DATA_START1 &&
636 in_buf[1] == SHELL_NLIP_DATA_START2) {
637 rc = boot_serial_in_dec(&in_buf[2], off - 2, dec_buf, &dec_off, max_input);
638 }
639
640 /* serve errors: out of decode memory, or bad encoding */
641 if (rc == 1) {
642 boot_serial_input(&dec_buf[2], dec_off - 2);
643 }
644 off = 0;
645 }
646 }
647