SDL_image: Fix heap-buffer-overflow WRITE in LBM palette (CWE-122) (cbd2e)

From cbd2e4c140fdcc1daa5deb468e307d00909da535 Mon Sep 17 00:00:00 2001
From: Ozkan Sezer <[EMAIL REDACTED]>
Date: Mon, 6 Apr 2026 19:29:38 +0200
Subject: [PATCH] Fix heap-buffer-overflow WRITE in LBM palette (CWE-122)

When nbplanes > 8 without HAM flag, nbrcolorsfinal exceeds 256,
causing writes past the palette buffer. Reject nbplanes > 8 for
paletted images.

(manual backport of commit 4f3700485ef7ecef0b93dd15b0ae9268edc5d0fb)
---
 IMG_lbm.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/IMG_lbm.c b/IMG_lbm.c
index 154adc36e..c64e9481e 100644
--- a/IMG_lbm.c
+++ b/IMG_lbm.c
@@ -236,6 +236,13 @@ SDL_Surface *IMG_LoadLBM_RW( SDL_RWops *src )
 
 	nbplanes = bmhd.planes;
 
+	/* Sanity check: nbplanes must not exceed 8 for paletted images.
+	   Higher values cause 1<<nbplanes to exceed the 256-entry palette. */
+	if ( !pbm && nbplanes > 8 && nbplanes != 24 && flagHAM == 0 ) {
+		IMG_SetError("LBM: invalid number of bitplanes (%u)", nbplanes);
+		goto done;
+	}
+
 	if ( pbm )                         /* File format : 'Packed Bitmap' */
 	{
 		bytesperline *= 8;