Untrusted code execution

Jon Ribbens jon+usenet at unequivocal.co.uk
Thu Apr 7 11:18:28 EDT 2016


On 2016-04-07, Chris Angelico <rosuav at gmail.com> wrote:
> On Thu, Apr 7, 2016 at 11:45 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>> And you would have to do something about the unfortunate matter that modules
>> have a reference to the unrestricted __builtins__:
>>
>> py> os.__builtins__['eval']
>> <built-in function eval>
>
> This *in itself* is blocked by the rule against leading-underscore
> attribute lookup. However, if you can get the sys module, the world's
> your oyster; and any other module that imports sys will give it to
> you:
>
>>>> import os
>>>> os.sys
><module 'sys' (built-in)>
>>>> codecs.sys
><module 'sys' (built-in)>
>
> Can't monkey-patch that away, and codecs.sys.modules["builtins"] will
> give you access to the original builtins. And you can go to any number
> of levels, tracing a chain from a white-listed module to the
> unrestricted sys.modules. The only modules that would be safe to
> whitelist are those that either don't import anything significant (I'm
> pretty sure 'math' is safe), or import everything with underscores
> ("import sys as _sys").

No, actually absolutely no modules at all are safe to import directly.
This is because the untrusted code might alter them, and then the
altered code would be used by the trusted main application. Trivial
examples might include altering hashlib to always return the same
hash, 're' to always or never match, etc. If you import something
then it needs to be a individual copy of the module, with each name
referring either to an immutable object or to an individual proxy for
the real object.



More information about the Python-list mailing list