Re: [PATCH 1/7] ext4: avoid overflow when setting values via sysfs

From: Baokun Li
Date: Sat Jan 27 2024 - 05:44:49 EST


On 2024/1/27 17:44, Alexey Dobriyan wrote:
Baokun Li wrote:

@@ -463,6 +463,8 @@ static ssize_t ext4_attr_store(struct kobject *kobj,
ret = kstrtoul(skip_spaces(buf), 0, &t);
if (ret)
return ret;
+ if (t != (unsigned int)t)
+ return -EINVAL;
kstrto*() interface has variants for all standard types.
It should be changed to kstrtou32() or kstrtouint();

If you check if kstrto*() result fits into another type,
you're probably doing it wrong.
Thanks for your comments!

The reason for not using those helper functions directly is as follows:

1)Those functions are also based on kstrtoull() wrappers, and if we
use kstrtou32() or kstrtouint(), we'd need to declare u32 t or int t,
which would leave us with a lot of declared but unused variables,
and an unsigned long t would be enough to cover our scenario.

2)Moreover, the actual range of a uint type sysfs interface may not
be 0-UINT_MAX, but 0-INT_MAX or 0-s_clusters_per_group, and we
need to limit the range of the variable according to the actual
meaning of the variable.

3)In addition, by declaring only an unsigned long type and then
uniformly parsing it with kstrtoul() and then restricting the range
of the variable according to the actual meaning of the variable,
we can reduce a lot of repetitive code.
if (a->attr_ptr == ptr_ext4_super_block_offset)
*((__le32 *) ptr) = cpu_to_le32(t);
--
With Best Regards,
Baokun Li
.