[PATCH -next] scsi: snic: fix double free in snic_tgt_create()

From: Zhu Wang
Date: Sat Aug 19 2023 - 04:40:19 EST


The commit 41320b18a0e0 ("scsi: snic: Fix possible memory leak if
device_add() fails") fix the memory leak caused by dev_set_name() when
device_add() failed. While it did not consider that 'tgt' has already been
released when put_device(&tgt->dev) is called. We removed kfree(tgt) in
the error path to avoid double free 'tgt'. And we moved
put_device(&tgt->dev) after the removed kfree(tgt) to avoid UAF
(Use-After-Free).

Fixes: 41320b18a0e0 ("scsi: snic: Fix possible memory leak if device_add() fails")
Signed-off-by: Zhu Wang <wangzhu9@xxxxxxxxxx>
---
drivers/scsi/snic/snic_disc.c | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/drivers/scsi/snic/snic_disc.c b/drivers/scsi/snic/snic_disc.c
index e429ad23c396..4db3ba62fcd3 100644
--- a/drivers/scsi/snic/snic_disc.c
+++ b/drivers/scsi/snic/snic_disc.c
@@ -303,12 +303,11 @@ snic_tgt_create(struct snic *snic, struct snic_tgt_id *tgtid)
"Snic Tgt: device_add, with err = %d\n",
ret);

- put_device(&tgt->dev);
put_device(&snic->shost->shost_gendev);
spin_lock_irqsave(snic->shost->host_lock, flags);
list_del(&tgt->list);
spin_unlock_irqrestore(snic->shost->host_lock, flags);
- kfree(tgt);
+ put_device(&tgt->dev);
tgt = NULL;

return tgt;
--
2.34.1