[PATCH] scsi: megaraid: fix a possible double-free bug caused by incorrect error handling in megasas_alloc_cmdlist_fusion()

From: Zixuan Fu
Date: Thu Sep 01 2022 - 08:54:31 EST


In megasas_alloc_cmdlist_fusion(), when kzalloc() fails, it frees
fusion->cmd_list but does not clear it. Then, the error is propagated to
its caller megasas_alloc_cmds_fusion(), which calls
megasas_free_cmds_fusion(). In megasas_free_cmds_fusion(), it frees
fusion->cmd_list again, which causes a double-free bug.

To fix this possible bug, in megasas_alloc_cmdlist_fusion(),
fusion->cmd_list should be cleared after it is freed.

The error log in our fault-injection testing is shown as follows:

[ 4152.707452][ T21] BUG: KASAN: use-after-free in megasas_free_cmds_fusion+0x2d0/0x1294 [megaraid_sas]
...
[ 4152.756117][ T21] Call trace:
...
[ 4152.795950][ T21] megasas_free_cmds_fusion+0x2d0/0x1294 [megaraid_sas]
[ 4152.803329][ T21] megasas_alloc_cmds_fusion+0x4de0/0x53bc [megaraid_sas]
[ 4152.810887][ T21] megasas_init_adapter_fusion+0xab4/0x30dc [megaraid_sas]
[ 4152.818539][ T21] megasas_init_fw+0x4874/0x925c [megaraid_sas]
[ 4152.825245][ T21] megasas_probe_one+0x978/0x2dd4 [megaraid_sas]
...
[ 4152.864486][ T21] Allocated by task 21:
...
[ 4152.883339][ T21] megasas_alloc_cmds_fusion+0x2a40/0x53bc [megaraid_sas]
[ 4152.890796][ T21] megasas_init_adapter_fusion+0xab4/0x30dc [megaraid_sas]
[ 4152.898331][ T21] megasas_init_fw+0x4874/0x925c [megaraid_sas]
[ 4152.904901][ T21] megasas_probe_one+0x978/0x2dd4 [megaraid_sas]
...
[ 4152.943038][ T21] Freed by task 21:
...
[ 4152.972830][ T21] kfree+0x100/0x374
[ 4152.976998][ T21] megasas_alloc_cmds_fusion+0x45c4/0x53bc [megaraid_sas]
[ 4152.984379][ T21] megasas_init_adapter_fusion+0xab4/0x30dc [megaraid_sas]
[ 4152.991856][ T21] megasas_init_fw+0x4874/0x925c [megaraid_sas]
[ 4152.998384][ T21] megasas_probe_one+0x978/0x2dd4 [megaraid_sas]


Fixes: 70c54e210ee9a ("scsi: megaraid_sas: fix memleak in megasas_alloc_cmdlist_fusion")
Reported-by: TOTE Robot <oslab@xxxxxxxxxxxxxxx>
Signed-off-by: Zixuan Fu <r33s3n6@xxxxxxxxx>
---
drivers/scsi/megaraid/megaraid_sas_fusion.c | 1 +
1 file changed, 1 insertion(+)

diff --git a/drivers/scsi/megaraid/megaraid_sas_fusion.c b/drivers/scsi/megaraid/megaraid_sas_fusion.c
index 09c5fe37754c..238103e7a028 100644
--- a/drivers/scsi/megaraid/megaraid_sas_fusion.c
+++ b/drivers/scsi/megaraid/megaraid_sas_fusion.c
@@ -613,6 +613,7 @@ megasas_alloc_cmdlist_fusion(struct megasas_instance *instance)
for (j = 0; j < i; j++)
kfree(fusion->cmd_list[j]);
kfree(fusion->cmd_list);
+ fusion->cmd_list = NULL;
dev_err(&instance->pdev->dev,
"Failed from %s %d\n", __func__, __LINE__);
return -ENOMEM;
--
2.25.1