Re: KASAN: use-after-free Read in sg_release

From: Douglas Gilbert
Date: Wed Sep 28 2022 - 17:45:37 EST


On 2022-09-22 17:29, Tony Battersby wrote:
On 9/20/22 10:46, Rondreis wrote:
Hello,

When fuzzing the Linux kernel driver v6.0-rc6, the following crash was
triggered.

HEAD commit: 521a547ced6477c54b4b0cc206000406c221b4d6
git tree: upstream

kernel config: https://pastebin.com/raw/hekxU61F
console output: https://pastebin.com/raw/73a8RzBY

Sorry for failing to extract the reproducer. But on other versions of
Linux, I also triggered this crash.

I would appreciate it if you have any idea how to solve this bug.

sg_release() calls "kref_put(&sfp->f_ref, sg_remove_sfp)" which
eventually does "kref_put(&sdp->d_ref, sg_device_destroy)" which does
"kfree(sdp)", but sg_release() continues to access sdp afterward.  Try
the following patch.

From 82ca6785c40eded6229183a53752fc5e43db4a94 Mon Sep 17 00:00:00 2001
From: Tony Battersby <tonyb@xxxxxxxxxxxxxxx>
Date: Thu, 22 Sep 2022 11:05:30 -0400
Subject: [PATCH] scsi: sg: fix memory-use-after-free on device removal

Fix memory-use-after-free race when closing a sg fd to a removed device.

Link: https://lore.kernel.org/linux-scsi/CAB7eexK_jr1LWOO9RWrBF9as7gAS9kpHjrZFRuRrRJF=1H4W6A@xxxxxxxxxxxxxx/
Reported-by: Rondreis <linhaoguo86@xxxxxxxxx>
Cc: <stable@xxxxxxxxxxxxxxx>
Signed-off-by: Tony Battersby <tonyb@xxxxxxxxxxxxxxx>
---
drivers/scsi/sg.c | 2 ++
1 file changed, 2 insertions(+)

diff --git a/drivers/scsi/sg.c b/drivers/scsi/sg.c
index 340b050ad28d..f44cbe42dba9 100644
--- a/drivers/scsi/sg.c
+++ b/drivers/scsi/sg.c
@@ -388,6 +388,7 @@ 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);
scsi_autopm_put_device(sdp->device);
kref_put(&sfp->f_ref, sg_remove_sfp);
@@ -402,6 +403,7 @@ 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;
}


Hi Rondreis,
Have you been able to test the above patch from Tony?

Doug Gilbert