hwmon: Fix potential UAF in pec_store

Sashiko reports:

In pec_store(), a guard(mutex)(&hwdev->lock) is taken. If the chip write
operation returns an error other than -EOPNOTSUPP, the code jumps to the
put label, which calls put_device(hdev). If this drops the final reference,
the device is freed. When the function then returns, the guard cleanup
function runs and attempts to unlock the freed mutex.

Use scoped_guard() instead of guard() to avoid the problem.

Fixes: 3ad2a7b9b1 ("hwmon: Serialize accesses in hwmon core")
Signed-off-by: Guenter Roeck <linux@roeck-us.net>
This commit is contained in:
Guenter Roeck 2026-08-20 10:51:50 -07:00
parent b4fffa75c1
commit 354ccc99b2

View File

@ -371,18 +371,17 @@ static ssize_t pec_store(struct device *dev, const struct device_attribute *deva
* handling is not required.
*/
hwdev = to_hwmon_device(hdev);
guard(mutex)(&hwdev->lock);
if (hwdev->chip->ops->write) {
err = hwdev->chip->ops->write(hdev, hwmon_chip, hwmon_chip_pec, 0, val);
if (err && err != -EOPNOTSUPP)
goto put;
scoped_guard(mutex, &hwdev->lock) {
if (hwdev->chip->ops->write) {
err = hwdev->chip->ops->write(hdev, hwmon_chip, hwmon_chip_pec, 0, val);
if (err && err != -EOPNOTSUPP)
goto put;
}
if (!val)
client->flags &= ~I2C_CLIENT_PEC;
else
client->flags |= I2C_CLIENT_PEC;
}
if (!val)
client->flags &= ~I2C_CLIENT_PEC;
else
client->flags |= I2C_CLIENT_PEC;
err = count;
put:
put_device(hdev);