Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sandbox to execute possibly unfriendly python code [duplicate]

Let's say there is a server on the internet that one can send a piece of code to for evaluation. At some point server takes all code that has been submitted, and starts running and evaluating it. However, at some point it will definitely bump into "os.system('rm -rf *')" sent by some evil programmer. Apart from "rm -rf" you could expect people try using the server to send spam or dos someone, or fool around with "while True: pass" kind of things.

Is there a way to coop with such unfriendly/untrusted code? In particular I'm interested in a solution for python. However if you have info for any other language, please share.

like image 532
facha Avatar asked Oct 11 '10 21:10

facha


3 Answers

If you are not specific to CPython implementation, you should consider looking at PyPy[wiki] for these purposes — this Python dialect allows transparent code sandboxing.

Otherwise, you can provide fake __builtin__ and __builtins__ in the corresponding globals/locals arguments to exec or eval.

Moreover, you can provide dictionary-like object instead of real dictionary and trace what untrusted code does with it's namespace.

Moreover, you can actually trace that code (issuing sys.settrace() inside restricted environment before any other code executed) so you can break execution if something will go bad.

If none of solutions is acceptable, use OS-level sandboxing like chroot, unionfs and standard multiprocess python module to spawn code worker in separate secured process.

like image 173
toriningen Avatar answered Oct 20 '22 14:10

toriningen


You can check pysandbox which does just that, though the VM route is probably safer if you can afford it.

like image 29
Luper Rouch Avatar answered Oct 20 '22 15:10

Luper Rouch


It's impossible to provide an absolute solution for this because the definition of 'bad' is pretty hard to nail down.

Is opening and writing to a file bad or good? What if that file is /dev/ram?

You can profile signatures of behavior, or you can try to block anything that might be bad, but you'll never win. Javascript is a pretty good example of this, people run arbitrary javascript code all the time on their computers -- it's supposed to be sandboxed but there's all sorts of security problems and edge conditions that crop up.

I'm not saying don't try, you'll learn a lot from the process.

Many companies have spent millions (Intel just spent billions on McAffee) trying to understand how to detect 'bad code' -- and every day machines running McAffe anti-virus get infected with viruses. Python code isn't any less dangerous than C. You can run system calls, bind to C libraries, etc.

like image 2
synthesizerpatel Avatar answered Oct 20 '22 13:10

synthesizerpatel