Skip to content

Commit 8bbb9ec

Browse files
Raise ValueError for truncated gAMA and cHRM PNG chunks (#9880)
1 parent df63ef4 commit 8bbb9ec

2 files changed

Lines changed: 13 additions & 2 deletions

File tree

Tests/test_file_png.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,8 @@ def test_padded_idat(self, monkeypatch: pytest.MonkeyPatch) -> None:
700700
assert_image_equal_tofile(im, "Tests/images/bw_gradient.png")
701701

702702
@pytest.mark.parametrize(
703-
"cid", (b"IHDR", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT")
703+
"cid",
704+
(b"IHDR", b"gAMA", b"cHRM", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT"),
704705
)
705706
def test_truncated_chunks(
706707
self, cid: bytes, monkeypatch: pytest.MonkeyPatch

src/PIL/PngImagePlugin.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,11 @@ def chunk_gAMA(self, pos: int, length: int) -> bytes:
521521
# gamma setting
522522
assert self.fp is not None
523523
s = ImageFile._safe_read(self.fp, length)
524+
if length < 4:
525+
if ImageFile.LOAD_TRUNCATED_IMAGES:
526+
return s
527+
msg = "Truncated gAMA chunk"
528+
raise ValueError(msg)
524529
self.im_info["gamma"] = i32(s) / 100000.0
525530
return s
526531

@@ -530,7 +535,12 @@ def chunk_cHRM(self, pos: int, length: int) -> bytes:
530535

531536
assert self.fp is not None
532537
s = ImageFile._safe_read(self.fp, length)
533-
raw_vals = struct.unpack(f">{len(s) // 4}I", s)
538+
if length < 32:
539+
if ImageFile.LOAD_TRUNCATED_IMAGES:
540+
return s
541+
msg = "Truncated cHRM chunk"
542+
raise ValueError(msg)
543+
raw_vals = struct.unpack(">8I", s[:32])
534544
self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals)
535545
return s
536546

0 commit comments

Comments
 (0)