CVE-2023-37271: Improper Control of Dynamically-Managed Code Resources (CWE-913)
value: RestrictedPython is a tool that helps to define a subset of the Python language which allows users to provide a program input into a trusted environment. RestrictedPython does not check access to stack frames and their attributes. Stack frames are accessible within at least generators and generator expressions, which are allowed inside RestrictedPython. Prior to versions 6.1 and 5.3, an attacker with access to a RestrictedPython environment can write code that gets the current stack frame in a generator and then walk the stack all the way beyond the RestrictedPython invocation boundary, thus breaking out of the restricted sandbox and potentially allowing arbitrary code execution in the Python interpreter. All RestrictedPython deployments that allow untrusted users to write Python code in the RestrictedPython environment are at risk. In terms of Zope and Plone, this would mean deployments where the administrator allows untrusted users to create and/or edit objects of type `Script (Python)`, `DTML Method`, `DTML Document` or `Zope Page Template`. This is a non-default configuration and likely to be extremely rare. The problem has been fixed in versions 6.1 and 5.3.
CWE description: The product does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements.
CVSS v3 base score: 9.9
Published: 2023-07-11T18:15Z
Repository: https://github.com/zopefoundation/RestrictedPython
Language: Other
Files changed: CHANGES.rst, docs/contributing/index.rst, src/RestrictedPython/transformer.py, tests/transformer/test_inspect.py
Commit date: 2023-07-08 07:14:27 +0000
Commit message: Merge pull request from GHSA-wqc8-x2pr-7jqh

* move the commented fix into this branch

* more verbose infos, and linting

* 3 tests for generators

* - add change log entry

---------

Co-authored-by: Jens Vagelpohl <jens@plyp.com>
Diff: diff --git a/CHANGES.rst b/CHANGES.rst
index 66353c0..6e43a00 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -13,10 +13,15 @@ Features
 ++++++++
 
 - Allow to use the package with Python 3.12 -- Caution: No security audit has
   been done so far.
 
+Fixes
++++++
+
+- Restrict access to some attributes accessible via the ``inspect`` module.
+
 
 6.0 (2022-11-03)
 ----------------
 
 Backwards incompatible changes
diff --git a/docs/contributing/index.rst b/docs/contributing/index.rst
index 20db4af..49f1127 100644
--- a/docs/contributing/index.rst
+++ b/docs/contributing/index.rst
@@ -62,10 +62,11 @@ To do so:
             return self.node_contents_visit(node)
 
     All AST Nodes without an explicit ``visit_<AST Node>`` method, are denied by default.
     So the usage of this expression and functionality is not allowed.
 
+* Check the documentation for `inspect <https://docs.python.org/3/library/inspect.html>`_ and adjust the ``transformer.py:INSPECT_ATTRIBUTES`` list.
 * Add a corresponding changelog entry.
 * Additionally modify ``.meta.toml`` and run the ``meta/config`` script (for details see: https://github.com/mgedmin/check-python-versions) to update the following files:
 
   * ``/setup.py`` - Check that the new Python version classifier has been added ``"Programming Language :: Python :: <version>",``, and that the ``python_requires`` section has been updated correctly.
   * ``/tox.ini`` - Check that a ``testenv`` entry is added to the general ``envlist`` statement.
diff --git a/src/RestrictedPython/transformer.py b/src/RestrictedPython/transformer.py
index f20650a..e8cbf4b 100644
--- a/src/RestrictedPython/transformer.py
+++ b/src/RestrictedPython/transformer.py
@@ -61,10 +61,36 @@ FORBIDDEN_FUNC_NAMES = frozenset([
     'printed',
     'builtins',
     'breakpoint',
 ])
 
+# inspect attributes. See also
+# https://docs.python.org/3/library/inspect.html
+INSPECT_ATTRIBUTES = frozenset([
+    # traceback
+    "tb_frame",
+    "tb_next",
+    # code
+    "co_code",
+    # frame
+    "f_back",
+    "f_builtins",
+    "f_code",
+    "f_globals",
+    "f_locals",
+    "f_trace",
+    # generator
+    "gi_frame",
+    "gi_code",
+    "gi_yieldfrom",
+    # coroutine
+    "cr_await",
+    "cr_frame",
+    "cr_code",
+    "cr_origin",
+])
+
 
 # When new ast nodes are generated they have no 'lineno', 'end_lineno',
 # 'col_offset' and 'end_col_offset'. This function copies these fields from the
 # incoming node:
 def copy_locations(new_node, old_node):
@@ -842,10 +868,17 @@ class RestrictingNodeTransformer(ast.NodeTransformer):
             self.error(
                 node,
                 '"{name}" is an invalid attribute name because it ends '
                 'with "__roles__".'.format(name=node.attr))
 
+        if node.attr in INSPECT_ATTRIBUTES:
+            self.error(
+                node,
+                f'"{node.attr}" is a restricted name,'
+                ' that is forbidden to access in RestrictedPython.',
+            )
+
         if isinstance(node.ctx, ast.Load):
             node = self.node_contents_visit(node)
             new_node = ast.Call(
                 func=ast.Name('_getattr_', ast.Load()),
                 args=[node.value, ast.Str(node.attr)],
diff --git a/tests/transformer/test_inspect.py b/tests/transformer/test_inspect.py
new file mode 100644
index 0000000..05e7d41
--- /dev/null
+++ b/tests/transformer/test_inspect.py
@@ -0,0 +1,60 @@
+from RestrictedPython import compile_restricted_exec
+
+
+def test_get_inspect_frame_on_generator():
+    source_code = """
+generator = (statement.gi_frame for _ in (1,))
+generator_element = [elem for elem in generator][0]
+
+"""
+    result = compile_restricted_exec(source_code)
+    assert result.errors == (
+        'Line 2: "gi_frame" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+    )
+
+
+def test_get_inspect_frame_back_on_generator():
+    source_code = """
+generator = (statement.gi_frame.f_back.f_back for _ in (1,))
+generator_element = [elem for elem in generator][0]
+
+"""
+    result = compile_restricted_exec(source_code)
+    assert result.errors == (
+        'Line 2: "f_back" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+        'Line 2: "f_back" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+        'Line 2: "gi_frame" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+    )
+
+
+def test_call_inspect_frame_on_generator():
+    source_code = """
+generator = None
+frame = None
+
+def test():
+    global generator, frame
+    frame = g.gi_frame.f_back.f_back
+    yield frame
+
+generator = test()
+generator.send(None)
+os = frame.f_builtins.get('__import__')('os')
+
+result = os.listdir('/')
+"""
+    result = compile_restricted_exec(source_code)
+    assert result.errors == (
+        'Line 7: "f_back" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+        'Line 7: "f_back" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+        'Line 7: "gi_frame" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+        'Line 12: "f_builtins" is a restricted name, '
+        'that is forbidden to access in RestrictedPython.',
+    )

Fixed code: Fixes

- Restrict access to some attributes accessible via the ``inspect`` module.

* Check the documentation for `inspect <https://docs.python.org/3/library/inspect.html>`_ and adjust the ``transformer.py:INSPECT_ATTRIBUTES`` list.
# inspect attributes. See also
# https://docs.python.org/3/library/inspect.html
INSPECT_ATTRIBUTES = frozenset([
    # traceback
    "tb_frame",
    "tb_next",
    # code
    "co_code",
    # frame
    "f_back",
    "f_builtins",
    "f_code",
    "f_globals",
    "f_locals",
    "f_trace",
    # generator
    "gi_frame",
    "gi_code",
    "gi_yieldfrom",
    # coroutine
    "cr_await",
    "cr_frame",
    "cr_code",
    "cr_origin",
])

        if node.attr in INSPECT_ATTRIBUTES:
            self.error(
                node,
                f'"{node.attr}" is a restricted name,'
                ' that is forbidden to access in RestrictedPython.',
            )

from RestrictedPython import compile_restricted_exec


def test_get_inspect_frame_on_generator():
    source_code = """
generator = (statement.gi_frame for _ in (1,))
generator_element = [elem for elem in generator][0]

"""
    result = compile_restricted_exec(source_code)
    assert result.errors == (
        'Line 2: "gi_frame" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
    )


def test_get_inspect_frame_back_on_generator():
    source_code = """
generator = (statement.gi_frame.f_back.f_back for _ in (1,))
generator_element = [elem for elem in generator][0]

"""
    result = compile_restricted_exec(source_code)
    assert result.errors == (
        'Line 2: "f_back" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
        'Line 2: "f_back" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
        'Line 2: "gi_frame" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
    )


def test_call_inspect_frame_on_generator():
    source_code = """
generator = None
frame = None

def test():
    global generator, frame
    frame = g.gi_frame.f_back.f_back
    yield frame

generator = test()
generator.send(None)
os = frame.f_builtins.get('__import__')('os')

result = os.listdir('/')
"""
    result = compile_restricted_exec(source_code)
    assert result.errors == (
        'Line 7: "f_back" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
        'Line 7: "f_back" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
        'Line 7: "gi_frame" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
        'Line 12: "f_builtins" is a restricted name, '
        'that is forbidden to access in RestrictedPython.',
    )