0
# Bandit
1
2
A security-oriented static analysis tool designed to find common security issues in Python code. Bandit processes AST representations of Python source code and runs security-focused plugins against AST nodes to identify potential vulnerabilities including hardcoded passwords, SQL injection, shell injection, and weak cryptographic implementations.
3
4
## Package Information
5
6
- **Package Name**: bandit
7
- **Language**: Python
8
- **Installation**: `pip install bandit`
9
- **Extra dependencies**: `pip install bandit[yaml,toml,baseline,sarif]` for additional features
10
11
## Core Imports
12
13
```python
14
import bandit
15
from bandit.core import manager, config, context, issue
16
```
17
18
For CLI usage:
19
```python
20
from bandit.cli import main
21
```
22
23
For programmatic usage:
24
```python
25
from bandit.core.manager import BanditManager
26
from bandit.core.config import BanditConfig
27
```
28
29
## Basic Usage
30
31
### Command Line Interface
32
33
```bash
34
# Scan a single file
35
bandit example.py
36
37
# Scan a directory recursively
38
bandit -r /path/to/project
39
40
# Generate JSON report
41
bandit -r /path/to/project -f json -o report.json
42
43
# Exclude specific tests
44
bandit -r /path/to/project --skip B101,B601
45
46
# Use baseline to ignore existing issues
47
bandit-baseline -r /path/to/project -o baseline.json
48
bandit -r /path/to/project -b baseline.json
49
```
50
51
### Programmatic Usage
52
53
```python
54
from bandit.core import manager, config
55
56
# Create configuration
57
conf = config.BanditConfig()
58
59
# Create manager
60
b_mgr = manager.BanditManager(conf, 'file')
61
62
# Discover and scan files
63
b_mgr.discover_files(['/path/to/code'])
64
b_mgr.run_tests()
65
66
# Get filtered results
67
issues = b_mgr.get_issue_list(sev_level='MEDIUM', conf_level='HIGH')
68
69
# Print results
70
for issue in issues:
71
print(f"{issue.fname}:{issue.lineno} - {issue.text}")
72
```
73
74
## Architecture
75
76
Bandit's plugin-based architecture enables extensible security analysis:
77
78
- **Core Manager**: Central orchestrator (`BanditManager`) that coordinates scanning workflow
79
- **Configuration System**: YAML-based configuration with profile support (`BanditConfig`)
80
- **Context Analysis**: AST node analysis providing call context and import tracking (`Context`)
81
- **Plugin System**: 60+ built-in security tests with decorator-based registration system
82
- **Issue Management**: Structured vulnerability reporting with CWE mapping (`Issue`, `Cwe`)
83
- **Multiple Output Formats**: JSON, XML, HTML, SARIF, CSV, YAML formatters for CI/CD integration
84
85
## Capabilities
86
87
### Core Management
88
89
Central scanning orchestration and configuration management. The BanditManager coordinates file discovery, test execution, and result filtering, while BanditConfig handles YAML configuration files and scanning profiles.
90
91
```python { .api }
92
class BanditManager:
93
def __init__(self, config, agg_type, debug=False, verbose=False, quiet=False, profile=None, ignore_nosec=False): ...
94
def discover_files(self, targets, recursive=False): ...
95
def run_tests(self): ...
96
def get_issue_list(self, sev_level='LOW', conf_level='LOW'): ...
97
98
class BanditConfig:
99
def __init__(self, config_file=None): ...
100
def get_option(self, option_string): ...
101
def get_setting(self, setting_name): ...
102
```
103
104
[Core Management](./core-management.md)
105
106
### Issue Reporting
107
108
Comprehensive security issue representation with Common Weakness Enumeration (CWE) support. Issues include severity levels, confidence ratings, source code context, and structured metadata for integration with security tools.
109
110
```python { .api }
111
class Issue:
112
def __init__(self, severity, cwe=0, confidence='UNDEFINED', text="", ident=None, lineno=None, test_id="", col_offset=-1, end_col_offset=0): ...
113
def filter(self, severity, confidence): ...
114
def get_code(self, max_lines=3, tabbed=False): ...
115
def as_dict(self, with_code=True, max_lines=3): ...
116
117
class Cwe:
118
def __init__(self, id=999): ...
119
def link(self): ...
120
def as_dict(self): ...
121
```
122
123
[Issue Reporting](./issue-reporting.md)
124
125
### Context Analysis
126
127
AST node analysis and import tracking during security test execution. Context provides access to function call information, string literals, and module import patterns essential for accurate vulnerability detection.
128
129
```python { .api }
130
class Context:
131
def __init__(self, context_object=None): ...
132
@property
133
def call_function_name(self): ...
134
@property
135
def call_function_name_qual(self): ...
136
@property
137
def call_args(self): ...
138
@property
139
def call_keywords(self): ...
140
def is_module_being_imported(self, module): ...
141
```
142
143
[Context Analysis](./context-analysis.md)
144
145
### Plugin Development
146
147
Framework for creating custom security tests using decorators and the plugin registration system. Supports AST node type filtering, configuration integration, and test identification.
148
149
```python { .api }
150
def checks(*args): ...
151
def test_id(id_val): ...
152
def takes_config(name=None): ...
153
def accepts_baseline(*args): ...
154
```
155
156
[Plugin Development](./plugin-development.md)
157
158
### Output Formatters
159
160
Multiple report formats for different use cases and CI/CD integration. Formatters support severity filtering, confidence thresholds, and baseline comparison for security reporting workflows.
161
162
```python { .api }
163
def report(manager, fileobj, sev_level, conf_level, lines): ...
164
```
165
166
Available formatters: JSON, XML, HTML, SARIF, CSV, YAML, screen, custom template-based
167
168
[Output Formatters](./output-formatters.md)
169
170
### Command Line Tools
171
172
Three CLI utilities for security scanning, configuration management, and baseline handling in development and CI/CD environments.
173
174
```bash { .api }
175
bandit [options] targets...
176
bandit-config-generator [options]
177
bandit-baseline [options] targets...
178
```
179
180
[Command Line Tools](./command-line-tools.md)
181
182
### Extension Management
183
184
Plugin system management for loading and validating security tests, formatters, and blacklist handlers. Provides centralized plugin registry and validation.
185
186
```python { .api }
187
class Manager:
188
def __init__(self, formatters_namespace="bandit.formatters", plugins_namespace="bandit.plugins", blacklists_namespace="bandit.blacklists"): ...
189
def load_formatters(self, formatters_namespace): ...
190
def load_plugins(self, plugins_namespace): ...
191
def validate_profile(self, profile): ...
192
def get_plugin_by_id(self, plugin_id): ...
193
194
# Global plugin manager instance
195
MANAGER = ... # Available from bandit.core.extension_loader
196
```
197
198
### Utility Functions
199
200
AST analysis and code inspection utilities for security test development and advanced usage.
201
202
```python { .api }
203
def get_call_name(node, aliases): ... # Extract function call name with alias resolution
204
def get_func_name(node): ... # Get function name from AST node
205
def get_qual_attr(node, aliases): ... # Get qualified attribute with aliases
206
def deepgetattr(obj, attr): ... # Deep attribute access with dot notation
207
def check_ast_node(node_type): ... # Validate AST node type
208
```
209
210
## Constants
211
212
```python { .api }
213
# Severity and confidence levels
214
HIGH = "HIGH"
215
MEDIUM = "MEDIUM"
216
LOW = "LOW"
217
UNDEFINED = "UNDEFINED"
218
219
# Ranking values for filtering
220
RANKING_VALUES = {
221
"UNDEFINED": 1,
222
"LOW": 3,
223
"MEDIUM": 5,
224
"HIGH": 10
225
}
226
227
# File exclusion patterns
228
EXCLUDE = (".svn", "CVS", ".bzr", ".hg", ".git", "__pycache__", ".tox", ".eggs", "*.egg")
229
230
# Values considered false in static analysis
231
FALSE_VALUES = [None, False, "False", 0, 0.0, 0j, "", (), [], {}]
232
233
# Default confidence level
234
CONFIDENCE_DEFAULT = "UNDEFINED"
235
```