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

Configure Feed

Select the types of activity you want to include in your feed.

string: Adjust strtomem() logic to allow for smaller sources

Arnd noticed we have a case where a shorter source string is being copied
into a destination byte array, but this results in a strnlen() call that
exceeds the size of the source. This is seen with -Wstringop-overread:

In file included from ../include/linux/uuid.h:11,
from ../include/linux/mod_devicetable.h:14,
from ../include/linux/cpufeature.h:12,
from ../arch/x86/coco/tdx/tdx.c:7:
../arch/x86/coco/tdx/tdx.c: In function 'tdx_panic.constprop':
../include/linux/string.h:284:9: error: 'strnlen' specified bound 64 exceeds source size 60 [-Werror=stringop-overread]
284 | memcpy_and_pad(dest, _dest_len, src, strnlen(src, _dest_len), pad); \
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../arch/x86/coco/tdx/tdx.c:124:9: note: in expansion of macro 'strtomem_pad'
124 | strtomem_pad(message.str, msg, '\0');
| ^~~~~~~~~~~~

Use the smaller of the two buffer sizes when calling strnlen(). When
src length is unknown (SIZE_MAX), it is adjusted to use dest length,
which is what the original code did.

Reported-by: Arnd Bergmann <arnd@arndb.de>
Fixes: dfbafa70bde2 ("string: Introduce strtomem() and strtomem_pad()")
Tested-by: Arnd Bergmann <arnd@arndb.de>
Cc: Andy Shevchenko <andy@kernel.org>
Cc: linux-hardening@vger.kernel.org
Signed-off-by: Kees Cook <keescook@chromium.org>

+5 -2
+5 -2
include/linux/string.h
··· 277 277 */ 278 278 #define strtomem_pad(dest, src, pad) do { \ 279 279 const size_t _dest_len = __builtin_object_size(dest, 1); \ 280 + const size_t _src_len = __builtin_object_size(src, 1); \ 280 281 \ 281 282 BUILD_BUG_ON(!__builtin_constant_p(_dest_len) || \ 282 283 _dest_len == (size_t)-1); \ 283 - memcpy_and_pad(dest, _dest_len, src, strnlen(src, _dest_len), pad); \ 284 + memcpy_and_pad(dest, _dest_len, src, \ 285 + strnlen(src, min(_src_len, _dest_len)), pad); \ 284 286 } while (0) 285 287 286 288 /** ··· 300 298 */ 301 299 #define strtomem(dest, src) do { \ 302 300 const size_t _dest_len = __builtin_object_size(dest, 1); \ 301 + const size_t _src_len = __builtin_object_size(src, 1); \ 303 302 \ 304 303 BUILD_BUG_ON(!__builtin_constant_p(_dest_len) || \ 305 304 _dest_len == (size_t)-1); \ 306 - memcpy(dest, src, min(_dest_len, strnlen(src, _dest_len))); \ 305 + memcpy(dest, src, strnlen(src, min(_src_len, _dest_len))); \ 307 306 } while (0) 308 307 309 308 /**