[PATCH v3] arm64/sysreg: refactor deprecated strncpy

From: Justin Stitt
Date: Thu Aug 31 2023 - 18:56:05 EST


strncpy is deprecated [1] and should not be used if the src string is
not NUL-terminated.

When dealing with `cmdline` we are counting the number of characters
until a space then copying these over into `buf`. Let's not use any of
the str*() functions since the src string is not necessarily NUL-terminated.

Prefer `memcpy()` alongside a forced NUL-termination as it more
accurately describes what is going on within this function, i.e: copying
from non NUL-terminated buffer into a NUL-terminated buffer.

Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings [1]
Link: https://github.com/KSPP/linux/issues/90
Cc: linux-hardening@xxxxxxxxxxxxxxx
Suggested-by: Kees Cook <keescook@xxxxxxxxxxxx>
Signed-off-by: Justin Stitt <justinstitt@xxxxxxxxxx>
---
Here's a quick rundown on the history of this patch:
1) v1 (changes requested)
2) v2 (applied to arm64 (for-next/misc))
3) v2 reverted (https://lore.kernel.org/all/20230831162227.2307863-1-smostafa@xxxxxxxxxx/)
4) v3 (fixes problems with both v1 and v2)

Changes in v3:
- Fix faulty logic and use memcpy over strscpy (thanks Mostafa and Kees)
- Use '\0' instead of 0 to make it abundantly clear that `buf` is a NUL-terminated string
- Link to v2: https://lore.kernel.org/r/20230811-strncpy-arch-arm64-v2-1-ba84eabffadb@xxxxxxxxxx

Changes in v2:
- Utilize return value from strscpy and check for truncation (thanks Kees)
- Link to v1: https://lore.kernel.org/r/20230810-strncpy-arch-arm64-v1-1-f67f3685cd64@xxxxxxxxxx
---
arch/arm64/kernel/idreg-override.c | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/arch/arm64/kernel/idreg-override.c b/arch/arm64/kernel/idreg-override.c
index 2fe2491b692c..3addc09f8746 100644
--- a/arch/arm64/kernel/idreg-override.c
+++ b/arch/arm64/kernel/idreg-override.c
@@ -263,8 +263,8 @@ static __init void __parse_cmdline(const char *cmdline, bool parse_aliases)
return;

len = min(len, ARRAY_SIZE(buf) - 1);
- strncpy(buf, cmdline, len);
- buf[len] = 0;
+ memcpy(buf, cmdline, len);
+ buf[len] = '\0';

if (strcmp(buf, "--") == 0)
return;

---
base-commit: 706a741595047797872e669b3101429ab8d378ef
change-id: 20230810-strncpy-arch-arm64-1f3d328bd9b8

Best regards,
--
Justin Stitt <justinstitt@xxxxxxxxxx>