[PATCH] getty: fix potential buffer overflow in parse_speeds()

Anton Moryakov via busybox <[email protected]> Tue, 26 May 2026 11:38:23 +0300
Newsgroups gmane.linux.busybox
Message-ID <[email protected]>
Static analyzer discovered an array index out-of-bounds issue in
parse_speeds() function.

The problem occurred when parsing exactly MAX_SPEED (10) baud rates:
- Index was incremented to 10 (becoming equal to MAX_SPEED)
- Check `if (G.numspeed > MAX_SPEED)` evaluated to false (10 > 10)
- Next iteration attempted to write to speeds[10], exceeding array bounds

Fix:
- Move bounds check BEFORE array access
- Change condition from `>` to `>=` for clarity
- Use bb_simple_error_msg_and_die() for error message

Now when G.numspeed reaches MAX_SPEED, the function terminates
gracefully instead of overflowing the buffer.

Signed-off-by: Anton Moryakov <[email protected]>
---
 loginutils/getty.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/loginutils/getty.c b/loginutils/getty.c
index 232fa2b84..190088ae3 100644
--- a/loginutils/getty.c
+++ b/loginutils/getty.c
@@ -162,13 +162,13 @@ static void parse_speeds(char *arg)
 	/* NB: at least one iteration is always done */
 	debug("entered parse_speeds\n");
 	while ((cp = strsep(&arg, ",")) != NULL) {
+		if (G.numspeed >= MAX_SPEED)
+			bb_simple_error_msg_and_die("too many alternate speeds");
 		G.speeds[G.numspeed] = bcode(cp);
 		if (G.speeds[G.numspeed] < 0)
 			bb_error_msg_and_die("bad speed: %s", cp);
 		/* note: arg "0" turns into speed B0 */
 		G.numspeed++;
-		if (G.numspeed > MAX_SPEED)
-			bb_simple_error_msg_and_die("too many alternate speeds");
 	}
 	debug("exiting parse_speeds\n");
 }
-- 
2.39.2