Re: [PATCH] EDAC/mc: Prefer strscpy or scnprintf over strcpy, sprintf and snprintf

From: Borislav Petkov
Date: Wed Sep 15 2021 - 07:58:40 EST


On Mon, Sep 13, 2021 at 10:59:10AM +0200, Robert Richter wrote:
> From 01a3c62a533e71984dfff7189e247b3e848f1449 Mon Sep 17 00:00:00 2001
> From: Len Baker <len.baker@xxxxxxx>
> Date: Fri, 3 Sep 2021 17:05:39 +0200
> Subject: [PATCH] EDAC/mc: Prefer strscpy or scnprintf over strcpy, sprintf
> and snprintf
>
> strcpy() performs no bounds checking on the destination buffer. This
> could result in linear overflows beyond the end of the buffer, leading
> to all kinds of misbehaviors. The safe replacement is strscpy().
> [1][2]
>
> However, to simplify and clarify the code, to concatenate labels use
> the scnprintf() function. This way it is not necessary to check the
> return value of strscpy (-E2BIG if the parameter count is 0 or the src
> was truncated) since the scnprintf returns always the number of chars
> written into the buffer. This function returns always a nul-terminated
> string even if it needs to be truncated.
>
> While at it, fix all other broken string generation code that wrongly
> interprets snprintf()'s return code or just uses sprintf(), implement
> that using scnprintf() here too. Drop breaks in loops around
> scnprintf() as it is safe now to loop. Moreover, the check is
> needless: For the case when the buffer is exhausted, len never gets
> zero because scnprintf() takes the full buffer length as input
> parameter, but excludes the trailing '\0' in its return code and thus,
> 1 is the minimum len.
>
> [1] https://www.kernel.org/doc/html/latest/process/deprecated.html#strcpy
> [2] https://github.com/KSPP/linux/issues/88
>
> [ rric: Replace snprintf() with scnprintf(), rework sprintf() user,
> drop breaks in loops around scnprintf(), introduce 'end' pointer to
> reduce pointer arithmetic, use prefix pattern for e->location,
> adjust subject and description ]
>
> Co-developed-by: Joe Perches <joe@xxxxxxxxxxx>
> Signed-off-by: Joe Perches <joe@xxxxxxxxxxx>
> Signed-off-by: Len Baker <len.baker@xxxxxxx>
> Signed-off-by: Robert Richter <rrichter@xxxxxxx>
> ---
> drivers/edac/edac_mc.c | 42 ++++++++++++++++++------------------------
> 1 file changed, 18 insertions(+), 24 deletions(-)

Applied, thanks.

--
Regards/Gruss,
Boris.

https://people.kernel.org/tglx/notes-about-netiquette