net: Fix undefined behavior in netdev name allocation
authorGal Pressman <gal@nvidia.com>
Tue, 14 Nov 2023 07:56:18 +0000 (09:56 +0200)
committerDavid S. Miller <davem@davemloft.net>
Wed, 15 Nov 2023 11:05:08 +0000 (11:05 +0000)
Cited commit removed the strscpy() call and kept the snprintf() only.

It is common to use 'dev->name' as the format string before a netdev is
registered, this results in 'res' and 'name' pointers being equal.
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: 7ad17b04dc7b ("net: trust the bitmap in __dev_alloc_name()")
Cc: Jakub Kicinski <kuba@kernel.org>
Reviewed-by: Vlad Buslov <vladbu@nvidia.com>
Signed-off-by: Gal Pressman <gal@nvidia.com>
Reviewed-by: Jakub Kicinski <kuba@kernel.org>
Reviewed-by: Simon Horman <horms@kernel.org>
Reviewed-by: Jiri Pirko <jiri@nvidia.com>
Signed-off-by: David S. Miller <davem@davemloft.net>
net/core/dev.c

index 0d548431f3fadfd37af7c58664d3c6a706e8ff80..af53f6d838ce9e5ec73570d31ac39b9f36b1c5c5 100644 (file)
@@ -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;
 }