Boot: Check integer overflow

Validate the input parameters from users, which comes
in the image header and image metadata (TLV) section,
to avoid integer overflow.

Change-Id: I1d1a48e8dbda2ced2620aa9fb19fda3bfbd801ab
Signed-off-by: Tamas Ban <tamas.ban@arm.com>
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/bootutil/src/image_validate.c
index e62455c..77b079c 100644
--- a/bl2/ext/mcuboot/bootutil/src/image_validate.c
+++ b/bl2/ext/mcuboot/bootutil/src/image_validate.c
@@ -210,6 +210,9 @@
     if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
         return BOOT_EBADMAGIC;
     }
+    if (boot_add_uint32_overflow_check(off, (info.it_tlv_tot + sizeof(info)))) {
+        return -1;
+    }
     end = off + info.it_tlv_tot;
     off += sizeof(info);
 
@@ -217,6 +220,9 @@
      * Traverse through all of the TLVs, performing any checks we know
      * and are able to do.
      */
+    if (boot_add_uint32_overflow_check(load_address, end)) {
+        return -1;
+    }
     while (off < end) {
         tlv = *((struct image_tlv *)(load_address + off));
         tlv_sz = sizeof(tlv);
@@ -239,7 +245,7 @@
         }
 
         /* Avoid integer overflow. */
-        if ((UINT32_MAX - off) < (sizeof(tlv) + tlv.it_len)) {
+        if (boot_add_uint32_overflow_check(off, (sizeof(tlv) + tlv.it_len))) {
             /* Potential overflow. */
             break;
         } else {
@@ -330,7 +336,8 @@
             }
 
             /* Avoid integer overflow. */
-            if ((UINT32_MAX - off) < (sizeof(tlv) + tlv.it_len)) {
+            if (boot_add_uint32_overflow_check(off, (sizeof(tlv) + tlv.it_len)))
+            {
                 /* Potential overflow. */
                 break;
             } else {
@@ -395,6 +402,9 @@
     if (info.it_magic != IMAGE_TLV_INFO_MAGIC) {
         return BOOT_EBADMAGIC;
     }
+    if (boot_add_uint32_overflow_check(off, (info.it_tlv_tot + sizeof(info)))) {
+        return -1;
+    }
     end = off + info.it_tlv_tot;
     off += sizeof(info);
 
@@ -513,7 +523,7 @@
         }
 
         /* Avoid integer overflow. */
-        if ((UINT32_MAX - off) < (sizeof(tlv) + tlv.it_len)) {
+        if (boot_add_uint32_overflow_check(off, (sizeof(tlv) + tlv.it_len))) {
             /* Potential overflow. */
             break;
         } else {