diff mbox series

[27/32] KEYS: Use mem_to_flex_dup() with struct user_key_payload

Message ID 20220504014440.3697851-28-keescook@chromium.org (mailing list archive)
State New
Headers show
Series Introduce flexible array struct memcpy() helpers | expand

Commit Message

Kees Cook May 4, 2022, 1:44 a.m. UTC
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 Howells <dhowells@redhat.com>
Cc: Jarkko Sakkinen <jarkko@kernel.org>
Cc: James Morris <jmorris@namei.org>
Cc: "Serge E. Hallyn" <serge@hallyn.com>
Cc: keyrings@vger.kernel.org
Cc: linux-security-module@vger.kernel.org
Signed-off-by: Kees Cook <keescook@chromium.org>
---
 include/keys/user-type.h     | 4 ++--
 security/keys/user_defined.c | 7 ++-----
 2 files changed, 4 insertions(+), 7 deletions(-)
diff mbox series

Patch

diff --git a/include/keys/user-type.h b/include/keys/user-type.h
index 386c31432789..4e67ff902a32 100644
--- a/include/keys/user-type.h
+++ b/include/keys/user-type.h
@@ -26,8 +26,8 @@ 
  */
 struct user_key_payload {
 	struct rcu_head	rcu;		/* RCU destructor */
-	unsigned short	datalen;	/* length of this data */
-	char		data[] __aligned(__alignof__(u64)); /* actual data */
+	DECLARE_FLEX_ARRAY_ELEMENTS_COUNT(unsigned short, datalen);
+	DECLARE_FLEX_ARRAY_ELEMENTS(char, data) __aligned(__alignof__(u64));
 };
 
 extern struct key_type key_type_user;
diff --git a/security/keys/user_defined.c b/security/keys/user_defined.c
index 749e2a4dcb13..2fb84894cdaa 100644
--- a/security/keys/user_defined.c
+++ b/security/keys/user_defined.c
@@ -58,21 +58,18 @@  EXPORT_SYMBOL_GPL(key_type_logon);
  */
 int user_preparse(struct key_preparsed_payload *prep)
 {
-	struct user_key_payload *upayload;
+	struct user_key_payload *upayload = NULL;
 	size_t datalen = prep->datalen;
 
 	if (datalen <= 0 || datalen > 32767 || !prep->data)
 		return -EINVAL;
 
-	upayload = kmalloc(sizeof(*upayload) + datalen, GFP_KERNEL);
-	if (!upayload)
+	if (mem_to_flex_dup(&upayload, prep->data, datalen, GFP_KERNEL))
 		return -ENOMEM;
 
 	/* attach the data */
 	prep->quotalen = datalen;
 	prep->payload.data[0] = upayload;
-	upayload->datalen = datalen;
-	memcpy(upayload->data, prep->data, datalen);
 	return 0;
 }
 EXPORT_SYMBOL_GPL(user_preparse);