Boot: Add security counter to image manifest

Add command line argument to the imgtool that can be used to add a
security counter TLV to the image manifest. This security counter value
can be used in rollback protection to compare the new image's security
counter against the active image's counter. It can be independent from
the image version, but if it is not specified in the argument list then
the script will generate it from the image version number
(not including the build number).

The value of the security counter is security critical data. Therefore,
this part of the TLV area must be included in the integrity protected
part of the image.

Add security counter to the build system. It can be specified at build
time with "-DSECURITY_COUNTER=<value>", otherwise the generated
security counter value will be added to the signed image.

Change-Id: Ia9773ad7a57fc3a8cc022e1c1df4321e27c912ec
Signed-off-by: David Vincze <david.vincze@arm.com>
diff --git a/bl2/ext/mcuboot/bootutil/src/image_validate.c b/bl2/ext/mcuboot/bootutil/src/image_validate.c
index 5cb4b49..68f1c40 100644
--- a/bl2/ext/mcuboot/bootutil/src/image_validate.c
+++ b/bl2/ext/mcuboot/bootutil/src/image_validate.c
@@ -63,11 +63,17 @@
         bootutil_sha256_update(&sha256_ctx, seed, seed_len);
     }
 
-    /*
-     * Hash is computed over image header and image itself. No TLV is
-     * included ATM.
-     */
+    /* Hash is computed over image header and image itself. */
     size = hdr->ih_img_size + hdr->ih_hdr_size;
+
+    /* If a security counter TLV is present then the TLV info header and the
+     * security counter are also protected and must be included in the hash
+     * calculation.
+     */
+    if (hdr->ih_protect_tlv_size != 0) {
+        size += hdr->ih_protect_tlv_size;
+    }
+
     for (off = 0; off < size; off += blk_sz) {
         blk_sz = size - off;
         if (blk_sz > tmp_buf_sz) {
@@ -229,7 +235,6 @@
     }
 
     /* The TLVs come after the image. */
-    /* After image there are TLVs. */
     off = hdr->ih_img_size + hdr->ih_hdr_size;
 
     rc = flash_area_read(fap, off, &info, sizeof(info));