Skip to contentSkip to conversation

mei: do not let mei_open() find a released mei_device

PATCH New Changyul Lee 1 participant 1 message Nov 17

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 mei: do not let mei_open() find a released mei_device

mei_open() looks up the mei_device in mei_idr without mei_minor_lock or RCU and only then takes a reference with get_device(). Two things can go wrong.

On a preemptible kernel the walk can read an IDR node that idr_remove() for another device has already freed through RCU.

The device can also be freed before the reference is taken. An open() of an earlier device's character device can be delayed between chrdev_open() and mei_open() while that device is removed and its minor is handed to a new device. If mei_register() of the new device fails, put_device() frees it while mei_idr still points at it. mei_deregister() has the same window, because device_destroy() runs before mei_minor_free().

Do the lookup and get_device() under mei_minor_lock, and stop mei_idr from pointing at the device before its last reference can be dropped. mei_register() frees the minor before put_device(), and mei_deregister() clears the entry with idr_replace() before device_destroy(), which keeps the minor reserved until the old device is gone.

Found with a static analysis tool we are developing. Compile-tested only, with x86_64_defconfig plus INTEL_MEI, INTEL_MEI_ME and W=1.

Fixes 7704e6be4ed2 ("mei: hook mei_device on class device")
Fixes a6dab2f61d23 ("mei: Fix error handling in mei_register")
---
 drivers/misc/mei/main.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/misc/mei/main.c +10 -2
index 4fbf0b323616..5a8570e54801 100644
@@ -53,10 +53,13 @@ static int mei_open(struct inode *inode, struct file *file)
 
 	int err;
 
+	mutex_lock(&mei_minor_lock);
 	dev = idr_find(&mei_idr, iminor(inode));
+	if (dev)
+		get_device(&dev->dev);
+	mutex_unlock(&mei_minor_lock);
 	if (!dev)
 		return -ENODEV;
-	get_device(&dev->dev);
 
 	mutex_lock(&dev->device_lock);
 
@@ -1324,8 +1327,8 @@ int mei_register(struct mei_device *dev, struct device *parent)
 err_del_cdev:
 	cdev_del(dev->cdev);
 err:
-	put_device(&dev->dev);
 	mei_minor_free(minor);
+	put_device(&dev->dev);
 	return ret;
 }
 EXPORT_SYMBOL_GPL(mei_register);
@@ -1340,6 +1343,11 @@ void mei_deregister(struct mei_device *dev)
 
 	mei_dbgfs_deregister(dev);
 
+	/* Keep the minor reserved, but stop mei_open() from finding dev. */
+	mutex_lock(&mei_minor_lock);
+	idr_replace(&mei_idr, NULL, minor);
+	mutex_unlock(&mei_minor_lock);
+
 	device_destroy(&mei_class, devno);
 
 	mei_minor_free(minor);

base-commit: 7475ea8b58616b33c04afb976cf0fbaad9dd63fb

Signature · 1 line
2.43.0