[PATCH v2] mtd: ubi: fix possible null-ptr-deref in ubi_free_volume()

Yang Yingliang yangyingliang at huawei.com
Fri Nov 11 20:14:43 PST 2022


It willl cause null-ptr-deref in the following case:

uif_init()
  ubi_add_volume()
    cdev_add() -> if it fails, call kill_volumes()
    device_register()

kill_volumes() -> if ubi_add_volume() fails call this function
  ubi_free_volume()
    cdev_del()
    device_unregister() -> trying to delete a not added device,
			   it causes null-ptr-deref

So in ubi_free_volume(), it delete devices whether they are added
or not, it will causes null-ptr-deref.

Fix this by adding some checks.

Fixes: 801c135ce73d ("UBI: Unsorted Block Images")
Signed-off-by: Yang Yingliang <yangyingliang at huawei.com>
---
v1 -> v2:
  Replace kfree() with vol_release() to avoid memory leak, if device is not initalized.
---
 drivers/mtd/ubi/vmt.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/drivers/mtd/ubi/vmt.c b/drivers/mtd/ubi/vmt.c
index 8fcc0bdf0635..5b7ad1c266cb 100644
--- a/drivers/mtd/ubi/vmt.c
+++ b/drivers/mtd/ubi/vmt.c
@@ -614,8 +614,14 @@ void ubi_free_volume(struct ubi_device *ubi, struct ubi_volume *vol)
 	dbg_gen("free volume %d", vol->vol_id);
 
 	ubi->volumes[vol->vol_id] = NULL;
-	cdev_del(&vol->cdev);
-	device_unregister(&vol->dev);
+	if (device_is_registered(&vol->dev)) {
+		cdev_del(&vol->cdev);
+		device_unregister(&vol->dev);
+	} else if (vol->dev.kobj.state_initialized) {
+		put_device(&vol->dev);
+	} else {
+		vol_release(&vol->dev);
+	}
 }
 
 /**
-- 
2.25.1




More information about the linux-mtd mailing list