diff --git a/Tests/test_file_jpeg2k.py b/Tests/test_file_jpeg2k.py index ba9896c1dff..0f045fba1ba 100644 --- a/Tests/test_file_jpeg2k.py +++ b/Tests/test_file_jpeg2k.py @@ -230,16 +230,14 @@ def test_header_errors() -> None: def test_oversized_box_length() -> None: - # A box declaring a 64-bit length that ends beyond the maximum seekable - # position must be rejected instead of raising OverflowError from seek() + # Do not raise an OverflowError() when seeking to the end of a box data = ( b"\x00\x00\x00\x0cjP \x0d\x0a\x87\x0a" # JP2 signature box - + struct.pack(">I4s", 1, b"\x00\x00\x00\x00") # box with 64-bit length - + struct.pack(">Q", 0xFFFFFFFFFF000004) # length beyond the seek range + + struct.pack(">I4s", 1, b"") # box with 64-bit length + + struct.pack(">Q", 16 + 2**63) # length beyond the seek range ) - with pytest.raises(UnidentifiedImageError): - with Image.open(BytesIO(data)): - pass + with pytest.raises(SyntaxError, match="Box length too large"): + Jpeg2KImagePlugin.Jpeg2KImageFile(BytesIO(data)) def test_layers_type(card: ImageFile.ImageFile, tmp_path: Path) -> None: diff --git a/src/PIL/Jpeg2KImagePlugin.py b/src/PIL/Jpeg2KImagePlugin.py index d2d30567de3..e2f70d11fdd 100644 --- a/src/PIL/Jpeg2KImagePlugin.py +++ b/src/PIL/Jpeg2KImagePlugin.py @@ -83,6 +83,9 @@ def has_next_box(self) -> bool: def next_box_type(self) -> bytes: # Skip the rest of the box if it has not been read if self.remaining_in_box > 0: + if self.remaining_in_box >= 2**63: + msg = "Box length too large" + raise SyntaxError(msg) self.fp.seek(self.remaining_in_box, os.SEEK_CUR) self.remaining_in_box = -1 @@ -98,11 +101,6 @@ def next_box_type(self) -> bytes: msg = "Invalid header length" raise SyntaxError(msg) - # Reject a box whose contents end beyond the maximum seekable position - if self.fp.tell() + lbox - hlen >= 2**63: - msg = "Invalid box length" - raise SyntaxError(msg) - self.remaining_in_box = lbox - hlen return tbox