boot: add precise check of the image size
It is possible that image in the slot is so big
that MCUboot swap metadata will interfere with
its content during the swap operation.
This patch introduces additional check to the image
validation procedure.
Signed-off-by: Andrzej Puzdrowski <andrzej.puzdrowski@nordicsemi.no>
diff --git a/boot/bootutil/src/bootutil_misc.c b/boot/bootutil/src/bootutil_misc.c
index e2c70bc..94521c4 100644
--- a/boot/bootutil/src/bootutil_misc.c
+++ b/boot/bootutil/src/bootutil_misc.c
@@ -387,3 +387,27 @@
return 0;
}
#endif
+
+uint32_t bootutil_max_image_size(const struct flash_area *fap)
+{
+#if defined(MCUBOOT_SWAP_USING_SCRATCH)
+ return boot_status_off(fap);
+#elif defined(MCUBOOT_SWAP_USING_MOVE)
+ struct flash_sector sector;
+ /* get the last sector offset */
+ int rc = flash_area_sector_from_off(boot_status_off(fap), §or);
+ if (rc) {
+ BOOT_LOG_ERR("Unable to determine flash sector of the image trailer");
+ return 0; /* Returning of zero here should cause any check which uses
+ * this value to fail.
+ */
+ }
+ return flash_sector_get_off(§or);
+#elif defined(MCUBOOT_OVERWRITE_ONLY)
+ return boot_swap_info_off(fap);
+#elif defined(MCUBOOT_DIRECT_XIP)
+ return boot_swap_info_off(fap);
+#elif defined(MCUBOOT_RAM_LOAD)
+ return boot_swap_info_off(fap);
+#endif
+}
diff --git a/boot/bootutil/src/bootutil_priv.h b/boot/bootutil/src/bootutil_priv.h
index 4085b54..43a2bac 100644
--- a/boot/bootutil/src/bootutil_priv.h
+++ b/boot/bootutil/src/bootutil_priv.h
@@ -463,6 +463,8 @@
(flash_area_read((fap), (start), (output), (size)))
#endif /* MCUBOOT_RAM_LOAD */
+uint32_t bootutil_max_image_size(const struct flash_area *fap);
+
#ifdef __cplusplus
}
#endif
diff --git a/boot/bootutil/src/image_validate.c b/boot/bootutil/src/image_validate.c
index 6891394..e8a3cc2 100644
--- a/boot/bootutil/src/image_validate.c
+++ b/boot/bootutil/src/image_validate.c
@@ -376,6 +376,11 @@
goto out;
}
+ if (it.tlv_end > bootutil_max_image_size(fap)) {
+ rc = -1;
+ goto out;
+ }
+
/*
* Traverse through all of the TLVs, performing any checks we know
* and are able to do.