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

From: zhongjinghua
Date: Mon Mar 06 2023 - 03:30:00 EST



在 2023/3/2 3:46, Bart Van Assche 写道:
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"?
Yes, I will modify late.

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."

Agree. Thanks for your e.g.

I will send the v2 late.


Otherwise this patch looks fine to me.

Thanks,

Bart.


Thanks,

Jinghua