From 1feabd2552a4789126be4fe3d46f19af26c4da93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjamin=20Cab=C3=A9?= Date: Wed, 21 Jan 2026 11:51:40 +0100 Subject: [PATCH] shell: fix potential buffer overflow in shell_help_is_structured() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Signed-off-by: Benjamin Cabé --- include/zephyr/shell/shell.h | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/include/zephyr/shell/shell.h b/include/zephyr/shell/shell.h index 7274b650180..a451bda9df2 100644 --- a/include/zephyr/shell/shell.h +++ b/include/zephyr/shell/shell.h @@ -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__)