shell: fix potential buffer overflow in shell_help_is_structured()

The function was casting a char* help pointer to struct shell_cmd_help*
and reading its 4-byte magic field. When the help string was shorter
than 4 bytes, this caused a read past the end of the buffer.

The fix replaces the struct cast with a byte-by-byte comparison of the
magic number.

Fixes zephyrproject-rtos/zephyr#102598

Co-authored-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
This commit is contained in:
Benjamin Cabé
2026-01-21 11:51:40 +01:00
committed by Maureen Helm
parent cdfd692b76
commit 1feabd2552

View File

@@ -326,10 +326,16 @@ struct shell_cmd_help {
*/
static inline bool shell_help_is_structured(const char *help)
{
const struct shell_cmd_help *structured = (const struct shell_cmd_help *)help;
const uint32_t magic32 = SHELL_STRUCTURED_HELP_MAGIC;
const char *magic = (const char *)&magic32;
return structured != NULL && IS_PTR_ALIGNED(structured, struct shell_cmd_help) &&
structured->magic == SHELL_STRUCTURED_HELP_MAGIC;
/**
* Check if what help points to starts with the structured help magic word,
* but without assuming help is 32 bit aligned, or that if it is a string,
* that it is at least 4 bytes long.
*/
return help != NULL && (magic[0] == help[0]) && (magic[1] == help[1])
&& (magic[2] == help[2]) && (magic[3] == help[3]);
}
#if defined(CONFIG_SHELL_HELP) || defined(__DOXYGEN__)