Skip to content

Commit

Permalink
Fix a false positive condition yaml_load
Browse files Browse the repository at this point in the history
The yaml.load() function has a second argument that is typically
passed as a kwarg. However, someone could pass as a positional
argument as well. In such a case, Bandit would flag code passing
a SafeLoader even though that is validly secure.

The fix involves looking at the positional args. However, the
convenience function to do so also had no handling of ast.Attribute
as args. So get_call_arg_at_position() was modified to function much
like call_args().

Closes PyCQA#546

Signed-off-by: Eric Brown <eric_wade_brown@yahoo.com>
  • Loading branch information
ericwb committed Jul 9, 2022
1 parent 5809d1b commit abac8d3
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 3 deletions.
5 changes: 2 additions & 3 deletions bandit/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,9 +276,8 @@ def get_call_arg_at_position(self, position_num):
"""
max_args = self.call_args_count
if max_args and position_num < max_args:
return self._get_literal_value(
self._context["call"].args[position_num]
)
arg = self._context["call"].args[position_num]
return getattr(arg, "attr", None) or self._get_literal_value(arg)
else:
return None

Expand Down
2 changes: 2 additions & 0 deletions bandit/plugins/yaml_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ def yaml_load(context):
func == "load",
not context.check_call_arg_value("Loader", "SafeLoader"),
not context.check_call_arg_value("Loader", "CSafeLoader"),
not context.get_call_arg_at_position(1) == "SafeLoader",
not context.get_call_arg_at_position(1) == "CSafeLoader",
]
):
return bandit.Issue(
Expand Down
8 changes: 8 additions & 0 deletions examples/yaml_load.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import json
import yaml
from yaml import CSafeLoader
from yaml import SafeLoader


def test_yaml_load():
Expand All @@ -18,3 +20,9 @@ def test_json_load():
j = json.load("{}")

yaml.load("{}", Loader=yaml.Loader)

# no issue should be found
yaml.load("{}", SafeLoader)
yaml.load("{}", yaml.SafeLoader)
yaml.load("{}", CSafeLoader)
yaml.load("{}", yaml.CSafeLoader)

0 comments on commit abac8d3

Please sign in to comment.