Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

fix(bmp): reject invalid colormap sizes instead of clamping to 256

chantology67ed8a3ac824
diff --git a/toonz/sources/common/tiio/tiio_bmp.cpp b/toonz/sources/common/tiio/tiio_bmp.cpp
index 24fb4d376..251c1ba76 100644
--- a/toonz/sources/common/tiio/tiio_bmp.cpp
+++ b/toonz/sources/common/tiio/tiio_bmp.cpp
@@ -9,6 +9,7 @@
#include "tpixel.h"
#include "tpixelgr.h"
#include "tproperty.h"
+#include "timage_io.h"
//#include "tconvert.h"
#include <stdio.h>
@@ -229,26 +230,22 @@ else
hd->biPad = 0;
*/
- // load up colormap, if any
- if (m_header.biBitCount < 16) {
- int cmaplen =
- (m_header.biClrUsed) ? m_header.biClrUsed : 1 << m_header.biBitCount;
- // Proposed by Claude Opus 4.8 — REQUIRES MAINTAINER CODE REVIEW.
- // Security fix (heap buffer overflow): cmaplen is derived from unvalidated
- // header fields — biClrUsed is read straight from the file, and when it is
- // zero the fallback 1<<biBitCount can be as large as 1<<15 (the guard above
- // is only biBitCount < 16). The colormap is a fixed 256-entry buffer
- // (new TPixel[256]) and the loop below writes cmaplen entries into it, so a
- // crafted BMP overflows the heap. The previous sole guard, assert(cmaplen
- // <= 256), is compiled out in release builds (NDEBUG). Clamp to the buffer
- // capacity; valid indexed BMPs never exceed 256 palette entries, so this
- // does not change behaviour for well-formed input. Malformed files may
- // decode to a garbled image, but no longer corrupt memory.
- if (cmaplen < 0 || cmaplen > 256) cmaplen = 256;
- assert(cmaplen <= 256);
+ // load up colormap, if any. A palette holds at most 2^biBitCount entries
+ // (2 / 16 / 256 for 1 / 4 / 8-bit); reject a file claiming more so a bogus
+ // biClrUsed cannot overflow the fixed buffer or leave the stream past the
+ // real palette.
+ if (m_header.biBitCount == 1 || m_header.biBitCount == 4 ||
+ m_header.biBitCount == 8) {
+ const UINT maxColorCount = 1u << m_header.biBitCount;
+ const UINT cmaplen =
+ m_header.biClrUsed ? m_header.biClrUsed : maxColorCount;
+
+ if (cmaplen > maxColorCount)
+ throw TImageException(TFilePath(), "Invalid BMP color map size");
+
m_cmap.reset(new TPixel[256]);
TPixel32 *pix = m_cmap.get();
- for (int i = 0; i < cmaplen; i++) {
+ for (UINT i = 0; i < cmaplen; ++i) {
pix->b = getc(m_chan);
pix->g = getc(m_chan);
pix->r = getc(m_chan);