From: Kshitiz Varshney <kshitiz.varshney@nxp.com>
Date: Sun, 1 Aug 2021 12:31:45 +0000 (+0200)
Subject: board: fsl_validate: Fix resource leak issue
X-Git-Tag: v2025.01-rc5-pxa1908~1739^2~9
X-Git-Url: http://git.dujemihanovic.xyz/html/static/git-logo.png?a=commitdiff_plain;h=0dfa9da277a4556f9e7faa0101c7694fe2b78733;p=u-boot.git

board: fsl_validate: Fix resource leak issue

Free dynamically allocated memory before every return statement
in calc_img_key_hash() and calc_esbchdr_esbc_hash() function.
Verified the secure boot changes using ls1046afrwy board.

Signed-off-by: Kshitiz Varshney <kshitiz.varshney@nxp.com>
Reviewed-by: Priyanka Jain <priyanka.jain@nxp.com>
---

diff --git a/board/freescale/common/fsl_validate.c b/board/freescale/common/fsl_validate.c
index 066aa9a7c3..c90afe2e21 100644
--- a/board/freescale/common/fsl_validate.c
+++ b/board/freescale/common/fsl_validate.c
@@ -1,6 +1,7 @@
 // SPDX-License-Identifier: GPL-2.0+
 /*
  * Copyright 2015 Freescale Semiconductor, Inc.
+ * Copyright 2021 NXP
  */
 
 #include <common.h>
@@ -498,8 +499,11 @@ static int calc_img_key_hash(struct fsl_secboot_img_priv *img)
 		return ret;
 
 	ret = algo->hash_init(algo, &ctx);
-	if (ret)
+	if (ret) {
+		if (ctx)
+			free(ctx);
 		return ret;
+	}
 
 	/* Update hash for ESBC key */
 #ifdef CONFIG_KEY_REVOCATION
@@ -518,8 +522,11 @@ static int calc_img_key_hash(struct fsl_secboot_img_priv *img)
 
 	/* Copy hash at destination buffer */
 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
-	if (ret)
+	if (ret) {
+		if (ctx)
+			free(ctx);
 		return ret;
+	}
 
 	for (i = 0; i < SHA256_BYTES; i++)
 		img->img_key_hash[i] = hash_val[i];
@@ -547,14 +554,18 @@ static int calc_esbchdr_esbc_hash(struct fsl_secboot_img_priv *img)
 
 	ret = algo->hash_init(algo, &ctx);
 	/* Copy hash at destination buffer */
-	if (ret)
+	if (ret) {
+		free(ctx);
 		return ret;
+	}
 
 	/* Update hash for CSF Header */
 	ret = algo->hash_update(algo, ctx,
 		(u8 *)&img->hdr, sizeof(struct fsl_secboot_img_hdr), 0);
-	if (ret)
+	if (ret) {
+		free(ctx);
 		return ret;
+	}
 
 	/* Update the hash with that of srk table if srk flag is 1
 	 * If IE Table is selected, key is not added in the hash
@@ -581,22 +592,29 @@ static int calc_esbchdr_esbc_hash(struct fsl_secboot_img_priv *img)
 		key_hash = 1;
 	}
 #endif
-	if (ret)
+	if (ret) {
+		free(ctx);
 		return ret;
-	if (!key_hash)
+	}
+	if (!key_hash) {
+		free(ctx);
 		return ERROR_KEY_TABLE_NOT_FOUND;
+	}
 
 	/* Update hash for actual Image */
 	ret = algo->hash_update(algo, ctx,
 		(u8 *)(*(img->img_addr_ptr)), img->img_size, 1);
-	if (ret)
+	if (ret) {
+		free(ctx);
 		return ret;
+	}
 
 	/* Copy hash at destination buffer */
 	ret = algo->hash_finish(algo, ctx, hash_val, algo->digest_size);
-	if (ret)
+	if (ret) {
+		free(ctx);
 		return ret;
-
+	}
 	return 0;
 }