Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

HID: uhid: replace deprecated strncpy with strscpy

`strncpy` is deprecated for use on NUL-terminated destination strings
[1] and as such we should prefer more robust and less ambiguous string
interfaces.

A suitable replacement is `strscpy` [2] due to the fact that it
guarantees NUL-termination on the destination buffer without
unnecessarily NUL-padding.

Furthermore, let's make sure `hid->xyz` and `ev->u.create2.xyz` are the
same size at compile time to prevent silent truncation.

With these changes, it is abundantly clear what the intent and behavior
of the code is -- We are getting a string to string copy with
NUL-termination and no truncation.

Link: https://www.kernel.org/doc/html/latest/process/deprecated.html#strncpy-on-nul-terminated-strings [1]
Link: https://manpages.debian.org/testing/linux-manual-4.8/strscpy.9.en.html [2]
Link: https://github.com/KSPP/linux/issues/90
Cc: linux-hardening@vger.kernel.org
Cc: Kees Cook <keescook@chromium.org>
Signed-off-by: Justin Stitt <justinstitt@google.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
Link: https://lore.kernel.org/r/20231003-strncpy-drivers-hid-uhid-c-v2-1-6a501402581e@google.com
Signed-off-by: Kees Cook <keescook@chromium.org>

authored by

Justin Stitt and committed by
Kees Cook
d4011f68 40b2519d

+7 -8
+7 -8
drivers/hid/uhid.c
··· 490 490 const struct uhid_event *ev) 491 491 { 492 492 struct hid_device *hid; 493 - size_t rd_size, len; 493 + size_t rd_size; 494 494 void *rd_data; 495 495 int ret; 496 496 ··· 514 514 goto err_free; 515 515 } 516 516 517 - /* @hid is zero-initialized, strncpy() is correct, strlcpy() not */ 518 - len = min(sizeof(hid->name), sizeof(ev->u.create2.name)) - 1; 519 - strncpy(hid->name, ev->u.create2.name, len); 520 - len = min(sizeof(hid->phys), sizeof(ev->u.create2.phys)) - 1; 521 - strncpy(hid->phys, ev->u.create2.phys, len); 522 - len = min(sizeof(hid->uniq), sizeof(ev->u.create2.uniq)) - 1; 523 - strncpy(hid->uniq, ev->u.create2.uniq, len); 517 + BUILD_BUG_ON(sizeof(hid->name) != sizeof(ev->u.create2.name)); 518 + strscpy(hid->name, ev->u.create2.name, sizeof(hid->name)); 519 + BUILD_BUG_ON(sizeof(hid->phys) != sizeof(ev->u.create2.phys)); 520 + strscpy(hid->phys, ev->u.create2.phys, sizeof(hid->phys)); 521 + BUILD_BUG_ON(sizeof(hid->uniq) != sizeof(ev->u.create2.uniq)); 522 + strscpy(hid->uniq, ev->u.create2.uniq, sizeof(hid->uniq)); 524 523 525 524 hid->ll_driver = &uhid_hid_driver; 526 525 hid->bus = ev->u.create2.bus;