[PATCH] rnbd-clt: fix use-after-free on device sysfs creation failure

Shuangpeng Bai <[email protected]>
Newsgroups org.kernel.vger.stable,org.kernel.vger.linux-block,org.kernel.vger.linux-kernel
Message-ID <[email protected]>
rnbd_clt_add_dev_kobj() initializes dev->kobj and adds it below the
gendisk kobject after rnbd_clt_map_device() has returned a live
rnbd_clt_dev to rnbd_clt_map_device_store().

If kobject_init_and_add() fails, the helper currently calls
kobject_put() on the embedded kobject. That put can drop the initial
kobject reference and run rnbd_dev_release(), freeing dev. The caller
then continues through the normal error path and calls
rnbd_clt_unmap_device(dev, true, NULL), dereferencing the freed device.

Leave the initialized kobject alive until the normal device teardown has
completed and rnbd_clt_put_dev() drops the final device reference. Since
kobject_init_and_add() failure can leave the kobject initialized but not
present in sysfs, only call kobject_del() from rnbd_destroy_sysfs() when
state_in_sysfs is set.

Fixes: 581cf833cac4 ("block: rnbd: add .release to rnbd_dev_ktype")
Cc: [email protected]
Signed-off-by: Shuangpeng Bai <[email protected]>
---
 drivers/block/rnbd/rnbd-clt-sysfs.c | 2 +-
 drivers/block/rnbd/rnbd-clt.c       | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/drivers/block/rnbd/rnbd-clt-sysfs.c b/drivers/block/rnbd/rnbd-clt-sysfs.c
index eb485e4c12e2..9f5d30659f3d 100644
--- a/drivers/block/rnbd/rnbd-clt-sysfs.c
+++ b/drivers/block/rnbd/rnbd-clt-sysfs.c
@@ -498,7 +498,7 @@ static int rnbd_clt_add_dev_kobj(struct rnbd_clt_dev *dev)
 	if (ret) {
 		rnbd_clt_err(dev, "Failed to create device sysfs dir, err: %d\n",
 			      ret);
-		kobject_put(&dev->kobj);
+		return ret;
 	}
 	kobject_uevent(gd_kobj, KOBJ_ONLINE);
 
diff --git a/drivers/block/rnbd/rnbd-clt.c b/drivers/block/rnbd/rnbd-clt.c
index 4d6725a0035e..5fe5c7e259b7 100644
--- a/drivers/block/rnbd/rnbd-clt.c
+++ b/drivers/block/rnbd/rnbd-clt.c
@@ -1658,7 +1658,7 @@ static void rnbd_destroy_sysfs(struct rnbd_clt_dev *dev,
 			  const struct attribute *sysfs_self)
 {
 	rnbd_clt_remove_dev_symlink(dev);
-	if (dev->kobj.state_initialized) {
+	if (dev->kobj.state_in_sysfs) {
 		if (sysfs_self)
 			/* To avoid deadlock firstly remove itself */
 			sysfs_remove_file_self(&dev->kobj, sysfs_self);
-- 
2.43.0
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.