diff --git a/Tests/test_file_png.py b/Tests/test_file_png.py index f4fe1de013d..37936cec58c 100644 --- a/Tests/test_file_png.py +++ b/Tests/test_file_png.py @@ -700,7 +700,8 @@ def test_padded_idat(self, monkeypatch: pytest.MonkeyPatch) -> None: assert_image_equal_tofile(im, "Tests/images/bw_gradient.png") @pytest.mark.parametrize( - "cid", (b"IHDR", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT") + "cid", + (b"IHDR", b"gAMA", b"cHRM", b"sRGB", b"pHYs", b"acTL", b"fcTL", b"fdAT"), ) def test_truncated_chunks( self, cid: bytes, monkeypatch: pytest.MonkeyPatch diff --git a/src/PIL/PngImagePlugin.py b/src/PIL/PngImagePlugin.py index 10ae999a774..0571c648135 100644 --- a/src/PIL/PngImagePlugin.py +++ b/src/PIL/PngImagePlugin.py @@ -521,6 +521,11 @@ def chunk_gAMA(self, pos: int, length: int) -> bytes: # gamma setting assert self.fp is not None s = ImageFile._safe_read(self.fp, length) + if length < 4: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated gAMA chunk" + raise ValueError(msg) self.im_info["gamma"] = i32(s) / 100000.0 return s @@ -530,7 +535,12 @@ def chunk_cHRM(self, pos: int, length: int) -> bytes: assert self.fp is not None s = ImageFile._safe_read(self.fp, length) - raw_vals = struct.unpack(f">{len(s) // 4}I", s) + if length < 32: + if ImageFile.LOAD_TRUNCATED_IMAGES: + return s + msg = "Truncated cHRM chunk" + raise ValueError(msg) + raw_vals = struct.unpack(">8I", s[:32]) self.im_info["chromaticity"] = tuple(elt / 100000.0 for elt in raw_vals) return s