Re: [PATCH-next] scsi: fix use-after-free problem in scsi_remove_target

From: Bart Van Assche
Date: Wed Mar 01 2023 - 14:46:39 EST


On 2/12/23 19:43, Zhong Jinghua wrote:
T0 T1
sdev_store_delete
scsi_remove_device
device_remove_file
__scsi_remove_device
__iscsi_unbind_session
scsi_remove_target
spin_lock_irqsave
list_for_each_entry
scsi_target_reap // starget->reaf 1 -> 0

What is "reaf"? Did you perhaps want to write "reap_ref"?

diff --git a/drivers/scsi/scsi_sysfs.c b/drivers/scsi/scsi_sysfs.c
index e7893835b99a..0ad357ff4c59 100644
--- a/drivers/scsi/scsi_sysfs.c
+++ b/drivers/scsi/scsi_sysfs.c
@@ -1561,7 +1561,17 @@ void scsi_remove_target(struct device *dev)
starget->state == STARGET_CREATED_REMOVE)
continue;
if (starget->dev.parent == dev || &starget->dev == dev) {
- kref_get(&starget->reap_ref);
+
+ /*
+ * If starget->reap_ref is reduced to 0, it means
+ * that other processes are releasing it and
+ * there is no need to delete it again
+ */
+ if (!kref_get_unless_zero(&starget->reap_ref)) {
+ spin_unlock_irqrestore(shost->host_lock, flags);
+ goto restart;
+ }
+
if (starget->state == STARGET_CREATED)
starget->state = STARGET_CREATED_REMOVE;
else

The above comment should be made more clear, e.g. as follows: "If the reference count is already zero, skip this target. Calling kref_get_unless_zero() if the reference count is zero is safe because scsi_target_destroy() will wait until the host lock has been released before freeing starget."

Otherwise this patch looks fine to me.

Thanks,

Bart.