Skip to content

Commit 5a5c51c

Browse files
authored
Limit length of read operation in ImageFont._load_pilfont_data() (#9181)
2 parents 8324b49 + caacd38 commit 5a5c51c

3 files changed

Lines changed: 20 additions & 7 deletions

File tree

Tests/test_imagefont.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -493,6 +493,11 @@ def test_stroke_mask() -> None:
493493
assert mask.getpixel((42, 5)) == 255
494494

495495

496+
def test_load_invalid_file() -> None:
497+
with pytest.raises(SyntaxError, match="Not a PILfont file"):
498+
ImageFont.load("Tests/images/1_trns.png")
499+
500+
496501
def test_load_when_image_not_found() -> None:
497502
with tempfile.NamedTemporaryFile(delete=False) as tmp:
498503
pass

Tests/test_imagefontpil.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,14 @@ def test_default_font(font: ImageFont.ImageFont) -> None:
3030
assert_image_equal_tofile(im, "Tests/images/default_font.png")
3131

3232

33+
def test_invalid_mode() -> None:
34+
font = ImageFont.ImageFont()
35+
fp = BytesIO()
36+
with Image.open("Tests/images/hopper.png") as im:
37+
with pytest.raises(TypeError, match="invalid font image mode"):
38+
font._load_pilfont_data(fp, im)
39+
40+
3341
def test_without_freetype() -> None:
3442
original_core = ImageFont.core
3543
if features.check_module("freetype2"):

src/PIL/ImageFont.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -125,11 +125,16 @@ def _load_pilfont(self, filename: str) -> None:
125125
image.close()
126126

127127
def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
128+
# check image
129+
if image.mode not in ("1", "L"):
130+
msg = "invalid font image mode"
131+
raise TypeError(msg)
132+
128133
# read PILfont header
129-
if file.readline() != b"PILfont\n":
134+
if file.read(8) != b"PILfont\n":
130135
msg = "Not a PILfont file"
131136
raise SyntaxError(msg)
132-
file.readline().split(b";")
137+
file.readline()
133138
self.info = [] # FIXME: should be a dictionary
134139
while True:
135140
s = file.readline()
@@ -140,11 +145,6 @@ def _load_pilfont_data(self, file: IO[bytes], image: Image.Image) -> None:
140145
# read PILfont metrics
141146
data = file.read(256 * 20)
142147

143-
# check image
144-
if image.mode not in ("1", "L"):
145-
msg = "invalid font image mode"
146-
raise TypeError(msg)
147-
148148
image.load()
149149

150150
self.font = Image.core.font(image.im, data)

0 commit comments

Comments
 (0)