diff --git a/bandit/core/blacklisting.py b/bandit/core/blacklisting.py index 53f4c73a..99f06457 100644 --- a/bandit/core/blacklisting.py +++ b/bandit/core/blacklisting.py @@ -53,6 +53,10 @@ def blacklist(context, config): name = "" # handle '__import__()' else: name = context.call_function_name_qual + # In the case the Call is an importlib.import, treat the first + # argument name as an actual import module name. + if name in ["importlib.import_module", "importlib.__import__"]: + name = context.call_args[0] for check in blacklists[node_type]: for qn in check['qualnames']: if fnmatch.fnmatch(name, qn): diff --git a/examples/imports-with-importlib.py b/examples/imports-with-importlib.py new file mode 100644 index 00000000..cc0bd659 --- /dev/null +++ b/examples/imports-with-importlib.py @@ -0,0 +1,5 @@ +import importlib +a = importlib.import_module('os') +b = importlib.import_module('pickle') +c = importlib.__import__('sys') +d = importlib.__import__('subprocess') diff --git a/tests/functional/test_functional.py b/tests/functional/test_functional.py index 60dd5851..58ec5996 100644 --- a/tests/functional/test_functional.py +++ b/tests/functional/test_functional.py @@ -256,6 +256,14 @@ class FunctionalTests(testtools.TestCase): } self.check_example('imports.py', expect) + def test_imports_using_importlib(self): + '''Test for dangerous imports using importlib.''' + expect = { + 'SEVERITY': {'UNDEFINED': 0, 'LOW': 2, 'MEDIUM': 0, 'HIGH': 0}, + 'CONFIDENCE': {'UNDEFINED': 0, 'LOW': 0, 'MEDIUM': 0, 'HIGH': 2} + } + self.check_example('imports-with-importlib.py', expect) + def test_mktemp(self): '''Test for `tempfile.mktemp`.''' expect = {