Disable inline module import in inline Python

I am embedding Python 3.6 in my application and want to disable the import command in scripts so that users cannot import any python built-in libraries. I would like to use only the language itself and my own C ++ specific modules.

Py_SetProgramName (L"Example");
Py_Initialize ();
PyObject* mainModule = PyImport_AddModule ("__main__");
PyObject* globals = PyModule_GetDict (mainModule);

// This should work
std::string script1 = "print ('example')";
PyRun_String (script1.c_str (), Py_file_input, globals, nullptr);

// This should not work
std::string script2 = "import random\n"
                      "print (random.randint (1, 10))\n";
PyRun_String (script2.c_str (), Py_file_input, globals, nullptr);

Py_Finalize ();

Do you know any way to achieve this?

+4
source share
1 answer

Python has a long history of not being able to create a secure sandbox (see How can I use Python in pure Python? As a starting point, and then dive into the old python-dev discussion if you like it). Here is what I consider your best two options.

- . Python AST module, , , . , , - .

, , import () (, a.b.c a , , a.b a), . , , .

, . , , , import . , __builtins__, globals, // __double_underscores__ . AST .

getattr(__builtins__, '__imp'+'ort__')('other_module')

globals()['__imp'+'ort__']('other_module')

module.__loader__.__class__(
    "other_module",
    module.__loader__.path + '/../other_module.py'
).load_module()

( , , , , , .)

Python, PEP 551. ( : PEP.) 3.7 3.6.

, Python , . , import , , , compile . Python ( sys.addaudithook) C ( PySys_AddAuditHook).

Programs/spython.c - C, Python ( PEP):

import sys

def prevent_bitly(event, args):
    if event == 'urllib.Request' and '://bit.ly/' in args[0]:
        print(f'WARNING: urlopen({args[0]}) blocked')
        raise RuntimeError('access to bit.ly is not allowed')

sys.addaudithook(prevent_bitly)

Python, . , , , .

+4

Source: https://habr.com/ru/post/1694136/


All Articles