scsi: st: Fix use-after-free race between st_remove() and st_open()

st_remove() drops the probe reference on the scsi_tape with kref_put()
and only afterwards removes its index from st_index_idr. If that was the
last reference, scsi_tape_release() frees the structure while it is
still published in the idr.

scsi_tape_get(), called from st_open(), looks up the tape in
st_index_idr and takes a reference under st_ref_mutex and
st_index_lock. remove_cdevs() does not wait for opens that are already
past chrdev_open(), so an open that is blocked on st_ref_mutex while
st_remove() holds it can take the mutex as soon as st_remove() drops it,
find the freed tpnt in the idr and call kref_get() on it:

  BUG: KASAN: slab-use-after-free in st_open
  Write of size 4 ...
   st_open (drivers/scsi/st.c:254 drivers/scsi/st.c:1291)
   chrdev_open
  ...
  Freed by task ...:
   kfree
   st_remove (drivers/scsi/st.c:4512)

Remove the index from the idr before dropping the reference, all under
st_ref_mutex. A concurrent scsi_tape_get() now either runs first and
holds a valid reference that keeps the tape alive, or runs afterwards
and finds nothing, so st_open() fails with -ENXIO.

This restores the ordering st_remove() had before the conversion to
st_index_idr, where the tape was unpublished from scsi_tapes[] before
the final kref_put().

Fixes: 6c648d95a6 ("[SCSI] st: get rid of scsi_tapes array")
Cc: [email protected]
Reported-by: Dingisoul <[email protected]>
Closes: https://lore.kernel.org/linux-scsi/[email protected]/
Tested-by: Dingisoul <[email protected]>
Signed-off-by: Laurence Oberman <[email protected]>
Link: https://patch.msgid.link/[email protected]
Signed-off-by: Martin K. Petersen (Oracle) <[email protected]>
This commit is contained in:
Laurence Oberman authored and Martin K. Petersen (Oracle) committed 2026-10-13 22:56:51 -04:00
1 parent c9e9f024dd
commit 71caf7f84b
1 file changed
+2 -2
+2 -2
View File
@@ -4515,11 +4515,11 @@ static void st_remove(struct scsi_device *SDp)
remove_cdevs(tpnt);
mutex_lock(&st_ref_mutex);
kref_put(&tpnt->kref, scsi_tape_release);
mutex_unlock(&st_ref_mutex);
spin_lock(&st_index_lock);
idr_remove(&st_index_idr, index);
spin_unlock(&st_index_lock);
kref_put(&tpnt->kref, scsi_tape_release);
mutex_unlock(&st_ref_mutex);
}
/**