Bandit Documentation
repository·main·Indexed 27 days ago
https://github.com/pycqa/banditA security linter for Python that identifies common security vulnerabilities by analyzing the Abstract Syntax Tree (AST) of source code. It includes a CLI for scanning files, a baseline tool for comparing findings between Git commits, and a configuration generator for creating profiles to include or skip specific tests.
What's inside Bandit
- Bandit is a security linter designed to find common security issues in Python code. It works by processing each file, building an Abstract Syntax Tree (AST), and running specialized plugins against the AST nodes to identify vulnerabilities. After scanning the files, it generates a report of the findings.
Overview of Bandit security scanning
mainBandit is a security tool for Python that identifies common security vulnerabilities. It works by processing Python files, building an Abstract Syntax Tree (AST) for each, and executing specialized plugins against the AST nodes. After the scan is complete, Bandit generates a report summarizing the findings.Register a custom Bandit formatter plugin via pbr
mainIf you are using
pbr, register your formatter in yoursetup.cfgfile under the[entry_points]section using thebandit.formatterskey.[entry_points] bandit.formatters = bson = bandit_bson:formatterUse the B101: assert_used plugin
mainTheB101: assert_usedplugin detects the use of theassertstatement in Python code. In Python,assertstatements can be optimized away when the code is run with optimizations (e.g., using the-Oflag), which can lead to security vulnerabilities if the assertion is used for critical logic or security checks. This plugin flags these instances to encourage developers to use explicit error handling instead.Implement Blacklist Plugins
mainBandit allows extending its security checks by implementing blacklist plugins for imports and function calls. These plugins are discovered at startup via the
bandit.blacklistsentry point.By convention:
- Blacklisted calls should use IDs in the
B3xxrange. - Blacklisted imports should use IDs in the
B4xxrange.
Plugin functions must return a dictionary mapping AST node types to lists of blacklist data. Supported node types are:
Call: For blacklisting function calls.Import: For blacklisting module imports (this also coversImportFromand calls to the built-in__import__()method).
To simplify implementation, use the utility method
bandit.blacklists.utils.build_conf_dictto construct the required data dictionaries.- Blacklisted calls should use IDs in the
Run Bandit scans
mainUse the
banditcommand to scan Python code. You can scan specific files, entire directories recursively, or use standard input.Common flags:
-r: Recursive scan.-n <number>: Show N lines of context.--severity-level=<level>: Filter by severity (e.g.,high).-lll: Shorthand for high severity.-p <profile>: Run using a specific plugin profile (e.g.,ShellInjection).-h: Show help information.
Use Bandit with Linters (Ruff and Flake8)
mainYou can incorporate Bandit's security checks into existing Python linting workflows:
- Ruff: Use the
flake8-bandit (S)rule set. - Flake8: Use the
flake8-banditplugin.
- Ruff: Use the
Detect insecure hashlib functions with B324
mainBandit includes a plugin (B324) that scans for the use of insecure hash functions within thehashlibmodule. This plugin identifies calls to functions that are known to be cryptographically broken or weak, such asmd5orsha1, which should not be used for security-sensitive purposes like password hashing or digital signatures.Integrate Bandit with IDEs
mainBandit can be used within various code editors via plugins to provide real-time security linting. Supported IDE integrations include:
- Visual Studio Code: Use
Bandit by PyCQA. - Sublime Text: Use
SublimeLinter-bandit. - Vim/Neovim: Use
Asynchronous Lint Engine (ALE). - Emacs: Use
flycheck-pycheckers.
- Visual Studio Code: Use
Write a custom Bandit test plugin
mainTo extend Bandit's security detection capabilities, you can create custom test plugins.
Follow these steps:
- Create a test case: Add a Python file to an
examples/directory containing the vulnerability you want to detect. - Implement the test function: Create a Python source file containing a function that accepts a
contextparameter. Thecontextobject allows you to query the element being examined or access the raw AST node. - Decorate the function: Use
@bandit.checksdecorators to specify which AST nodes the plugin should target:@bandit.checks('Call')@bandit.checks('Import', 'ImportFrom')@bandit.checks('Str')
- Return an Issue: If a vulnerability is found, return a
bandit.Issueobject specifyingseverity,confidence, andtext. - Register the plugin: Use the
bandit.pluginsentry point (see registration guide). - Verify: Run Bandit against your example file to ensure the vulnerability is detected.
@bandit.checks('Call') def prohibit_unsafe_deserialization(context): if 'unsafe_load' in context.call_function_name_qual: return bandit.Issue( severity=bandit.HIGH, confidence=bandit.HIGH, text="Unsafe deserialization detected." )- Create a test case: Add a Python file to an
Register a Bandit plugin via entry points
mainTo make your plugin discoverable by Bandit, you must register it using entry points in your packaging configuration.
Using setuptools (
setup.py): Add theentry_pointsargument to yoursetup()call.Using pbr (
setup.cfg): Add the plugin under the[entry_points]section.# Using setuptools in setup.py setup( # ... entry_points={'bandit.plugins': ['mako = bandit_mako']} )# Using pbr in setup.cfg [entry_points] bandit.plugins = mako = bandit_makoSelect the correct Python version for running Bandit
mainWhen choosing which Python version to use for running Bandit, select the version that matches the Python version of the project you are analyzing.
Bandit relies on the standard library's
astmodule to parse code. Because theastmodule can only parse syntax valid for the specific interpreter version it is running under, using an older Python version to analyze code written for a newer version will result in syntax errors.Guidelines:
- If your project is compatible only with Python 3.9, install and run Bandit under Python 3.9.
- If your project is compatible only with Python 3.10, run Bandit under Python 3.10.
- If your project supports multiple versions, you may run Bandit under any of those supported versions.