Safe Python Execution

Alex Martelli aleaxit at yahoo.com
Thu Feb 16 10:59:03 EST 2006


Graham <graham.abbott at gmail.com> wrote:

> I've been messing around with trying to get a small sandbox like
> environment where i could execute python code in a "safe" way.
> Basically what the old restricted execution module attempted to do.
> I've written a small amount of code to get custom interpreter running,
> but i'm not really sure if its safe.
> 
> The way i'm controlling functionality is with some games and exec, so
> if 'code' was the text code you wanted to execute i run:
> 
> exec code in {'__builtins__':None"}
> 
> obviously this doesn't give you much to play with, but it does remove
> file access and importing as far as i can tell. Can anyone think of a
> hack around this? I assume if it was this easy it would be a module
> already but i figured i would ask.

I suggest compiling the code and examining the names used in the code
object (co_names attribute of the code object which compile returns) --
refuse to execute the code if it mentions, defines or uses any special
name (starting and ending with two underscores).  That, plus removing
almost all builtins as you do here, should be a good start.


Alex



More information about the Python-list mailing list