Re: [PATCH] drivers/base/cpu: Use scnprintf() for avoiding potential buffer overflow

Greg Kroah-Hartman
2020-03-11T07:19:39Z

On Wed, Mar 11, 2020 at 08:12:00AM +0100, Takashi Iwai wrote:
> Since snprintf() returns the would-be-output size instead of the
> actual output size, the succeeding calls may go beyond the given
> buffer limit. Fix it by replacing with scnprintf().
>
> Signed-off-by: Takashi Iwai <tiwai@suse.de>
> ---
> drivers/base/cpu.c | 8 ++++----
> 1 file changed, 4 insertions(+), 4 deletions(-)
>
> diff --git a/drivers/base/cpu.c b/drivers/base/cpu.c
> index 6265871a4af2..0abcd9d68714 100644
> --- a/drivers/base/cpu.c
> +++ b/drivers/base/cpu.c
> @@ -231,7 +231,7 @@ static struct cpu_attr cpu_attrs[] = {
> static ssize_t print_cpus_kernel_max(struct device *dev,
> struct device_attribute *attr, char *buf)
> {
> - int n = snprintf(buf, PAGE_SIZE-2, "%d\n", NR_CPUS - 1);
> + int n = scnprintf(buf, PAGE_SIZE-2, "%d\n", NR_CPUS - 1);

This should just be "sprintf()" as we "know" that fitting a single
number will work.

> return n;
> }
> static DEVICE_ATTR(kernel_max, 0444, print_cpus_kernel_max, NULL);
> @@ -258,13 +258,13 @@ static ssize_t print_cpus_offline(struct device *dev,
> buf[n++] = ',';
>
> if (nr_cpu_ids == total_cpus-1)
> - n += snprintf(&buf[n], len - n, "%u", nr_cpu_ids);
> + n += scnprintf(&buf[n], len - n, "%u", nr_cpu_ids);
> else
> - n += snprintf(&buf[n], len - n, "%u-%d",
> + n += scnprintf(&buf[n], len - n, "%u-%d",
> nr_cpu_ids, total_cpus-1);
> }
>
> - n += snprintf(&buf[n], len - n, "\n");
> + n += scnprintf(&buf[n], len - n, "\n");

this part looks sane, can you respin this?

thanks,

greg k-h