Embedding a restricted python interpreter
Craig Ringer
craig at postnewspapers.com.au
Wed Jan 5 01:04:53 EST 2005
On Wed, 2005-01-05 at 13:43, Maurice LING wrote:
> Rolf Magnus wrote:
> > Hi,
> >
> > I would like to embed a python interpreter within a program, but since that
> > program would be able to automatically download scripts from the internet,
> > I'd like to run those in a restricted environment, which basically means
> > that I want to allow only a specific set of modules to be used by the
> > scripts, so that it wouldn't be possible for them to remove files from the
> > hard drive, kill processes or do other nasty stuff.
> > Is there any way to do that with the standard python interpreter?
> >
>
> I won't really count on that. In my opinions, which may be wrong, Python
> is not constructed to work in a sandbox like Java.
That is my understanding. In fact, I'd say with Python it's nearly
impossible given how dynamic everything is and the number of tricks that
can be used to obfuscate what you're doing. Think of the fun that can be
had with str.encode / str.decode and getattr/hasattr .
I looked into this, and my conclusion ended up being "Well, I'm using
Python because I want it's power and flexibilty. If I want a secure
scripting environment, I should use something like Lua or Qt Script for
Applications instead."
AFAIK that's why the rexec() builtin is disabled - it's just not
practical to make a restricted Python execution environment.
> You can try to use 'exec' to run your scripts in a constructed
> environment. For example,
>
> global = {}
> local = {}
>
> ... your stuffs ....
>
> statement = [] # to hold the script to run
>
> for line in statement:
> exec statement in global, local
>
> global and local are the global and local namespaces respectively.
> Although it had been explained to me before but I can't recall the
> details of how it works. In gist, you may be able to craft a global and
> local environment for your script to run in.
> I do not know if it is possible to disable or override 'import'......
You can do a fair bit to it by wrapping/replacing __builtin__.__import__
. Preventing people from getting around what you've done, though... not
sure.
--
Craig Ringer
More information about the Python-list
mailing list