zopefoundation / RestrictedPython

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

handling of compile_restricted optional params ``flags`` and ``dont_inherit`` #114

Open loechel opened 6 years ago

loechel commented 6 years ago

@stephan-hof did bring up the point that the current handling of flags and dont_inherit did not work as expected in https://github.com/zopefoundation/RestrictedPython/pull/39#issuecomment-283074699

Currently this inheritance is not compatible. Let's assume the following code in module called test.py

from __future__ import print_function
from RestrictedPython import compile_restricted as compile
compile(<source>, filename="<inline>", mode="exec", ...) 

Even if dont_inhert=False the future is not recognized in the compile_restricted function. When compile_restricted is called it uses the futures from compile.py not from test.py See: https://github.com/python/cpython/blob/2.7/Python/ceval.c#L4159

If this inheriting should be compatible with the original compile function something like this needs to be done.

parent_flags = sys._getframe(1).f_code.co_flags
parent_flags = parent_flags & PyCF_MASK
flags = flags | parent_flags

and then call compile with flags=flags and dont_inhert=True to avoid using future flags from compile.py.

Right now the users of RestrictedPython don't need this feature of future inheriting so I would leave it out. Typically the comes from a different component anyway so inheriting the flags where restricted_compile is called could lead to surprising effects.

loechel commented 6 years ago

supersede #96

Currently _compile_restricted_mode takes flags and dont_inherit as arguments but it does not pass them to compile (code has comment signs in front of) in case there is a policy.

Either it should not have arguments or it should handle them properly.

by @icemac

ebagdasa commented 4 years ago

is it related to this code:

https://github.com/zopefoundation/RestrictedPython/blob/6c602c90cf8658cf1aaea660543228f127f6bbfd/src/RestrictedPython/compile.py#L70-L73

Why were these lines commented?

loechel commented 4 years ago

@ebagdasa as fas as I remember they are commented out, as we got problems / unpredicted results if we pass the current defaults.

We should look more into that when we have time.

perrinjerome commented 7 months ago

For reference, to get __future__.print_function working, I did https://github.com/perrinjerome/RestrictedPython/commit/4c132f622f33575aca8da1d0450caa3a33b8c0a0 . The missing piece of the puzzle seems to be that the ast should not be retrieved with ast.parse but with compile and ast.PyCF_ONLY_AST flags - at least for print_function because this is a future that makes a difference at parsing time, not compile time.