[PATCH 14/32] af_unix: Use mem_to_flex_dup() with struct unix_address

Kees Cook keescook at chromium.org
Wed May 4 01:44:23 UTC 2022


As part of the work to perform bounds checking on all memcpy() uses,
replace the open-coded a deserialization of bytes out of memory into a
trailing flexible array by using a flex_array.h helper to perform the
allocation, bounds checking, and copying.

Cc: "David S. Miller" <davem at davemloft.net>
Cc: Eric Dumazet <edumazet at google.com>
Cc: Jakub Kicinski <kuba at kernel.org>
Cc: Paolo Abeni <pabeni at redhat.com>
Cc: Kuniyuki Iwashima <kuniyu at amazon.co.jp>
Cc: Alexei Starovoitov <ast at kernel.org>
Cc: Cong Wang <cong.wang at bytedance.com>
Cc: Al Viro <viro at zeniv.linux.org.uk>
Cc: netdev at vger.kernel.org
Signed-off-by: Kees Cook <keescook at chromium.org>
---
 include/net/af_unix.h | 14 ++++++++++++--
 net/unix/af_unix.c    |  7 ++-----
 2 files changed, 14 insertions(+), 7 deletions(-)

diff --git a/include/net/af_unix.h b/include/net/af_unix.h
index a7ef624ed726..422535b71295 100644
--- a/include/net/af_unix.h
+++ b/include/net/af_unix.h
@@ -25,8 +25,18 @@ extern struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
 
 struct unix_address {
 	refcount_t	refcnt;
-	int		len;
-	struct sockaddr_un name[];
+	DECLARE_FLEX_ARRAY_ELEMENTS_COUNT(int, len);
+	union {
+		DECLARE_FLEX_ARRAY(struct sockaddr_un, name);
+		/*
+		 * While a struct is used to access the flexible
+		 * array, it may only be partially populated, and
+		 * "len" above is actually tracking bytes, not a
+		 * count of struct sockaddr_un elements, so also
+		 * include a byte-size flexible array.
+		 */
+		DECLARE_FLEX_ARRAY_ELEMENTS(u8, bytes);
+	};
 };
 
 struct unix_skb_parms {
diff --git a/net/unix/af_unix.c b/net/unix/af_unix.c
index e1dd9e9c8452..8410cbc82ded 100644
--- a/net/unix/af_unix.c
+++ b/net/unix/af_unix.c
@@ -244,15 +244,12 @@ EXPORT_SYMBOL_GPL(unix_peer_get);
 static struct unix_address *unix_create_addr(struct sockaddr_un *sunaddr,
 					     int addr_len)
 {
-	struct unix_address *addr;
+	struct unix_address *addr = NULL;
 
-	addr = kmalloc(sizeof(*addr) + addr_len, GFP_KERNEL);
-	if (!addr)
+	if (mem_to_flex_dup(&addr, sunaddr, addr_len, GFP_KERNEL))
 		return NULL;
 
 	refcount_set(&addr->refcnt, 1);
-	addr->len = addr_len;
-	memcpy(addr->name, sunaddr, addr_len);
 
 	return addr;
 }
-- 
2.32.0



More information about the Linux-security-module-archive mailing list