Skip to content

Commit 701d404

Browse files
authored
Raise error if declared JPEG2000 marker length is too small (#9666)
1 parent 09cfbab commit 701d404

2 files changed

Lines changed: 19 additions & 0 deletions

File tree

Tests/test_file_jpeg2k.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import os
44
import re
5+
import struct
56
from collections.abc import Generator
67
from io import BytesIO
78
from pathlib import Path
@@ -547,6 +548,18 @@ def test_plt_marker(card: ImageFile.ImageFile) -> None:
547548
out.seek(length - 2, os.SEEK_CUR)
548549

549550

551+
def test_marker_length() -> None:
552+
magic = b"\xff\x4f\xff\x51"
553+
b = BytesIO(magic + b"\x00\x00")
554+
with pytest.raises(ValueError, match="SIZ marker length must be at least 38"):
555+
Image.open(b)
556+
557+
siz_marker = _binary.o16be(38) + b"\x00" * 34 + struct.pack(">H", 2)
558+
b = BytesIO(magic + siz_marker + b"\x00" * 4)
559+
with pytest.raises(ValueError, match="Marker length too small"):
560+
Image.open(b)
561+
562+
550563
def test_9bit() -> None:
551564
with Image.open("Tests/images/9bit.j2k") as im:
552565
assert im.mode == "I;16"

src/PIL/Jpeg2KImagePlugin.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ def _parse_codestream(fp: IO[bytes]) -> tuple[tuple[int, int], str]:
108108

109109
hdr = fp.read(2)
110110
lsiz = _binary.i16be(hdr)
111+
if lsiz < 38:
112+
msg = "SIZ marker length must be at least 38"
113+
raise ValueError(msg)
111114
siz = hdr + fp.read(lsiz - 2)
112115
lsiz, rsiz, xsiz, ysiz, xosiz, yosiz, _, _, _, _, csiz = struct.unpack_from(
113116
">HHIIIIIIIIH", siz
@@ -328,6 +331,9 @@ def _parse_comment(self) -> None:
328331
break
329332
hdr = self.fp.read(2)
330333
length = _binary.i16be(hdr)
334+
if length < 2:
335+
msg = "Marker length too small"
336+
raise ValueError(msg)
331337
if typ == 0x64:
332338
# Comment
333339
self.info["comment"] = self.fp.read(length - 2)[2:]

0 commit comments

Comments
 (0)