Re: [syzbot] [scsi?] [usb?] KASAN: slab-use-after-free Read in sg_release

From: Bart Van Assche
Date: Mon Nov 18 2024 - 14:27:47 EST


On 11/15/24 3:46 PM, syzbot wrote:
Hello,

syzbot has tested the proposed patch but the reproducer is still triggering an issue:
KASAN: slab-use-after-free Read in sg_release

==================================================================
BUG: KASAN: slab-use-after-free in sg_device_destroy+0x57/0x180 drivers/scsi/sg.c:1572
Read of size 8 at addr ffff888034a06008 by task syz.3.47/7437

CPU: 1 UID: 0 PID: 7437 Comm: syz.3.47 Not tainted 6.12.0-rc1-syzkaller-00116-g9024d215a5d3 #0
Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 10/30/2024
Call Trace:
<TASK>
__dump_stack lib/dump_stack.c:94 [inline]
dump_stack_lvl+0x241/0x360 lib/dump_stack.c:120
print_address_description mm/kasan/report.c:377 [inline]
print_report+0x169/0x550 mm/kasan/report.c:488
kasan_report+0x143/0x180 mm/kasan/report.c:601
sg_device_destroy+0x57/0x180 drivers/scsi/sg.c:1572
kref_put include/linux/kref.h:65 [inline]
sg_release+0x274/0x3c0 drivers/scsi/sg.c:404
__fput+0x23f/0x880 fs/file_table.c:431
task_work_run+0x24f/0x310 kernel/task_work.c:228
resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]
exit_to_user_mode_loop kernel/entry/common.c:114 [inline]
exit_to_user_mode_prepare include/linux/entry-common.h:328 [inline]
__syscall_exit_to_user_mode_work kernel/entry/common.c:207 [inline]
syscall_exit_to_user_mode+0x168/0x370 kernel/entry/common.c:218
do_syscall_64+0x100/0x230 arch/x86/entry/common.c:89
entry_SYSCALL_64_after_hwframe+0x77/0x7f

The above output shows that the tested patch postponed the use-after-
free from the mutex_unlock() call in sg_release to the code that I
inserted after that call. This is the patch that has been tested:

diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 84334ab39c81..6c6e03f37b5f 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -385,6 +385,8 @@ sg_release(struct inode *inode, struct file *filp)
return -ENXIO;
SCSI_LOG_TIMEOUT(3, sg_printk(KERN_INFO, sdp, "sg_release\n"));

+ kref_get(&sdp->d_ref);
+
mutex_lock(&sdp->open_rel_lock);
kref_put(&sfp->f_ref, sg_remove_sfp);
sdp->open_cnt--;
@@ -398,6 +400,9 @@ sg_release(struct inode *inode, struct file *filp)
wake_up_interruptible(&sdp->open_wait);
}
mutex_unlock(&sdp->open_rel_lock);
+
+ kref_put(&sdp->d_ref, sg_device_destroy);
+
return 0;
}