From 3ba8eb3b7e0cf6d02c0d62b315cc2db7afe969e8 Mon Sep 17 00:00:00 2001 From: Andrew Murray Date: Sat, 16 Mar 2024 12:29:21 +1100 Subject: [PATCH] Raise a ValueError for negative values when loading P1-P3 PPM images --- Tests/test_file_ppm.py | 12 +++++++++++- src/PIL/PpmImagePlugin.py | 3 +++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/Tests/test_file_ppm.py b/Tests/test_file_ppm.py index 6a0a5a445a7..1bfd0434e96 100644 --- a/Tests/test_file_ppm.py +++ b/Tests/test_file_ppm.py @@ -241,13 +241,23 @@ def test_plain_ppm_token_too_long(tmp_path: Path, data: bytes) -> None: im.load() +def test_plain_ppm_value_negative(tmp_path: Path) -> None: + path = str(tmp_path / "temp.ppm") + with open(path, "wb") as f: + f.write(b"P3\n128 128\n255\n-1") + + with Image.open(path) as im: + with pytest.raises(ValueError, match="Channel value is negative"): + im.load() + + def test_plain_ppm_value_too_large(tmp_path: Path) -> None: path = str(tmp_path / "temp.ppm") with open(path, "wb") as f: f.write(b"P3\n128 128\n255\n256") with Image.open(path) as im: - with pytest.raises(ValueError): + with pytest.raises(ValueError, match="Channel value too large"): im.load() diff --git a/src/PIL/PpmImagePlugin.py b/src/PIL/PpmImagePlugin.py index 6ac7a9bbc79..bca3018c36f 100644 --- a/src/PIL/PpmImagePlugin.py +++ b/src/PIL/PpmImagePlugin.py @@ -270,6 +270,9 @@ def _decode_blocks(self, maxval: int) -> bytearray: msg = b"Token too long found in data: %s" % token[: max_len + 1] raise ValueError(msg) value = int(token) + if value < 0: + msg_str = f"Channel value is negative: {value}" + raise ValueError(msg_str) if value > maxval: msg_str = f"Channel value too large for this mode: {value}" raise ValueError(msg_str)