[U-Boot,v2,6/8] rsa: Fix missing memory leak on error in fdt_add_bignum()

Message ID 20180612060502.196817-7-sjg@chromium.org
State Under Review
Delegated to: Tom Rini
Headers show
Series
  • Fix some coverity warnings
Related show

Commit Message

Simon Glass June 12, 2018, 6:05 a.m.
Thsi function can fail without freeing all its memory. Fix it.

Reported-by: Coverity (CID: 131217)
Signed-off-by: Simon Glass <sjg@chromium.org>
---

Changes in v2:
- Add a comment defending the technical memory leaks that remain

 lib/rsa/rsa-sign.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)

Comments

Tom Rini June 19, 2018, 6:42 p.m. | #1
On Tue, Jun 12, 2018 at 12:05:00AM -0600, Simon Glass wrote:

> Thsi function can fail without freeing all its memory. Fix it.
> 
> Reported-by: Coverity (CID: 131217)
> Signed-off-by: Simon Glass <sjg@chromium.org>

Applied to u-boot/master, thanks!

Patch

diff --git a/lib/rsa/rsa-sign.c b/lib/rsa/rsa-sign.c
index d2788bf79a..cfe09cc94c 100644
--- a/lib/rsa/rsa-sign.c
+++ b/lib/rsa/rsa-sign.c
@@ -635,6 +635,15 @@  static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
 	big2 = BN_new();
 	big32 = BN_new();
 	big2_32 = BN_new();
+
+	/*
+	 * Note: This code assumes that all of the above succeed, or all fail.
+	 * In practice memory allocations generally do not fail (unless the
+	 * process is killed), so it does not seem worth handling each of these
+	 * as a separate case. Technicaly this could leak memory on failure,
+	 * but a) it won't happen in practice, and b) it doesn't matter as we
+	 * will immediately exit with a failure code.
+	 */
 	if (!tmp || !big2 || !big32 || !big2_32) {
 		fprintf(stderr, "Out of memory (bignum)\n");
 		return -ENOMEM;
@@ -667,15 +676,13 @@  static int fdt_add_bignum(void *blob, int noffset, const char *prop_name,
 	 * might fail several times
 	 */
 	ret = fdt_setprop(blob, noffset, prop_name, buf, size);
-	if (ret)
-		return -FDT_ERR_NOSPACE;
 	free(buf);
 	BN_free(tmp);
 	BN_free(big2);
 	BN_free(big32);
 	BN_free(big2_32);
 
-	return ret;
+	return ret ? -FDT_ERR_NOSPACE : 0;
 }
 
 int rsa_add_verify_data(struct image_sign_info *info, void *keydest)