0
# Core Management
1
2
Central scanning orchestration and configuration management for Bandit security analysis. The core management system coordinates file discovery, test execution, result filtering, and configuration handling.
3
4
## Capabilities
5
6
### BanditManager
7
8
Main orchestrator for security scanning operations. Manages the complete workflow from file discovery through test execution to result filtering and reporting.
9
10
```python { .api }
11
class BanditManager:
12
def __init__(self, config, agg_type, debug=False, verbose=False, quiet=False, profile=None, ignore_nosec=False):
13
"""
14
Initialize bandit manager.
15
16
Parameters:
17
- config: BanditConfig instance with scanning configuration
18
- agg_type: str, aggregation type ('file' or 'vuln')
19
- debug: bool, enable debug logging
20
- verbose: bool, enable verbose output
21
- quiet: bool, suppress output
22
- profile: dict, test profile configuration
23
- ignore_nosec: bool, ignore # nosec comments
24
"""
25
26
def discover_files(self, targets, recursive=False, excluded_paths=""):
27
"""
28
Discover Python files to scan.
29
30
Parameters:
31
- targets: list, target files or directories
32
- recursive: bool, scan directories recursively
33
- excluded_paths: str, comma-separated paths to exclude
34
35
Returns:
36
list: Discovered Python file paths
37
"""
38
39
def run_tests(self):
40
"""
41
Execute security tests on discovered files.
42
Runs all enabled security test plugins against discovered files.
43
"""
44
45
def get_issue_list(self, sev_level='LOW', conf_level='LOW'):
46
"""
47
Get filtered list of security issues.
48
49
Parameters:
50
- sev_level: str, minimum severity level ('LOW', 'MEDIUM', 'HIGH')
51
- conf_level: str, minimum confidence level ('LOW', 'MEDIUM', 'HIGH')
52
53
Returns:
54
list: List of Issue objects meeting criteria
55
"""
56
57
def output_results(self, lines, sev_level, conf_level, output_file, output_format, template=None):
58
"""
59
Output results using specified formatter.
60
61
Parameters:
62
- lines: int, lines of code context to show per result
63
- sev_level: str, minimum severity level to include
64
- conf_level: str, minimum confidence level to include
65
- output_file: file object, where to write output
66
- output_format: str, formatter name ('json', 'xml', 'screen', etc.)
67
- template: str, custom template for 'custom' formatter
68
"""
69
70
def results_count(self, sev_filter='LOW', conf_filter='LOW'):
71
"""
72
Count results matching severity and confidence filters.
73
74
Parameters:
75
- sev_filter: str, minimum severity level
76
- conf_filter: str, minimum confidence level
77
78
Returns:
79
int: Number of matching results
80
"""
81
82
def populate_baseline(self, data):
83
"""
84
Load baseline issues from JSON data.
85
86
Parameters:
87
- data: dict, baseline data from JSON file
88
"""
89
90
def filter_results(self, sev_level, conf_level):
91
"""
92
Filter results by severity and confidence levels.
93
94
Parameters:
95
- sev_level: str, minimum severity level
96
- conf_level: str, minimum confidence level
97
"""
98
99
def get_skipped(self):
100
"""
101
Get list of skipped files with reasons.
102
103
Returns:
104
list: Skipped files and skip reasons
105
"""
106
```
107
108
### BanditConfig
109
110
Configuration management for security scanning profiles, test selection, and scanning options. Supports YAML configuration files with validation and legacy config conversion.
111
112
```python { .api }
113
class BanditConfig:
114
def __init__(self, config_file=None):
115
"""
116
Initialize configuration from file or defaults.
117
118
Parameters:
119
- config_file: str, path to YAML configuration file (optional)
120
"""
121
122
def get_option(self, option_string):
123
"""
124
Retrieve configuration option using dot notation.
125
126
Parameters:
127
- option_string: str, option path like 'tests.B101.skip'
128
129
Returns:
130
Configuration value or None
131
"""
132
133
def get_setting(self, setting_name):
134
"""
135
Get specific setting value.
136
137
Parameters:
138
- setting_name: str, setting name
139
140
Returns:
141
Setting value or default
142
"""
143
144
def convert_legacy_config(self):
145
"""
146
Convert old format config to new format.
147
Transforms legacy configuration structure to current format.
148
"""
149
150
def validate(self, path):
151
"""
152
Validate configuration file.
153
154
Parameters:
155
- path: str, path to configuration file
156
157
Returns:
158
bool: True if valid, raises ConfigError if invalid
159
"""
160
161
@property
162
def config(self):
163
"""
164
Access to internal configuration dictionary.
165
166
Returns:
167
dict: Internal configuration data
168
"""
169
```
170
171
## Usage Examples
172
173
### Basic Scanning Workflow
174
175
```python
176
from bandit.core import manager, config
177
178
# Create configuration with defaults
179
conf = config.BanditConfig()
180
181
# Create manager for file-based aggregation
182
b_mgr = manager.BanditManager(conf, 'file', verbose=True)
183
184
# Discover Python files in project
185
files = b_mgr.discover_files(['/path/to/project'], recursive=True)
186
print(f"Found {len(files)} Python files")
187
188
# Run security tests
189
b_mgr.run_tests()
190
191
# Get high-severity issues
192
high_issues = b_mgr.get_issue_list(sev_level='HIGH', conf_level='MEDIUM')
193
194
for issue in high_issues:
195
print(f"{issue.fname}:{issue.lineno} - {issue.text}")
196
print(f" Severity: {issue.severity}, Confidence: {issue.confidence}")
197
print(f" Test ID: {issue.test_id}, CWE: {issue.cwe}")
198
```
199
200
### Configuration File Usage
201
202
```python
203
from bandit.core import config, manager
204
205
# Load configuration from YAML file
206
conf = config.BanditConfig('/path/to/bandit.yaml')
207
208
# Access specific configuration options
209
skip_tests = conf.get_option('skips')
210
test_config = conf.get_option('tests.B101')
211
212
# Create manager with configuration
213
b_mgr = manager.BanditManager(conf, 'file')
214
```
215
216
### Custom Profile Configuration
217
218
```python
219
# Define custom test profile
220
custom_profile = {
221
'include': ['B101', 'B102', 'B601'],
222
'exclude': ['B404', 'B603']
223
}
224
225
# Create manager with profile
226
b_mgr = manager.BanditManager(conf, 'file', profile=custom_profile)
227
```
228
229
## Exception Handling
230
231
```python { .api }
232
class ConfigError(Exception):
233
"""Raised when configuration file fails validation."""
234
def __init__(self, message, config_file):
235
"""
236
Parameters:
237
- message: str, error description
238
- config_file: str, path to problematic config file
239
"""
240
241
class ProfileNotFound(Exception):
242
"""Raised when specified profile cannot be found in configuration."""
243
def __init__(self, config_file, profile):
244
"""
245
Parameters:
246
- config_file: str, path to config file
247
- profile: str, name of missing profile
248
"""
249
250
class InvalidModulePath(Exception):
251
"""Raised when module path is invalid or cannot be resolved."""
252
```
253
254
Common configuration validation errors include invalid YAML syntax, unknown test IDs, and malformed profile definitions.