Embedded Python and Restricted Execution

cgfandrich at my-deja.com cgfandrich at my-deja.com
Thu Jun 15 13:25:03 EDT 2000


In article <8F5198BEAgmcmhypernetcom at 199.171.54.194>,
  gmcm at hypernet.com (Gordon McMillan) wrote:
> 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
>


Thanks for the help.  That was the problem (test2 found test1's
imported modules in sys.modules).  Ended up writing a C++ version of
rexec (and ihooks) that has its own modules dictionary.

-chris


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list