Subject: Re: [PATCH net] net: Fix undefined behavior in netdev name allocation

From: Simon Horman <[email-masked]>
Date: Mon, 13 Nov 2023 09:53:33 +0000

On Mon, Nov 13, 2023 at 10:35:44AM +0200, Gal Pressman wrote:
> Cited commit removed the strscpy() call and kept the snprintf() only.
> 
> When allocating a netdev, 'res' and 'name' pointers are equal, but
> according to POSIX, if copying takes place between objects that overlap
> as a result of a call to sprintf() or snprintf(), the results are
> undefined.
> 
> Add back the strscpy() and use 'buf' as an intermediate buffer.
> 
> Fixes: 9a810468126c ("net: reduce indentation of __dev_alloc_name()")

Hi Gal,

perhaps my eyes are deceiving me, but I wonder if this fixes the following:

  7ad17b04dc7b ("net: trust the bitmap in __dev_alloc_name()")

> Cc: Jakub Kicinski <[email-masked]>
> Reviewed-by: Vlad Buslov <[email-masked]>
> Signed-off-by: Gal Pressman <[email-masked]>
> ---
>  net/core/dev.c | 4 +++-
>  1 file changed, 3 insertions(+), 1 deletion(-)
> 
> diff --git a/net/core/dev.c b/net/core/dev.c
> index 0d548431f3fa..af53f6d838ce 100644
> --- a/net/core/dev.c
> +++ b/net/core/dev.c
> @@ -1119,7 +1119,9 @@ static int __dev_alloc_name(struct net *net, const char *name, char *res)
>  	if (i == max_netdevices)
>  		return -ENFILE;
>  
> -	snprintf(res, IFNAMSIZ, name, i);
> +	/* 'res' and 'name' could overlap, use 'buf' as an intermediate buffer */
> +	strscpy(buf, name, IFNAMSIZ);
> +	snprintf(res, IFNAMSIZ, buf, i);
>  	return i;
>  }
>  
> -- 
> 2.40.1
> 
>