Re: [PATCH] net: cpmac: replace deprecated strncpy with strscpy

From: Andrew Lunn
Date: Sat Oct 14 2023 - 12:15:18 EST


On Thu, Oct 12, 2023 at 08:53:30PM +0000, Justin Stitt wrote:
> strncpy() is deprecated for use on NUL-terminated destination strings
> [1] and as such we should prefer more robust and less ambiguous string
> interfaces.
>
> We expect mdio_bus_id to be NUL-terminated based on its use with
> snprint():
> | snprintf(priv->phy_name, MII_BUS_ID_SIZE, PHY_ID_FMT,
> | mdio_bus_id, phy_id);
>
> Moreover, as this is the only use of mdio_bus_id, we can see that
> NUL-padding is not required.
>
> Considering the above, a suitable replacement is `strscpy` [2] due to
> the fact that it guarantees NUL-termination on the destination buffer
> without unnecessarily NUL-padding.
>
> Note that for the replacement involving cpmac_mii->id, the source
> buffer's length is equal to MII_BUS_ID_SIZE which could result in a
> buffer overread. However, there is no buffer overread since "cpmac-1"
> (the string copied into cpmac_mii->id) is smaller than MII_BUS_ID_SIZE
> thus meaning the previous usage of strncpy() here did _not_ have any
> overread bugs. Nonetheless, let's still favor strscpy() over strncpy().
>
> Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings [1]
> Link: https://manpages.debian.org/testing/linux-manual-4.8/strscpy.9.en.html [2]
> Link: https://github.com/KSPP/linux/issues/90
> Cc: linux-hardening@xxxxxxxxxxxxxxx
> Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>

Reviewed-by: Andrew Lunn <andrew@xxxxxxx>

Andrew