Embedded Python and Restricted Execution

Gordon McMillan gmcm at hypernet.com
Mon Jun 12 15:22:04 EDT 2000


cgfandrich at my-deja.com wrote:

>I'm embedding Python in an application and I'd like to be able to run
>Python code (including callable PyObjects) in a restricted environment -
> much like rexec - but I'd like to control the environment in C/C++.
>I've tried the following and had some success:
>
>1. Create a new module.
>2. Add a "__builtins__" dictionary to the module.
>3. Copy references from existing "__builtins__" to new "__builtins__"
>(except for "__import__" and "open" - use my functions for those 2)
>4. Use the new "__builtins__" dictionary whenever I want to run code in
>restricted environment.
>
>When importing modules, I've also had to make sure that the module
>being imported gets the correct "__builtins__" dictionary.  The only
>problem is ... if I have 2 modules "test1" and "test2" that use the
>same Python source code, I can't run them in the different
>environments.  It seems like they both run with
>whichever "__builtins__" was used to import the first module.

I think you're saying that test1 and test2 both import some other module? 
If that's the case, the import in test2 will find the module already in 
sys.modules. So if test1 did an unrestricted import, test2 will find the 
other module to have an unrestricted builtins.

No easy answers for you. I assume you've checked out what rexec and bastion 
do (in pure Python). You might consider having 2 separate interpreters (as 
in Py_NewInterpreter, not 2 instances of python). Or you could completely 
take over the management of namespaces (as in using the equivalent of "mod 
= __import__(...)" which doesn't automatically put mod in sys.modules).

- Gordon



More information about the Python-list mailing list