CVE-2023-37271 (published 2023-07-11T18:15Z)

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.

CVSS v3 base score: 9.9, CRITICAL (CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H)

Weakness information:
cwe_id: CWE-913
cwe_name: Improper Control of Dynamically-Managed Code Resources
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.
extended_description: Many languages offer powerful features that allow the programmer to dynamically create or modify existing code, or resources used by code such as variables and objects. While these features can offer significant flexibility and reduce development time, they can be extremely dangerous if attackers can directly influence these code resources in unexpected ways.
         

Fix information:
repo_url: https://github.com/zopefoundation/RestrictedPython
commit_details: repo_url: https://github.com/zopefoundation/RestrictedPython
author: Alexander Loechel
author_date: 2023-07-08 09:14:27+02:00
msg: 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>
repository: repo_url: https://github.com/zopefoundation/RestrictedPython
repo_name: zopefoundation/RestrictedPython
description: A restricted execution environment for Python to run untrusted code.
repo_language: Python
owner: zopefoundation
file_changes: filename: CHANGES.rst
change_type: ModificationType.MODIFY
diff: @@ -15,6 +15,11 @@ 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)
 ----------------

programming_language: Markdown
filename: index.rst
change_type: ModificationType.MODIFY
diff: @@ -64,6 +64,7 @@ To do so:
     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:
 

programming_language: Markdown
filename: transformer.py
change_type: ModificationType.MODIFY
diff: @@ -63,6 +63,32 @@ FORBIDDEN_FUNC_NAMES = frozenset([
     '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
@@ -844,6 +870,13 @@ class RestrictingNodeTransformer(ast.NodeTransformer):
                 '"{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(

programming_language: Python
filename: test_inspect.py
change_type: ModificationType.ADD
diff: @@ -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.',
+    )

programming_language: Python