sandboxing python code

ben at transversal.com ben at transversal.com
Tue Jun 3 05:11:20 EDT 2003


Hi!

I've recently (6 months or so) been converted to Python, and so have
become an avid reader of this newgroup. One thing that has been brought up
occasionally by other people, but never has really been answered
satisfactorily is the problem of running untrusted code.

I have been interested in writing a web based program where some "clients"
would be able to enter code via a web interface which would then be
executed on the server machines. Obviously I don't trust this code, so I
want not only to be able to stop people from importing unwanted libraries,
but also from writing infinite loops or using up infinite memory. There
are a couple of ways I can think of doing this:

1. Have a pseudo language which I then can render doen to python before
running. But then whats the point of using python? I want to give them all
the power of python where allowed

2. Simply run the code using exec with restricted globals and locals
dictionaries. This can stop people importing dodgy libraries, but cannot
stop people writing infinite loops etc

3. Use the parser to generate the AST for the program, and then add checks
inside for loops etc which will cause the program to quit if a certain
counter reaches a maximum. This doesn't solve the memory problem either.

4. Use the c api to run the compiled bytecode a batch at a time, e.g run
for a 100 instructions and the check a condition, bailing out if it fails.
This still doesn't stop people doing something like range(100000000), and
also doesn't seem to have support in the api, so would entail effectively
writing my own python virtual machine.

Obviously there are also combinations of the above choices. What I want to
know is what experience other people have with this kind of thing, and
whether something is being worked on for a future version of python. I do
know about Zope, but it doesn't seem to do the full DoS stuff, and also
bring in a lot of other stuff with it.

Thanks for taking the time to read this.

Cheers!

Ben
---




More information about the Python-list mailing list