Skip to content

Commit 9ff51ff

Browse files
author
Your Name
committed
Fix integer overflow in quantize_pngquant() and replace sprintf
- Add overflow check for width * height before malloc() to prevent heap buffer overflow when the product exceeds UINT_MAX - Use size_t for total_pixels to ensure correct arithmetic on 64-bit - Replace sprintf with snprintf (consistent with CVE-2024-28219 fix) Security: CWE-190 (Integer Overflow) -> CWE-122 (Heap Buffer Overflow)
1 parent 3a44ba1 commit 9ff51ff

1 file changed

Lines changed: 13 additions & 5 deletions

File tree

src/libImaging/QuantPngQuant.c

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
*
99
*/
1010

11+
#include <stdint.h>
1112
#include <stdio.h>
1213
#include <stdlib.h>
1314
#include <string.h>
@@ -39,6 +40,13 @@ quantize_pngquant(
3940
*paletteLength = 0;
4041
*quantizedPixels = NULL;
4142

43+
/* Check for integer overflow in width * height to prevent
44+
* undersized allocations leading to heap buffer overflow. */
45+
if (height != 0 && (size_t)width > SIZE_MAX / (size_t)height) {
46+
goto err;
47+
}
48+
size_t total_pixels = (size_t)width * (size_t)height;
49+
4250
/* configure pngquant */
4351
attr = liq_attr_create();
4452
if (!attr) {
@@ -77,7 +85,7 @@ quantize_pngquant(
7785
}
7886

7987
/* write output pixels (pngquant uses char array) */
80-
charMatrix = malloc(width * height);
88+
charMatrix = malloc(total_pixels);
8189
if (!charMatrix) {
8290
goto err;
8391
}
@@ -86,18 +94,18 @@ quantize_pngquant(
8694
goto err;
8795
}
8896
for (y = 0; y < height; y++) {
89-
charMatrixRows[y] = &charMatrix[y * width];
97+
charMatrixRows[y] = &charMatrix[(size_t)y * width];
9098
}
9199
if (LIQ_OK != liq_write_remapped_image_rows(remap, image, charMatrixRows)) {
92100
goto err;
93101
}
94102

95103
/* transcribe output pixels (pillow uses uint32_t array) */
96-
*quantizedPixels = malloc(sizeof(uint32_t) * width * height);
104+
*quantizedPixels = malloc(sizeof(uint32_t) * total_pixels);
97105
if (!*quantizedPixels) {
98106
goto err;
99107
}
100-
for (i = 0; i < width * height; i++) {
108+
for (i = 0; i < total_pixels; i++) {
101109
(*quantizedPixels)[i] = charMatrix[i];
102110
}
103111

@@ -126,7 +134,7 @@ const char *
126134
ImagingImageQuantVersion(void) {
127135
static char version[20];
128136
int number = liq_version();
129-
sprintf(version, "%d.%d.%d", number / 10000, (number / 100) % 100, number % 100);
137+
snprintf(version, sizeof(version), "%d.%d.%d", number / 10000, (number / 100) % 100, number % 100);
130138
return version;
131139
}
132140

0 commit comments

Comments
 (0)