From baaa810e604aa3afd8cf9832a5b29828d6ffc6f4 Mon Sep 17 00:00:00 2001
From: Ji Luo <ji.luo@nxp.com>
Date: Thu, 26 Nov 2020 13:21:33 +0800
Subject: [PATCH] MA-18325 Pad keyslot_package struct to one block size

blk_dwrite() will write data in blocks, padding the keyslot_package
struct to one block to avoid redundant data write.

Test: RPMB key set.

Change-Id: I326d7f4394d15e6e22b12c3abd6a5e2de18920cc
Signed-off-by: Ji Luo <ji.luo@nxp.com>
(cherry picked from commit 8a0deb19628d2752b516fbce00fc1b988f2e78b5)
---
 lib/avb/fsl/fsl_avbkey.c | 10 ++++++----
 lib/avb/fsl/fsl_avbkey.h |  3 +++
 2 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/lib/avb/fsl/fsl_avbkey.c b/lib/avb/fsl/fsl_avbkey.c
index 4c0dd94..1c9643e 100644
--- a/lib/avb/fsl/fsl_avbkey.c
+++ b/lib/avb/fsl/fsl_avbkey.c
@@ -712,6 +712,7 @@ int init_avbkey(void) {
 	read_keyslot_package(&kp);
 	if (strcmp(kp.magic, KEYPACK_MAGIC)) {
 		printf("keyslot package magic error. Will generate new one\n");
+		memset((void *)&kp, 0, sizeof(struct keyslot_package));
 		gen_rpmb_key(&kp);
 	}
 #ifndef CONFIG_IMX_TRUSTY_OS
@@ -1229,6 +1230,7 @@ int do_rpmb_key_set(uint8_t *key, uint32_t key_size)
 		printf("RPMB key programed successfully!\n");
 
 	/* Generate keyblob with CAAM. */
+	memset((void *)&kp, 0, sizeof(struct keyslot_package));
 	kp.rpmb_keyblob_len = RPMBKEY_LENGTH + CAAM_PAD;
 	strcpy(kp.magic, KEYPACK_MAGIC);
 	if (hwcrypto_gen_blob((uint32_t)(ulong)rpmb_key, RPMBKEY_LENGTH,
@@ -1241,6 +1243,10 @@ int do_rpmb_key_set(uint8_t *key, uint32_t key_size)
 
 	memcpy(kp.rpmb_keyblob, blob, kp.rpmb_keyblob_len);
 
+	/* Reset key after use */
+	memset(rpmb_key, 0, RPMBKEY_LENGTH);
+	memset(key, 0, RPMBKEY_LENGTH);
+
 	/* Store the rpmb key blob to last block of boot1 partition. */
 	if (mmc_switch_part(mmc, KEYSLOT_HWPARTITION_ID) != 0) {
 		printf("ERROR - can't switch to boot1 partition! \n");
@@ -1261,10 +1267,6 @@ int do_rpmb_key_set(uint8_t *key, uint32_t key_size)
 		goto fail;
 	}
 
-	/* Erase the key buffer. */
-	memset(rpmb_key, 0, RPMBKEY_LENGTH);
-	memset(key, 0, RPMBKEY_LENGTH);
-
 fail:
 	/* Return to original partition */
 	if (desc->hwpart != original_part) {
diff --git a/lib/avb/fsl/fsl_avbkey.h b/lib/avb/fsl/fsl_avbkey.h
index 8dd8746..a4343e0 100644
--- a/lib/avb/fsl/fsl_avbkey.h
+++ b/lib/avb/fsl/fsl_avbkey.h
@@ -82,12 +82,15 @@ typedef struct kblb_hdr kblb_hdr_t;
 
 #define RPMBKEY_LEN (32 + CAAM_PAD)
 #define KEYPACK_MAGIC "!KS"
+#define KEYPACK_PAD_LENGTH (512 - 4 * sizeof(char) - sizeof(unsigned int) - RPMBKEY_LEN * sizeof(unsigned char))
 
 struct keyslot_package
 {
     char magic[4];
     unsigned int rpmb_keyblob_len;
     unsigned char rpmb_keyblob[RPMBKEY_LEN];
+    // padding keyslot_package to 1 block size
+    unsigned char pad[KEYPACK_PAD_LENGTH];
 };
 
 int gen_rpmb_key(struct keyslot_package *kp);
-- 
1.9.1