[PATCH] printk: fix out-of-bounds access in try_enable_preferred_console()

From: Naveen Kumar Chaudhary

Date: Sat May 30 2026 - 00:48:37 EST


When all MAX_CMDLINECONSOLES (8) slots in console_cmdline[] are occupied
and none match the newly registered console, the for loop exits with
i == MAX_CMDLINECONSOLES and c pointing past the end of the array. The
subsequent access to c->user_specified is then an out-of-bounds read.

This can occur when a self-enabling console (one with CON_ENABLED already
set), such as netconsole or pstore, calls register_console() on a system
where the console_cmdline[] array has been filled by a combination of
command-line console= parameters, ACPI SPCR, device tree stdout-path,
and/or arch-specific add_preferred_console() calls.

Add a bounds check to ensure c is only dereferenced when the loop exited
due to finding an empty slot (i.e., c still points within the array).
Also add parentheses around the bitwise-AND to silence compiler warnings
about its use in a boolean context.

Signed-off-by: Naveen Kumar Chaudhary <naveen.osdev@xxxxxxxxx>
---
kernel/printk/printk.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/kernel/printk/printk.c b/kernel/printk/printk.c
index 0323149548f6..00282ca467fd 100644
--- a/kernel/printk/printk.c
+++ b/kernel/printk/printk.c
@@ -3938,7 +3938,8 @@ static int try_enable_preferred_console(struct console *newcon,
* without matching. Accept the pre-enabled consoles only when match()
* and setup() had a chance to be called.
*/
- if (newcon->flags & CON_ENABLED && c->user_specified == user_specified)
+ if (i < MAX_CMDLINECONSOLES && (newcon->flags & CON_ENABLED) &&
+ c->user_specified == user_specified)
return 0;

return -ENOENT;
--
2.43.0