Skip to content

Commit

Permalink
#694 Bandit fails when using importlib with named arguments (#701)
Browse files Browse the repository at this point in the history
* #694 Bandit fails when using importlib with named arguments

* add missing tests

* improvement in the tests

Co-authored-by: Luke Hinds <7058938+lukehinds@users.noreply.github.com>
  • Loading branch information
maciejstromich and lukehinds committed Apr 5, 2021
1 parent 1eff509 commit 193c355
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
5 changes: 4 additions & 1 deletion bandit/core/blacklisting.py
Expand Up @@ -47,7 +47,10 @@ def blacklist(context, config):
# argument name as an actual import module name.
# Will produce None if argument is not a literal or identifier
if name in ["importlib.import_module", "importlib.__import__"]:
name = context.call_args[0]
if context.call_args_count > 0:
name = context.call_args[0]
else:
name = context.call_keywords['name']
for check in blacklists[node_type]:
for qn in check['qualnames']:
if name is not None and fnmatch.fnmatch(name, qn):
Expand Down
6 changes: 6 additions & 0 deletions examples/imports-with-importlib.py
Expand Up @@ -7,3 +7,9 @@
# Do not crash when target is an expression
e = importlib.import_module(MODULE_MAP[key])
f = importlib.__import__(MODULE_MAP[key])

# Do not crash when target is a named argument
g = importlib.import_module(name='sys')
h = importlib.__import__(name='subprocess')
i = importlib.import_module(name='subprocess', package='bar.baz')
j = importlib.__import__(name='sys', package='bar.baz')
4 changes: 2 additions & 2 deletions tests/functional/test_functional.py
Expand Up @@ -230,8 +230,8 @@ def test_imports(self):
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}
'SEVERITY': {'UNDEFINED': 0, 'LOW': 4, 'MEDIUM': 0, 'HIGH': 0},
'CONFIDENCE': {'UNDEFINED': 0, 'LOW': 0, 'MEDIUM': 0, 'HIGH': 4}
}
self.check_example('imports-with-importlib.py', expect)

Expand Down

0 comments on commit 193c355

Please sign in to comment.