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

qed: replace uses of strncpy

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

This patch eliminates three uses of strncpy():

Firstly, `dest` is expected to be NUL-terminated which is evident by the
manual setting of a NUL-byte at size - 1. For this use specifically,
strscpy() is a viable replacement due to the fact that it guarantees
NUL-termination on the destination buffer.

The next two cases should simply be memcpy() as the size of the src
string is always 3 and the destination string just wants the first 3
bytes changed.

To be clear, there are no buffer overread bugs in the current code as
the sizes and offsets are carefully managed such that buffers are
NUL-terminated. However, with these changes, the code is now more robust
and less ambiguous (and hopefully easier to read).

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
Signed-off-by: Justin Stitt <justinstitt@google.com>
Reviewed-by: Kees Cook <keescook@chromium.org>
Link: https://lore.kernel.org/r/20231012-strncpy-drivers-net-ethernet-qlogic-qed-qed_debug-c-v2-1-16d2c0162b80@google.com
Signed-off-by: Jakub Kicinski <kuba@kernel.org>

authored by

Justin Stitt and committed by
Jakub Kicinski
a0252736 621735f5

+3 -4
+3 -4
drivers/net/ethernet/qlogic/qed/qed_debug.c
··· 3204 3204 BIT(big_ram->is_256b_bit_offset[dev_data->chip_id]) ? 256 3205 3205 : 128; 3206 3206 3207 - strncpy(type_name, big_ram->instance_name, BIG_RAM_NAME_LEN); 3208 - strncpy(mem_name, big_ram->instance_name, BIG_RAM_NAME_LEN); 3207 + memcpy(type_name, big_ram->instance_name, BIG_RAM_NAME_LEN); 3208 + memcpy(mem_name, big_ram->instance_name, BIG_RAM_NAME_LEN); 3209 3209 3210 3210 /* Dump memory header */ 3211 3211 offset += qed_grc_dump_mem_hdr(p_hwfn, ··· 6359 6359 { 6360 6360 const char *source_str = &((const char *)buf)[*offset]; 6361 6361 6362 - strncpy(dest, source_str, size); 6363 - dest[size - 1] = '\0'; 6362 + strscpy(dest, source_str, size); 6364 6363 *offset += size; 6365 6364 } 6366 6365