Blob Blame History Raw
From cf8d70b86f0d5ee9e72a1e69ad76cf5831f977fa Mon Sep 17 00:00:00 2001
From: Eric Soroos <eric-github@soroos.net>
Date: Thu, 8 Feb 2024 21:32:44 +0100
Subject: [PATCH] Don't allow __ or builtins in env dictionarys for
 ImageMath.eval

---
 PIL/ImageMath.py        | 5 +++++
 Tests/test_imagemath.py | 6 ++++++
 2 files changed, 11 insertions(+)

diff --git a/PIL/ImageMath.py b/PIL/ImageMath.py
index 5312207..13550a9 100644
--- a/PIL/ImageMath.py
+++ b/PIL/ImageMath.py
@@ -213,6 +213,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 = "'{0}' not allowed".format(k)
+            raise ValueError(msg)
+
     args.update(_dict)
     args.update(kw)
     for k, v in list(args.items()):
diff --git a/Tests/test_imagemath.py b/Tests/test_imagemath.py
index da9d1d7..aaf32cf 100644
--- a/Tests/test_imagemath.py
+++ b/Tests/test_imagemath.py
@@ -45,6 +45,12 @@ def test_ops():
     assert_equal(pixel(ImageMath.eval("float(B)**2", images)), "F 4.0")
     assert_equal(pixel(ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
 
+def test_prevent_double_underscores():
+    assert_exception(ValueError, lambda: ImageMath.eval("1", {"__": None}))
+
+def test_prevent_builtins():
+    assert_exception(ValueError, lambda: ImageMath.eval("(lambda: isinstance('a', str))()", {"isinstance": None}))
+
 def test_logical():
     assert_exception(ValueError, ImageMath.eval("exit()"))
     assert_exception(ValueError, ImageMath.eval("(lambda:(exit()))()"))
-- 
2.43.0