Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Restricted environment keys for ImageMath.eval() #7655

Merged
merged 3 commits into from Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions Tests/test_imagemath.py
Expand Up @@ -64,6 +64,16 @@ def test_prevent_exec(expression):
ImageMath.eval(expression)


def test_prevent_double_underscores():
with pytest.raises(ValueError):
ImageMath.eval("1", {"__": None})


def test_prevent_builtins():
with pytest.raises(ValueError):
ImageMath.eval("(lambda: exec('exit()'))()", {"exec": None})


def test_logical():
assert pixel(ImageMath.eval("not A", images)) == 0
assert pixel(ImageMath.eval("A and B", images)) == "L 2"
Expand Down
9 changes: 6 additions & 3 deletions docs/releasenotes/10.2.0.rst
Expand Up @@ -62,10 +62,13 @@ output only the quantization and Huffman tables for the image.
Security
========

TODO
^^^^
Restricted environment keys for ImageMath.eval
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

TODO
:cve:`2023-50447`: If an attacker has control over the keys passed to the
``environment`` argument of :py:meth:`PIL.ImageMath.eval`, they may be able to execute
arbitrary code. To prevent this, keys matching the names of builtins and keys
containing double underscores will now raise a :py:exc:`ValueError`.

Other Changes
=============
Expand Down
5 changes: 5 additions & 0 deletions src/PIL/ImageMath.py
Expand Up @@ -234,6 +234,11 @@ def eval(expression, _dict={}, **kw):

# build execution namespace
args = ops.copy()
for k in list(_dict.keys()) + list(kw.keys()):
if "__" in k or hasattr(builtins, k):
msg = f"'{k}' not allowed"
raise ValueError(msg)

args.update(_dict)
args.update(kw)
for k, v in args.items():
Expand Down