File 030-CVE-2022-22817.patch of Package python-Pillow

From 8531b01d6cdf0b70f256f93092caa2a5d91afc11 Mon Sep 17 00:00:00 2001
From: Andrew Murray <radarhere@users.noreply.github.com>
Date: Sun, 2 Jan 2022 17:23:49 +1100
Subject: [PATCH] Restrict builtins for ImageMath.eval

---
 Tests/test_imagemath.py     | 7 +++++++
 docs/releasenotes/9.0.0.rst | 8 ++++++++
 src/PIL/ImageMath.py        | 7 ++++++-
 3 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/Tests/test_imagemath.py b/Tests/test_imagemath.py
index 2329b747..4505633b 100644
--- a/Tests/test_imagemath.py
+++ b/Tests/test_imagemath.py
@@ -1,5 +1,6 @@
 from __future__ import print_function
 from helper import unittest, PillowTestCase
+import pytest
 
 from PIL import Image
 from PIL import ImageMath
@@ -58,6 +59,12 @@ class TestImageMath(PillowTestCase):
         self.assertEqual(pixel(
             ImageMath.eval("float(B)**33", images)), "F 8589934592.0")
 
+
+    def test_prevent_exec(self):
+        with pytest.raises(ValueError):
+            ImageMath.eval("exit")
+
+
     def test_logical(self):
         self.assertEqual(pixel(ImageMath.eval("not A", images)), 0)
         self.assertEqual(pixel(ImageMath.eval("A and B", images)), "L 2")
diff --git a/src/PIL/ImageMath.py b/src/PIL/ImageMath.py
index d985877a..ec5d10b4 100644
--- a/src/PIL/ImageMath.py
+++ b/src/PIL/ImageMath.py
@@ -264,7 +264,12 @@ def eval(expression, _dict={}, **kw):
         if hasattr(v, "im"):
             args[k] = _Operand(v)
 
-    out = builtins.eval(expression, args)
+    code = compile(expression, "<string>", "eval")
+    for name in code.co_names:
+        if name not in args and name != "abs":
+            raise ValueError('not allowed: {}'.format(name))
+
+    out = builtins.eval(expression, {"__builtins": {"abs": abs}}, args)
     try:
         return out.im
     except AttributeError:

openSUSE Build Service is sponsored by