app: aboot: Verify boot image signature

Verify boot image signature as part of fastboot boot
command and fix buffer over read issues by sanitize
the kernel, ramdisk, page size read from boot image
header.

CRs-Fixed: 681957 682002
Change-Id: I546502c7a9479c8a41453e32c6cb14bc850709fe
diff --git a/app/aboot/aboot.c b/app/aboot/aboot.c
index 21b0c41..fc6bf34 100755
--- a/app/aboot/aboot.c
+++ b/app/aboot/aboot.c
@@ -35,6 +35,7 @@
 #include <arch/arm.h>
 #include <string.h>
 #include <stdlib.h>
+#include <limits.h>
 #include <kernel/thread.h>
 #include <arch/ops.h>
 
@@ -106,6 +107,8 @@
 
 #define IS_ARM64(ptr) (ptr->magic_64 == KERNEL64_HDR_MAGIC) ? true : false
 
+#define ADD_OF(a, b) (UINT_MAX - b > a) ? (a + b) : UINT_MAX
+
 #if UFS_SUPPORT
 static const char *emmc_cmdline = " androidboot.bootdevice=";
 #else
@@ -1574,6 +1577,8 @@
 {
 	unsigned kernel_actual;
 	unsigned ramdisk_actual;
+	uint32_t image_actual;
+	uint32_t dt_actual = 0;
 	struct boot_img_hdr *hdr;
 	struct kernel64_hdr *kptr;
 	char *ptr = ((char*) data);
@@ -1597,6 +1602,25 @@
 
 	kernel_actual = ROUND_TO_PAGE(hdr->kernel_size, page_mask);
 	ramdisk_actual = ROUND_TO_PAGE(hdr->ramdisk_size, page_mask);
+#if DEVICE_TREE
+	dt_actual = ROUND_TO_PAGE(hdr->dt_size, page_mask);
+#endif
+
+	image_actual = ADD_OF(page_size, kernel_actual);
+	image_actual = ADD_OF(image_actual, ramdisk_actual);
+	image_actual = ADD_OF(image_actual, dt_actual);
+
+	/* sz should have atleast raw boot image */
+	if (image_actual > sz) {
+		fastboot_fail("incomplete bootimage");
+		return;
+	}
+
+	/* Verify the boot image
+	 * device & page_size are initialized in aboot_init
+	 */
+	if (target_use_signed_kernel() && (!device.is_unlocked))
+		verify_signed_bootimg((uint32_t)data, image_actual);
 
 	/*
 	 * Update the kernel/ramdisk/tags address if the boot image header
@@ -1619,12 +1643,6 @@
 		return;
 	}
 
-	/* sz should have atleast raw boot image */
-	if (page_size + kernel_actual + ramdisk_actual > sz) {
-		fastboot_fail("incomplete bootimage");
-		return;
-	}
-
 #if DEVICE_TREE
 	/* find correct dtb and copy it to right location */
 	ret = copy_dtb(data);