bandit.core package¶
Submodules¶
bandit.core.blacklisting module¶
-
bandit.core.blacklisting.
blacklist
(context, config)¶ Generic blacklist test, B001.
This generic blacklist test will be called for any encountered node with defined blacklist data available. This data is loaded via plugins using the ‘bandit.blacklists’ entry point. Please see the documentation for more details. Each blacklist datum has a unique bandit ID that may be used for filtering purposes, or alternatively all blacklisting can be filtered using the id of this built in test, ‘B001’.
-
bandit.core.blacklisting.
report_issue
(check, name)¶
bandit.core.config module¶
-
class
bandit.core.config.
BanditConfig
(config_file=None)¶ Bases:
object
-
config
¶ Property to return the config dictionary
Returns: Config dictionary
-
convert_legacy_blacklist_data
()¶ Detect legacy blacklist data and convert it to new format.
-
static
convert_legacy_blacklist_tests
(profiles, bad_imports, bad_calls)¶ Detect old blacklist tests, convert to use new builtin.
-
convert_legacy_config
()¶
-
convert_names_to_ids
()¶ Convert test names to IDs, unknown names are left unchanged.
-
get_option
(option_string)¶ Returns the option from the config specified by the option_string.
‘.’ can be used to denote levels, for example to retrieve the options from the ‘a’ profile you can use ‘profiles.a’ :param option_string: The string specifying the option to retrieve :return: The object specified by the option_string, or None if it can’t be found.
-
get_setting
(setting_name)¶
-
validate
(path)¶ Validate the config data.
-
bandit.core.constants module¶
bandit.core.context module¶
-
class
bandit.core.context.
Context
(context_object=None)¶ Bases:
object
-
bytes_val
¶ Get the value of a standalone bytes object (py3 only)
Returns: value of a standalone bytes object
-
call_args
¶ Get a list of function args
Returns: A list of function args
-
call_args_count
¶ Get the number of args a function call has
Returns: The number of args a function call has
-
call_function_name
¶ Get the name (not FQ) of a function call
Returns: The name (not FQ) of a function call
-
call_function_name_qual
¶ Get the FQ name of a function call
Returns: The FQ name of a function call
-
call_keywords
¶ Get a dictionary of keyword parameters
Returns: A dictionary of keyword parameters for a call as strings
-
check_call_arg_value
(argument_name, argument_values=None)¶ Checks for a value of a named argument in a function call.
Returns none if the specified argument is not found. :param argument_name: A string - name of the argument to look for :param argument_values: the value, or list of values to test against :return: Boolean True if argument found and matched, False if found and not matched, None if argument not found at all
-
function_def_defaults_qual
¶ Get a list of fully qualified default values in a function def
Returns: List of defaults
-
get_call_arg_at_position
(position_num)¶ Returns positional argument at the specified position (if it exists)
Parameters: position_num – The index of the argument to return the value for Returns: Value of the argument at the specified position if it exists
-
get_call_arg_value
(argument_name)¶ Gets the value of a named argument in a function call.
Returns: named argument value
-
get_lineno_for_call_arg
(argument_name)¶ Get the line number for a specific named argument
In case the call is split over multiple lines, get the correct one for the argument. :param argument_name: A string - name of the argument to look for :return: Integer - the line number of the found argument, or -1
-
is_module_being_imported
(module)¶ Check for the specified module is currently being imported
Parameters: module – The module name to look for Returns: True if the module is found, False otherwise
-
is_module_imported_exact
(module)¶ Check if a specified module has been imported; only exact matches.
Parameters: module – The module name to look for Returns: True if the module is found, False otherwise
-
is_module_imported_like
(module)¶ Check if a specified module has been imported
Check if a specified module has been imported; specified module exists as part of any import statement. :param module: The module name to look for :return: True if the module is found, False otherwise
-
node
¶ Get the raw AST node associated with the context
Returns: The raw AST node associated with the context
-
statement
¶ Get the raw AST for the current statement
Returns: The raw AST for the current statement
-
string_val
¶ Get the value of a standalone unicode or string object
Returns: value of a standalone unicode or string object
-
string_val_as_escaped_bytes
¶ Get escaped value of the object.
Turn the value of a string or bytes object into byte sequence with unknown, control, and characters escaped.
This function should be used when looking for a known sequence in a potentially badly encoded string in the code.
Returns: sequence of printable ascii bytes representing original string
-
bandit.core.extension_loader module¶
-
class
bandit.core.extension_loader.
Manager
(formatters_namespace='bandit.formatters', plugins_namespace='bandit.plugins', blacklists_namespace='bandit.blacklists')¶ Bases:
object
-
builtin
= ['B001']¶
-
check_id
(test)¶
-
get_plugin_id
(plugin_name)¶
-
load_blacklists
(blacklist_namespace)¶
-
load_formatters
(formatters_namespace)¶
-
load_plugins
(plugins_namespace)¶
-
validate_profile
(profile)¶ Validate that everything in the configured profiles looks good.
-
bandit.core.issue module¶
-
class
bandit.core.issue.
Issue
(severity, confidence='UNDEFINED', text=u'', ident=None, lineno=None, test_id=u'')¶ Bases:
object
-
as_dict
(with_code=True)¶ Convert the issue to a dict of values for outputting.
-
filter
(severity, confidence)¶ Utility to filter on confidence and severity
This function determines whether an issue should be included by comparing the severity and confidence rating of the issue to minimum thresholds specified in ‘severity’ and ‘confidence’ respectively.
Formatters should call manager.filter_results() directly.
This will return false if either the confidence or severity of the issue are lower than the given threshold values.
Parameters: - severity – Severity threshold
- confidence – Confidence threshold
Returns: True/False depending on whether issue meets threshold
-
from_dict
(data, with_code=True)¶
-
get_code
(max_lines=3, tabbed=False)¶ Gets lines of code from a file the generated this issue.
Parameters: - max_lines – Max lines of context to return
- tabbed – Use tabbing in the output
Returns: strings of code
-
-
bandit.core.issue.
issue_from_dict
(data)¶
bandit.core.manager module¶
-
class
bandit.core.manager.
BanditManager
(config, agg_type, debug=False, verbose=False, profile=None, ignore_nosec=False)¶ Bases:
object
-
discover_files
(targets, recursive=False, excluded_paths='')¶ Add tests directly and from a directory to the test set
Parameters: - targets – The command line list of files and directories
- recursive – True/False - whether to add all files from dirs
Returns:
-
filter_results
(sev_filter, conf_filter)¶ Returns a list of results filtered by the baseline
This works by checking the number of results returned from each file we process. If the number of results is different to the number reported for the same file in the baseline, then we return all results for the file. We can’t reliably return just the new results, as line numbers will likely have changed.
Parameters: - sev_filter – severity level filter to apply
- conf_filter – confidence level filter to apply
-
get_issue_list
(sev_level='LOW', conf_level='LOW')¶
-
get_skipped
()¶
-
output_results
(lines, sev_level, conf_level, output_file, output_format, template=None)¶ Outputs results from the result store
Parameters: - lines – How many surrounding lines to show per result
- sev_level – Which severity levels to show (LOW, MEDIUM, HIGH)
- conf_level – Which confidence levels to show (LOW, MEDIUM, HIGH)
- output_file – File to store results
- output_format – output format plugin name
- template – Output template with non-terminal tags <N> (default: {abspath}:{line}: {test_id}[bandit]: {severity}: {msg})
Returns:
-
populate_baseline
(data)¶ Populate a baseline set of issues from a JSON report
This will populate a list of baseline issues discovered from a previous run of bandit. Later this baseline can be used to filter out the result set, see filter_results.
-
results_count
(sev_filter='LOW', conf_filter='LOW')¶ Return the count of results
Parameters: - sev_filter – Severity level to filter lower
- conf_filter – Confidence level to filter
Returns: Number of results in the set
-
run_tests
()¶ Runs through all files in the scope
Returns:
-
scope
= []¶
-
bandit.core.meta_ast module¶
bandit.core.metrics module¶
-
class
bandit.core.metrics.
Metrics
¶ Bases:
object
Bandit metric gathering.
This class is a singleton used to gather and process metrics collected when processing a code base with bandit. Metric collection is stateful, that is, an active metric block will be set when requested and all subsequent operations will effect that metric block until it is replaced by a setting a new one.
-
aggregate
()¶ Do final aggregation of metrics.
-
begin
(fname)¶ Begin a new metric block.
This starts a new metric collection name “fname” and makes is active.
Parameters: fname – the metrics unique name, normally the file name.
-
count_issues
(scores)¶
-
count_locs
(lines)¶ Count lines of code.
We count lines that are not empty and are not comments. The result is added to our currently active metrics loc count (normally this is 0).
Parameters: lines – lines in the file to process
-
note_nosec
(num=1)¶ Note a “nosec” commnet.
Increment the currently active metrics nosec count.
Parameters: num – number of nosecs seen, defaults to 1
-
bandit.core.node_visitor module¶
-
class
bandit.core.node_visitor.
BanditNodeVisitor
(fname, metaast, testset, debug, nosec_lines, metrics)¶ Bases:
object
-
generic_visit
(node)¶ Drive the visitor.
-
post_visit
(node)¶
-
pre_visit
(node)¶
-
process
(data)¶ Main process loop
Build and process the AST :param lines: lines code to process :return score: the aggregated score for the current file
-
update_scores
(scores)¶ Score updater
Since we moved from a single score value to a map of scores per severity, this is needed to update the stored list. :param score: The score list to update our scores with
-
visit
(node)¶
-
visit_Bytes
(node)¶ Visitor for AST Bytes nodes
add relevant information about node to the context for use in tests which inspect strings. :param node: The node that is being inspected :return: -
-
visit_Call
(node)¶ Visitor for AST Call nodes
add relevant information about the node to the context for use in tests which inspect function calls. :param node: The node that is being inspected :return: -
-
visit_ClassDef
(node)¶ Visitor for AST ClassDef node
Add class name to current namespace for all descendants. :param node: Node being inspected :return: -
-
visit_FunctionDef
(node)¶ Visitor for AST FunctionDef nodes
add relevant information about the node to the context for use in tests which inspect function definitions. Add the function name to the current namespace for all descendants. :param node: The node that is being inspected :return: -
-
visit_Import
(node)¶ Visitor for AST Import nodes
add relevant information about node to the context for use in tests which inspect imports. :param node: The node that is being inspected :return: -
-
visit_ImportFrom
(node)¶ Visitor for AST ImportFrom nodes
add relevant information about node to the context for use in tests which inspect imports. :param node: The node that is being inspected :return: -
-
visit_Str
(node)¶ Visitor for AST String nodes
add relevant information about node to the context for use in tests which inspect strings. :param node: The node that is being inspected :return: -
-
bandit.core.test_properties module¶
-
bandit.core.test_properties.
accepts_baseline
(*args)¶ Decorator to indicate formatter accepts baseline results
Use of this decorator before a formatter indicates that it is able to deal with baseline results. Specifically this means it has a way to display candidate results and know when it should do so.
-
bandit.core.test_properties.
checks
(*args)¶ Decorator function to set checks to be run.
-
bandit.core.test_properties.
takes_config
(*args)¶ Test function takes config
Use of this delegate before a test function indicates that it should be passed data from the config file. Passing a name parameter allows aliasing tests and thus sharing config options.
-
bandit.core.test_properties.
test_id
(id_val)¶ Test function identifier
Use this decorator before a test function indicates its simple ID
bandit.core.test_set module¶
bandit.core.tester module¶
-
class
bandit.core.tester.
BanditTester
(testset, debug, nosec_lines)¶ Bases:
object
-
static
report_error
(test, context, error)¶
-
run_tests
(raw_context, checktype)¶ Runs all tests for a certain type of check, for example
Runs all tests for a certain type of check, for example ‘functions’ store results in results.
Parameters: - raw_context – Raw context dictionary
- checktype – The type of checks to run
- nosec_lines – Lines which should be skipped because of nosec
Returns: a score based on the number and type of test results
-
static
bandit.core.utils module¶
-
exception
bandit.core.utils.
ConfigError
(message, config_file)¶ Bases:
exceptions.Exception
Raised when the config file fails validation.
-
exception
bandit.core.utils.
InvalidModulePath
¶ Bases:
exceptions.Exception
-
bandit.core.utils.
LOG
= <logging.Logger object>¶ Various helper functions.
-
exception
bandit.core.utils.
ProfileNotFound
(config_file, profile)¶ Bases:
exceptions.Exception
Raised when chosen profile cannot be found.
-
bandit.core.utils.
check_ast_node
(name)¶ Check if the given name is that of a valid AST node.
-
bandit.core.utils.
concat_string
(node, stop=None)¶ Builds a string from a ast.BinOp chain.
This will build a string from a series of ast.Str nodes wrapped in ast.BinOp nodes. Something like “a” + “b” + “c” or “a %s” % val etc. The provided node can be any participant in the BinOp chain.
Parameters: - node – (ast.Str or ast.BinOp) The node to process
- stop – (ast.Str or ast.BinOp) Optional base node to stop at
Returns: (Tuple) the root node of the expression, the string value
-
bandit.core.utils.
deepgetattr
(obj, attr)¶ Recurses through an attribute chain to get the ultimate value.
-
bandit.core.utils.
escaped_bytes_representation
(b)¶ PY3 bytes need escaping for comparison with other strings.
In practice it turns control characters into acceptable codepoints then encodes them into bytes again to turn unprintable bytes into printable escape sequences.
This is safe to do for the whole range 0..255 and result matches unicode_escape on a unicode string.
-
bandit.core.utils.
get_call_name
(node, aliases)¶
-
bandit.core.utils.
get_called_name
(node)¶ Get a function name from an ast.Call node.
An ast.Call node representing a method call with present differently to one wrapping a function call: thing.call() vs call(). This helper will grab the unqualified call name correctly in either case.
Parameters: node – (ast.Call) the call node Returns: (String) the function name
-
bandit.core.utils.
get_func_name
(node)¶
-
bandit.core.utils.
get_module_qualname_from_path
(path)¶ Get the module’s qualified name by analysis of the path.
Resolve the absolute pathname and eliminate symlinks. This could result in an incorrect name if symlinks are used to restructure the python lib directory.
Starting from the right-most directory component look for __init__.py in the directory component. If it exists then the directory name is part of the module name. Move left to the subsequent directory components until a directory is found without __init__.py.
Param: Path to module file. Relative paths will be resolved relative to current working directory. Returns: fully qualified module name
-
bandit.core.utils.
get_path_for_function
(f)¶ Get the path of the file where the function is defined.
Returns: the path, or None if one could not be found or f is not a real function
-
bandit.core.utils.
get_qual_attr
(node, aliases)¶
-
bandit.core.utils.
linerange
(node)¶ Get line number range from a node.
-
bandit.core.utils.
linerange_fix
(node)¶ Try and work around a known Python bug with multi-line strings.
-
bandit.core.utils.
namespace_path_join
(base, name)¶ Extend the current namespace path with an additional name
Take a namespace path (i.e., package.module.class) and extends it with an additional name (i.e., package.module.class.subclass). This is similar to how os.path.join works.
Parameters: - base – (String) The base namespace path.
- name – (String) The new name to append to the base path.
Returns: (String) A new namespace path resulting from combination of base and name.
-
bandit.core.utils.
namespace_path_split
(path)¶ Split the namespace path into a pair (head, tail).
Tail will be the last namespace path component and head will be everything leading up to that in the path. This is similar to os.path.split.
Parameters: path – (String) A namespace path. Returns: (String, String) A tuple where the first component is the base path and the second is the last path component.
-
bandit.core.utils.
parse_ini_file
(f_loc)¶
-
bandit.core.utils.
warnings_formatter
(message, category=<type 'exceptions.UserWarning'>, filename='', lineno=-1, line='')¶ Monkey patch for warnings.warn to suppress cruft output.