Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sandbox Python in pure Python?

I'm developing a web game in pure Python, and want some simple scripting available to allow for more dynamic game content. Game content can be added live by privileged users.

It would be nice if the scripting language could be Python. However, it can't run with access to the environment the game runs on since a malicious user could wreak havoc which would be bad. Is it possible to run sandboxed Python in pure Python?

Update: In fact, since true Python support would be way overkill, a simple scripting language with Pythonic syntax would be perfect.

If there aren't any Pythonic script interpreters, are there any other open source script interpreters written in pure Python that I could use? The requirements are support for variables, basic conditionals and function calls (not definitions).

like image 728
Blixt Avatar asked Jun 18 '10 08:06

Blixt


People also ask

Does codesandbox have Python?

There are now over 30 versions of Python with the lastest version being version 3.8. 1! Python is a powerful and easy to learn to learn and read language for beginners and experts!


2 Answers

AFAIK it is possible to run a code in a completely isolated environment:

exec somePythonCode in {'__builtins__': {}}, {} 

But in such environment you can do almost nothing :) (you can not even import a module; but still a malicious user can run an infinite recursion or cause running out of memory.) Probably you would want to add some modules that will be the interface to you game engine.

like image 44
Messa Avatar answered Sep 25 '22 01:09

Messa


This is really non-trivial.

There are two ways to sandbox Python. One is to create a restricted environment (i.e., very few globals etc.) and exec your code inside this environment. This is what Messa is suggesting. It's nice but there are lots of ways to break out of the sandbox and create trouble. There was a thread about this on Python-dev a year ago or so in which people did things from catching exceptions and poking at internal state to break out to byte code manipulation. This is the way to go if you want a complete language.

The other way is to parse the code and then use the ast module to kick out constructs you don't want (e.g. import statements, function calls etc.) and then to compile the rest. This is the way to go if you want to use Python as a config language etc.

Another way (which might not work for you since you're using GAE), is the PyPy sandbox. While I haven't used it myself, word on the intertubes is that it's the only real sandboxed Python out there.

Based on your description of the requirements (The requirements are support for variables, basic conditionals and function calls (not definitions)) , you might want to evaluate approach 2 and kick out everything else from the code. It's a little tricky but doable.

like image 82
Noufal Ibrahim Avatar answered Sep 26 '22 01:09

Noufal Ibrahim