Re: [PATCH] net: dsa: lan9303: replace deprecated strncpy with memcpy

From: Kees Cook
Date: Thu Oct 05 2023 - 09:58:45 EST


On Wed, Oct 04, 2023 at 08:07:55PM -0700, Kees Cook wrote:
> On Thu, Oct 05, 2023 at 12:30:18AM +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
> > interfaces.
> >
> > Let's opt for memcpy as we are copying strings into slices of length
> > `ETH_GSTRING_LEN` within the `data` buffer. Other similar get_strings()
> > implementations [2] [3] use memcpy().
> >
> > Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings [1]
> > Link: https://elixir.bootlin.com/linux/v6.3/source/drivers/infiniband/ulp/opa_vnic/opa_vnic_ethtool.c#L167 [2]
> > Link: https://elixir.bootlin.com/linux/v6.3/source/drivers/infiniband/ulp/ipoib/ipoib_ethtool.c#L137 [3]
> > Link: https://github.com/KSPP/linux/issues/90
> > Cc: linux-hardening@xxxxxxxxxxxxxxx
> > Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>
> > ---
> > Note: build-tested only.
> > ---
> > drivers/net/dsa/lan9303-core.c | 4 ++--
> > 1 file changed, 2 insertions(+), 2 deletions(-)
> >
> > diff --git a/drivers/net/dsa/lan9303-core.c b/drivers/net/dsa/lan9303-core.c
> > index ee67adeb2cdb..665d69384b62 100644
> > --- a/drivers/net/dsa/lan9303-core.c
> > +++ b/drivers/net/dsa/lan9303-core.c
> > @@ -1013,8 +1013,8 @@ static void lan9303_get_strings(struct dsa_switch *ds, int port,
> > return;
> >
> > for (u = 0; u < ARRAY_SIZE(lan9303_mib); u++) {
> > - strncpy(data + u * ETH_GSTRING_LEN, lan9303_mib[u].name,
> > - ETH_GSTRING_LEN);
> > + memcpy(data + u * ETH_GSTRING_LEN, lan9303_mib[u].name,
> > + ETH_GSTRING_LEN);
>
> This won't work because lan9303_mib entries aren't ETH_GSTRING_LEN-long
> strings; they're string pointers:
>
> static const struct lan9303_mib_desc lan9303_mib[] = {
> { .offset = LAN9303_MAC_RX_BRDCST_CNT_0, .name = "RxBroad", },
>
> So this really does need a strcpy-family function.
>
> And, I think the vnic_gstrings_stats and ipoib_gstrings_stats examples
> are actually buggy -- they're copying junk into userspace...
>
> I am reminded of this patch, which correctly uses strscpy_pad():
> https://lore.kernel.org/lkml/20230718-net-dsa-strncpy-v1-1-e84664747713@xxxxxxxxxx/
>
> I think you want to do the same here, and use strscpy_pad(). And perhaps
> send some fixes for the other memcpy() users?

Meh, I think it's not worth fixing the memcpy() users of this. This
buggy pattern is very common, it seems:

$ git grep 'data.*ETH_GSTRING_LEN' | grep memcpy | wc -l
47

--
Kees Cook