9

I have python embedded in an application as a scripting platform so the users can write python scripts. I am trying to prevent imports so they cannot cause damage in anyway and have to stick to the provided API.

I have come up with the following Python code:

__builtins__ .__import__= None 
reload = None

This seems to prevent imports and prevents reloading of modules. The prevention of reloading is required so they can't reload builtins giving them back a working import.

However I am not a Python expert. Is there anything else I am missing that the user can still do to import modules?

Thanks

Alan Macdonald
  • 1,872
  • 20
  • 36
  • 3
    Please have a look at this [question](http://stackoverflow.com/q/3068139/183066). – jcollado Dec 08 '11 at 09:18
  • 1
    Thanks. From that post it's highlighted that there are really quite a lot of dangerous other things apart from import so just preventing import is probably not enough. – Alan Macdonald Dec 08 '11 at 13:06
  • If the user is running an application on his machinne, what can be "dangerous" about allowing him to make full use of Python? Or will your app be receiving scripts in a server, from untrusted remote users? – jsbueno Dec 08 '11 at 13:35
  • 1
    We wouldn't want them importing more code of ours beyond the documented and intended API as they may break the application or lose their data. Sharing the scripts around with people and it turns out it's malicious, a bit like the security vulnerabilities in Word macros. They could also use something in Python they think isn't dangerous but it turns out it is and hoses their system. If they chose to run through the standalone Python interpreter that's fine that's up to them but it wouldn't be the apps fault. – Alan Macdonald Dec 08 '11 at 13:49

1 Answers1

3

What you probably want is to run Python in a sandbox. There are a number of ways of doing this, for example PyPy has sandboxing support.

You could also try sandboxing the Python process itself using external tools, but I suppose this is dependent on the operating system.

Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • 1
    Thanks for the link about sandboxing. I was really looking for something that would work more generally without PyPy. The code I posted works on both CPython and IronPython for example. – Alan Macdonald Dec 08 '11 at 13:02
  • It is easy to hack something in to prevent imports, and they will likely be always override-able by clever people. Pypy implements sandboxing in its structure, done the right way. – jsbueno Dec 08 '11 at 13:33