Module injection High

Untrusted user imports in Python allow an attacker to load arbitrary code. To prevent malicious code from running, only allow imports from trusted libraries or from libraries on allow lists.

Detector ID
python/module-injection@v1.0
Category
Common Weakness Enumeration (CWE) external icon

Noncompliant example

1def module_injection_noncompliant():
2    import importlib
3    module_name = input('module name')
4    # Noncompliant: Untrusted user input is being passed to `import_module`.
5    importlib.import_module(module_name)

Compliant example

1def module_injection_compliant():
2    import importlib
3    allowed_module_names_list = ['example_module1', 'example_module2']
4    module_name = input('module name')
5    if module_name in allowed_module_names_list:
6        # Compliant: User input is validated before using in `import_module()`.
7        importlib.import_module(module_name)