zopefoundation / RestrictedPython

A restricted execution environment for Python to run untrusted code.
http://restrictedpython.readthedocs.io/
Other
456 stars 38 forks source link

How can I use imports? #273

Open jsmith173 opened 5 months ago

jsmith173 commented 5 months ago

BUG/PROBLEM REPORT / FEATURE REQUEST

What I did:

Please see the attached code.

test1.zip

What I expect to happen:

No error message

What actually happened:

ImportError: import not found

What version of Python and Zope/Addons I am using:

Python: 3.11.5

d-maurer commented 5 months ago

jsmith173 wrote at 2024-3-17 02:17 -0700:

...

What I expect to happen:

No error message

What actually happened:

ImportError: import not found

RestrictedPython essentially is a code transformer which transforms some Python features (essentially attribute access and subscriptions) into function calls. An external policy package provides implementations for the respective functions and thereby can control the use of those features.

You can use the dis function from Python's dis module (dis means simething like "DISassember") to lean how interesting features (e.g. an import) it transformed by RestrictedPython.

Imports are potentially dangerous. Therefore, RestrictedPython does not come with an implementation. If your application needs imports, the corresponding policy package must provide it.

The error message tells you that the corresponding function has the name __import__. In your implementation, you would ensure that only safe modules can be imported. What is safe and what is not is determined by your application.

Your __import__ implementation should either reject an import or behave like Python's built in function of the same name.

You have observed that the use of RestrictedPython consists of a (restricted) compilation and the execution of the resulting code via exec (or eval). Beside the code to be executed, exec can get 2 optional dicts holding the "global" and "local" "variables" for the execution. If you provide only one dict, it is used for both global as well as local variabes. If you provide none, then the callers context is used.

The policy package mentioned above, typically provides a function safe_globals containing its implementations for controlled features (such as _gatattr, _getitem, __import__) and builtins considered safe (e.g. bytearray).