Sandboxing Python

Christian Gollwitzer auriocus at gmx.de
Sun Aug 23 01:17:33 EDT 2015


Am 23.08.15 um 02:04 schrieb Chris Angelico:
>> <code>
>>>>> import os
>>>>> eval("os.system('rm -rf /')", {"__builtins__":None})
>> Traceback (most recent call last):
>>    File "<pyshell#8>", line 1, in <module>
>>      eval("os.system('rm -rf /')", {"__builtins__":None})
>>    File "<string>", line 1, in <module>
>> TypeError: 'NoneType' object is not subscriptable
>> </code>
>
> Got it, thanks. The answer is: It's easy to make something you can't
> yourself break out of. It just means you don't know all the tricks.
>
> http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
>
>>>> cmd="""[c for c in ().__class__.__base__.__subclasses__() if c.__name__ == 'catch_warnings'][0]()._module.__builtins__["__import__"]("os").system("echo Hello")"""
>>>> eval(cmd,{"__builtins__":None})
> Hello
> 0
>
> Et voila. Arbitrary module loading, arbitrary code execution, have fun.

In one of my other favourite languages, you can create sandboxes very 
easily. You create them as a new slave interpreter with restrictions:

interp create -safe myInterp
myInterp eval $userinput

In addition to removing "dangerous" functions, you can limit the mount 
of time spent by the eval, or alias new functions to callbacks from the 
main interpreter (though this may break security)
This was once built into it for a browser plugin (now extinct).

Would it be that difficult to get the same for Python? On the C side, 
the interpreter is a structure and does not use global variables (as 
opposed to CPython), therefore it is easy to create more than one 
interpreter in a single program, and also to reflect that to the 
scripting level.

	Christian





More information about the Python-list mailing list