Skip to content

Commit 8f65ac0

Browse files
Isaac J. Manjarresakpm00
authored andcommitted
mm/memfd: use strncpy_from_user() to read memfd name
The existing logic uses strnlen_user() to calculate the length of the memfd name from userspace and then copies the string into a buffer using copy_from_user(). This is error-prone, as the string length could have changed between the time when it was calculated and when the string was copied. The existing logic handles this by ensuring that the last byte in the buffer is the terminating zero. This handling is contrived and can better be handled by using strncpy_from_user(), which gets the length of the string and copies it in one shot. Therefore, simplify the logic for copying the memfd name by using strncpy_from_user(). No functional change. Link: https://lkml.kernel.org/r/[email protected] Signed-off-by: Isaac J. Manjarres <[email protected]> Reviewed-by: Alice Ryhl <[email protected]> Reviewed-by: Lorenzo Stoakes <[email protected]> Cc: John Stultz <[email protected]> Cc: Kalesh Singh <[email protected]> Cc: Suren Baghdasaryan <[email protected]> Signed-off-by: Andrew Morton <[email protected]>
1 parent f5dbcd9 commit 8f65ac0

File tree

1 file changed

+6
-14
lines changed

1 file changed

+6
-14
lines changed

mm/memfd.c

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -396,26 +396,18 @@ static char *alloc_name(const char __user *uname)
396396
char *name;
397397
long len;
398398

399-
/* length includes terminating zero */
400-
len = strnlen_user(uname, MFD_NAME_MAX_LEN + 1);
401-
if (len <= 0)
402-
return ERR_PTR(-EFAULT);
403-
if (len > MFD_NAME_MAX_LEN + 1)
404-
return ERR_PTR(-EINVAL);
405-
406-
name = kmalloc(len + MFD_NAME_PREFIX_LEN, GFP_KERNEL);
399+
name = kmalloc(NAME_MAX + 1, GFP_KERNEL);
407400
if (!name)
408401
return ERR_PTR(-ENOMEM);
409402

410403
strcpy(name, MFD_NAME_PREFIX);
411-
if (copy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, len)) {
404+
/* returned length does not include terminating zero */
405+
len = strncpy_from_user(&name[MFD_NAME_PREFIX_LEN], uname, MFD_NAME_MAX_LEN + 1);
406+
if (len < 0) {
412407
error = -EFAULT;
413408
goto err_name;
414-
}
415-
416-
/* terminating-zero may have changed after strnlen_user() returned */
417-
if (name[len + MFD_NAME_PREFIX_LEN - 1]) {
418-
error = -EFAULT;
409+
} else if (len > MFD_NAME_MAX_LEN) {
410+
error = -EINVAL;
419411
goto err_name;
420412
}
421413

0 commit comments

Comments
 (0)