Embedded Python and Restricted Execution
cgfandrich at my-deja.com
cgfandrich at my-deja.com
Mon Jun 12 13:07:45 EDT 2000
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.
Any ideas? Should I be doing this differently?
-chris
//====================================================================
static PyMethodDef restricted_methods[] =
{
{"__import__", restricted___import__, 1},
{"open", restricted_open, 1},
{NULL,NULL}
};
void InitRestricted()
{
PyObject *SecureModule;
SecureModule = PyImport_AddModule("__restricted__");
PyObject *SecureDictionary = PyModule_GetDict(SecureModule);
PyObject *SecureBuiltins=PyDict_New();
PyDict_SetItemString
(SecureDictionary,"__builtins__",SecureBuiltins);
PyObject *MainBuiltins = PyEval_GetBuiltins();
if(MainBuiltins && SecureBuiltins)
{
PyObject *MainKeys = PyDict_Keys(MainBuiltins);
int i;
// __import__
value = PyCFunction_New(&restricted_methods[0], NULL);
if (value != NULL)
PyDict_SetItemString(SecureBuiltins, "__import__", value);
Py_DECREF(value);
// open
value = PyCFunction_New(&restricted_methods[1], NULL);
if (value != NULL)
PyDict_SetItemString(SecureBuiltins, "open", value);
Py_DECREF(value);
for(i=0;i<PyList_Size(MainKeys);i++)
{
PyObject *key = PyList_GetItem(MainKeys,i);
char *keyname=PyString_AsString(key);
PyObject *value = PyDict_GetItemString
(MainBuiltins,keyname);
if((strcmpi(keyname,"__import__")!=0) && (strcmpi
(keyname,"open")!=0))
PyDict_SetItemString(SecureBuiltins,keyname,value);
}
}
}
void RunScript(char *Script,const BOOL Secure,PyObject *RetObject)
{
PyObject *module;
PyObject *dict;
if(Secure)
module = PyImport_AddModule("__restricted__");
else
module = PyImport_AddModule("__main__");
dict = PyModule_GetDict(module);
RetObject = PyRun_String(Script,Py_eval_input,dict,dict);
}
Sent via Deja.com http://www.deja.com/
Before you buy.
More information about the Python-list
mailing list