diff --git a/Tests/test_file_fpx.py b/Tests/test_file_fpx.py index 1887fce1be5..4f5cdd484d3 100644 --- a/Tests/test_file_fpx.py +++ b/Tests/test_file_fpx.py @@ -47,10 +47,31 @@ def test_invalid_file() -> None: def test_invalid_tile_size() -> None: with open("Tests/images/input_bw_one_band.fpx", "rb") as f: - data = f.read() - data = data[:4204] + b"\x00" * 8 + data[4212:] + data = bytearray(f.read()) + data[4204:4212] = b"\x00" * 8 + b = BytesIO(data) with pytest.raises(ValueError, match="Tile must be 64 pixels by 64 pixels"): - Image.open(BytesIO(data)) + Image.open(b) + + +def test_invalid_tile_header_entry_length() -> None: + with open("Tests/images/input_bw_one_band.fpx", "rb") as f: + data = bytearray(f.read()) + data[4220:4224] = b"\x01\x00\x00\x00" + b = BytesIO(data) + with pytest.raises( + ValueError, match="Tile header entry length must be at least 16" + ): + Image.open(b) + + +def test_decompression_bomb() -> None: + with open("Tests/images/input_bw_one_band.fpx", "rb") as f: + data = bytearray(f.read()) + data[3220:3224] = b"\x00\x00\x00\x40" + b = BytesIO(data) + with pytest.raises(Image.DecompressionBombError): + Image.open(b) def test_invalid_number_of_bands() -> None: diff --git a/src/PIL/FpxImagePlugin.py b/src/PIL/FpxImagePlugin.py index 6da46c17bee..43ca8e25ed2 100644 --- a/src/PIL/FpxImagePlugin.py +++ b/src/PIL/FpxImagePlugin.py @@ -87,6 +87,8 @@ def _open_index(self, index: int = 1) -> None: assert isinstance(prop[0x1000002], int) assert isinstance(prop[0x1000003], int) self._size = prop[0x1000002], prop[0x1000003] + # The size bounds the number of tile descriptors read in _open_subimage() + Image._decompression_bomb_check(self._size) size = max(self.size) i = 1 @@ -142,7 +144,7 @@ def _open_subimage(self, index: int = 1, subimage: int = 0) -> None: s = fp.read(36) size = i32(s, 4), i32(s, 8) - # tilecount = i32(s, 12) + tilecount = i32(s, 12) xtile, ytile = i32(s, 16), i32(s, 20) if xtile != 64 or ytile != 64: msg = "Tile must be 64 pixels by 64 pixels" @@ -151,14 +153,20 @@ def _open_subimage(self, index: int = 1, subimage: int = 0) -> None: # channels = i32(s, 24) offset = i32(s, 28) length = i32(s, 32) + if length < 16: + # 16 bytes are required + # for the tile offset, tile size, compression type and compression subtype + msg = "Tile header entry length must be at least 16" + raise ValueError(msg) if size != self.size: msg = "subimage mismatch" raise OSError(msg) - # get tile descriptors + # get tile header entries fp.seek(28 + offset) - s = fp.read(i32(s, 12) * length) + xtiles, ytiles = (size[0] + xtile - 1) // xtile, (size[1] + ytile - 1) // ytile + s = fp.read(min(tilecount, xtiles * ytiles) * length) x = y = 0 xsize, ysize = size