Re: [PATCH] lm85: Bounds check to_sensor_dev_attr()->index usage

From: Kees Cook
Date: Fri Feb 03 2023 - 17:35:13 EST


On Sat, Jan 28, 2023 at 05:13:19AM -0800, Guenter Roeck wrote:
> On Fri, Jan 27, 2023 at 02:37:45PM -0800, Kees Cook wrote:
> > The index into various register arrays was not bounds checked. Add
> > checking. Seen under GCC 13:
> >
> > drivers/hwmon/lm85.c: In function 'pwm_auto_pwm_minctl_store':
> > drivers/hwmon/lm85.c:1110:26: warning: array subscript [0, 31] is outside array bounds of 'struct lm85_autofan[3]' [-Warray-bounds=]
> > 1110 | if (data->autofan[nr].min_off)
> > | ~~~~~~~~~~~~~^~~~
> > drivers/hwmon/lm85.c:317:29: note: while referencing 'autofan'
> > 317 | struct lm85_autofan autofan[3];
> > | ^~~~~~~
> >
>
> This is a false positive. The value can never be >= 3.
> It is derived from the last value of the following
> SENSOR_DEVICE_ATTR_RW() entries.
>
> I resist making changes like this to the code just because
> the compiler can not determine the range of a variable.
> It blows up code size amd makes it hard to read just to
> make the compiler happy.

I think it's worth it given the index is an "int" and it'd be very easy
for things to go wrong in the face of other memory corruption, etc. I've
sent a v2 that I think is much more readable and non-invasive but
provides similar robustness.

-Kees

--
Kees Cook