Security oriented static analyser for python code.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Central scanning orchestration and configuration management for Bandit security analysis. The core management system coordinates file discovery, test execution, result filtering, and configuration handling.
Main orchestrator for security scanning operations. Manages the complete workflow from file discovery through test execution to result filtering and reporting.
class BanditManager:
def __init__(self, config, agg_type, debug=False, verbose=False, quiet=False, profile=None, ignore_nosec=False):
"""
Initialize bandit manager.
Parameters:
- config: BanditConfig instance with scanning configuration
- agg_type: str, aggregation type ('file' or 'vuln')
- debug: bool, enable debug logging
- verbose: bool, enable verbose output
- quiet: bool, suppress output
- profile: dict, test profile configuration
- ignore_nosec: bool, ignore # nosec comments
"""
def discover_files(self, targets, recursive=False, excluded_paths=""):
"""
Discover Python files to scan.
Parameters:
- targets: list, target files or directories
- recursive: bool, scan directories recursively
- excluded_paths: str, comma-separated paths to exclude
Returns:
list: Discovered Python file paths
"""
def run_tests(self):
"""
Execute security tests on discovered files.
Runs all enabled security test plugins against discovered files.
"""
def get_issue_list(self, sev_level='LOW', conf_level='LOW'):
"""
Get filtered list of security issues.
Parameters:
- sev_level: str, minimum severity level ('LOW', 'MEDIUM', 'HIGH')
- conf_level: str, minimum confidence level ('LOW', 'MEDIUM', 'HIGH')
Returns:
list: List of Issue objects meeting criteria
"""
def output_results(self, lines, sev_level, conf_level, output_file, output_format, template=None):
"""
Output results using specified formatter.
Parameters:
- lines: int, lines of code context to show per result
- sev_level: str, minimum severity level to include
- conf_level: str, minimum confidence level to include
- output_file: file object, where to write output
- output_format: str, formatter name ('json', 'xml', 'screen', etc.)
- template: str, custom template for 'custom' formatter
"""
def results_count(self, sev_filter='LOW', conf_filter='LOW'):
"""
Count results matching severity and confidence filters.
Parameters:
- sev_filter: str, minimum severity level
- conf_filter: str, minimum confidence level
Returns:
int: Number of matching results
"""
def populate_baseline(self, data):
"""
Load baseline issues from JSON data.
Parameters:
- data: dict, baseline data from JSON file
"""
def filter_results(self, sev_level, conf_level):
"""
Filter results by severity and confidence levels.
Parameters:
- sev_level: str, minimum severity level
- conf_level: str, minimum confidence level
"""
def get_skipped(self):
"""
Get list of skipped files with reasons.
Returns:
list: Skipped files and skip reasons
"""Configuration management for security scanning profiles, test selection, and scanning options. Supports YAML configuration files with validation and legacy config conversion.
class BanditConfig:
def __init__(self, config_file=None):
"""
Initialize configuration from file or defaults.
Parameters:
- config_file: str, path to YAML configuration file (optional)
"""
def get_option(self, option_string):
"""
Retrieve configuration option using dot notation.
Parameters:
- option_string: str, option path like 'tests.B101.skip'
Returns:
Configuration value or None
"""
def get_setting(self, setting_name):
"""
Get specific setting value.
Parameters:
- setting_name: str, setting name
Returns:
Setting value or default
"""
def convert_legacy_config(self):
"""
Convert old format config to new format.
Transforms legacy configuration structure to current format.
"""
def validate(self, path):
"""
Validate configuration file.
Parameters:
- path: str, path to configuration file
Returns:
bool: True if valid, raises ConfigError if invalid
"""
@property
def config(self):
"""
Access to internal configuration dictionary.
Returns:
dict: Internal configuration data
"""from bandit.core import manager, config
# Create configuration with defaults
conf = config.BanditConfig()
# Create manager for file-based aggregation
b_mgr = manager.BanditManager(conf, 'file', verbose=True)
# Discover Python files in project
files = b_mgr.discover_files(['/path/to/project'], recursive=True)
print(f"Found {len(files)} Python files")
# Run security tests
b_mgr.run_tests()
# Get high-severity issues
high_issues = b_mgr.get_issue_list(sev_level='HIGH', conf_level='MEDIUM')
for issue in high_issues:
print(f"{issue.fname}:{issue.lineno} - {issue.text}")
print(f" Severity: {issue.severity}, Confidence: {issue.confidence}")
print(f" Test ID: {issue.test_id}, CWE: {issue.cwe}")from bandit.core import config, manager
# Load configuration from YAML file
conf = config.BanditConfig('/path/to/bandit.yaml')
# Access specific configuration options
skip_tests = conf.get_option('skips')
test_config = conf.get_option('tests.B101')
# Create manager with configuration
b_mgr = manager.BanditManager(conf, 'file')# Define custom test profile
custom_profile = {
'include': ['B101', 'B102', 'B601'],
'exclude': ['B404', 'B603']
}
# Create manager with profile
b_mgr = manager.BanditManager(conf, 'file', profile=custom_profile)class ConfigError(Exception):
"""Raised when configuration file fails validation."""
def __init__(self, message, config_file):
"""
Parameters:
- message: str, error description
- config_file: str, path to problematic config file
"""
class ProfileNotFound(Exception):
"""Raised when specified profile cannot be found in configuration."""
def __init__(self, config_file, profile):
"""
Parameters:
- config_file: str, path to config file
- profile: str, name of missing profile
"""
class InvalidModulePath(Exception):
"""Raised when module path is invalid or cannot be resolved."""Common configuration validation errors include invalid YAML syntax, unknown test IDs, and malformed profile definitions.
Install with Tessl CLI
npx tessl i tessl/pypi-bandit