From d8151f98331ee4d15fcca59edffa59246d8fc15f Mon Sep 17 00:00:00 2001
From: Alec Brown <alec.r.brown@oracle.com>
Date: Wed, 22 Jan 2025 02:55:10 +0000
Subject: [PATCH 51/73] disk: Prevent overflows when allocating memory for
 arrays

Use grub_calloc() when allocating memory for arrays to ensure proper
overflow checks are in place.

Signed-off-by: Alec Brown <alec.r.brown@oracle.com>
Reviewed-by: Daniel Kiper <daniel.kiper@oracle.com>
---
 grub-core/disk/cryptodisk.c | 2 +-
 grub-core/disk/lvm.c        | 6 ++----
 2 files changed, 3 insertions(+), 5 deletions(-)

diff --git a/grub-core/disk/cryptodisk.c b/grub-core/disk/cryptodisk.c
index 431db2fae..7a785a49c 100644
--- a/grub-core/disk/cryptodisk.c
+++ b/grub-core/disk/cryptodisk.c
@@ -1532,7 +1532,7 @@ grub_cmd_cryptomount (grub_extcmd_context_t ctxt, int argc, char **args)
 
   if (state[OPTION_PROTECTOR].set) /* key protector(s) */
     {
-      cargs.key_cache = grub_zalloc (state[OPTION_PROTECTOR].set * sizeof (*cargs.key_cache));
+      cargs.key_cache = grub_calloc (state[OPTION_PROTECTOR].set, sizeof (*cargs.key_cache));
       if (cargs.key_cache == NULL)
 	return grub_error (GRUB_ERR_OUT_OF_MEMORY,
 			   "no memory for key protector key cache");
diff --git a/grub-core/disk/lvm.c b/grub-core/disk/lvm.c
index 0c32c95f9..b53c3b75e 100644
--- a/grub-core/disk/lvm.c
+++ b/grub-core/disk/lvm.c
@@ -671,8 +671,7 @@ grub_lvm_detect (grub_disk_t disk,
 			  goto lvs_segment_fail;
 			}
 
-		      seg->nodes = grub_zalloc (sizeof (seg->nodes[0])
-						* seg->node_count);
+		      seg->nodes = grub_calloc (seg->node_count, sizeof (seg->nodes[0]));
 
 		      p = grub_strstr (p, "mirrors = [");
 		      if (p == NULL)
@@ -760,8 +759,7 @@ grub_lvm_detect (grub_disk_t disk,
 			    }
 			}
 
-		      seg->nodes = grub_zalloc (sizeof (seg->nodes[0])
-						* seg->node_count);
+		      seg->nodes = grub_calloc (seg->node_count, sizeof (seg->nodes[0]));
 
 		      p = grub_strstr (p, "raids = [");
 		      if (p == NULL)
-- 
2.33.0

