### Install Bandit from source using setup.py Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Install Bandit by cloning the repository and running its `setup.py` script directly. ```console python setup.py install ``` -------------------------------- ### Install Bandit from Source Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Methods for installing Bandit directly from its source code, either by cloning the repository or downloading a tarball, and using setup.py or pip. ```console python setup.py install ``` ```console pip install git+https://github.com/PyCQA/bandit#egg=bandit ``` -------------------------------- ### Install Bandit with Virtual Environment Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Instructions for creating and activating a virtual environment using virtualenv or venv, followed by installing Bandit using pip. ```console virtualenv bandit-env source bandit-env/bin/activate ``` ```console python3 -m venv bandit-env source bandit-env/bin/activate ``` -------------------------------- ### Install Bandit from Git repository via pip Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Install Bandit directly from its GitHub repository using pip, which handles cloning and installation. ```console pip install git+https://github.com/PyCQA/bandit#egg=bandit ``` -------------------------------- ### Install Bandit with Pip Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Installs Bandit using pip, including optional extras for TOML support, baseline CLI, and SARIF output formatter. ```console pip install bandit ``` ```console pip install bandit[toml] ``` ```console pip install bandit[baseline] ``` ```console pip install bandit[sarif] ``` -------------------------------- ### Bandit Example Usage Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst Provides an example of how to run Bandit recursively across a code tree to scan for security issues. ```bash bandit -r ~/your-repos/project ``` -------------------------------- ### Registering Bandit Plugins with Setuptools Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/index.rst Demonstrates how to register Bandit plugins and formatters using the `entry_points` argument in a `setup` call when using setuptools directly. ```python entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']} entry_points={'bandit.plugins': ['mako = bandit_mako']} ``` -------------------------------- ### Run Bandit Command Examples Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Demonstrates various ways to run Bandit, including recursive scanning, context lines, severity levels, profiles, and standard input. ```console bandit -r path/to/your/code ``` ```console bandit examples/*.py -n 3 --severity-level=high ``` ```console bandit examples/*.py -n 3 -lll ``` ```console bandit examples/*.py -p ShellInjection ``` ```console cat examples/imports.py | bandit - ``` ```console bandit -h ``` -------------------------------- ### Scan a project directory with Bandit Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Example of running Bandit recursively on a user's project directory. ```console bandit -r ~/your_repos/project ``` -------------------------------- ### Example Blacklist Issue Report Source: https://github.com/pycqa/bandit/blob/main/doc/source/blacklists/index.rst An example of how an issue detected by a blacklist plugin might be reported, including the issue ID, description, severity, confidence, and location in the code. ```none >> Issue: [B317:blacklist] Using xml.sax.parse to parse untrusted XML data is known to be vulnerable to XML attacks. Replace xml.sax.parse with its defusedxml equivalent function. Severity: Medium Confidence: High Location: ./examples/xml_sax.py:24 23 sax.parseString(xmlString, ExampleContentHandler()) 24 sax.parse('notaxmlfilethatexists.xml', ExampleContentHandler) ``` -------------------------------- ### Bandit B111 Example Issue Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/b111_execute_with_run_as_root_equals_true.rst This example demonstrates the output format when the Bandit B111 plugin identifies a potential security issue due to a function call with 'run_as_root=True'. It shows the issue type, severity, confidence, and the specific line of code. ```none >> Issue: Execute with run_as_root=True identified, possible security issue. Severity: Low Confidence: Medium Location: ./examples/exec-as-root.py:26 25 nova_utils.trycmd('gcc --version') 26 nova_utils.trycmd('gcc --version', run_as_root=True) 27 ``` -------------------------------- ### Pre-commit Configuration for Bandit Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a pre-commit hook configuration to run Bandit, specifying a configuration file and additional dependencies. ```yaml repos: - repo: https://github.com/PyCQA/bandit rev: '' # Update me! hooks: - id: bandit args: ["-c", "pyproject.toml"] additional_dependencies: ["bandit[toml]"] ``` -------------------------------- ### Example Git Commit Message Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md An example of a well-formed Git commit message following best practices. It includes a concise summary line, a detailed body explaining the 'why' behind the change, and issue references. ```git Summarize changes in around 50 characters or less More detailed explanatory text, if necessary. Wrap it to about 72 characters or so. In some contexts, the first line is treated as the subject of the commit and the rest of the text as the body. The blank line separating the summary from the body is critical (unless you omit the body entirely); various tools like `log`, `shortlog` and `rebase` can get confused if you run the two together. Explain the problem that this commit is solving. Focus on why you are making this change as opposed to how (the code explains that). Are there side effects or other unintuitive consequences of this change? Here's the place to explain them. Further paragraphs come after blank lines. - Bullet points are okay, too - Typically a hyphen or asterisk is used for the bullet, preceded by a single space, with blank lines in between, but conventions vary here If you use an issue tracker, put references to them at the bottom, like this: Resolves: #123 See also: #456, #789 ``` -------------------------------- ### Clone Bandit Repository Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md Clone the Bandit repository to your local machine to start contributing. This involves forking the repository and then cloning your fork. ```shell git clone https://github.com//bandit.git ``` -------------------------------- ### Run Bandit with Standard Input Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst This example demonstrates how to pipe Python code directly to Bandit for scanning using standard input. The 'imports.py' file from the 'examples/' directory is used as input. ```bash cat examples/imports.py | bandit - ``` -------------------------------- ### Install Bandit via Docker Source: https://github.com/pycqa/bandit/blob/main/README.rst This snippet shows how to pull the Bandit Docker image from ghcr.io. It also demonstrates how to pull an image for a specific architecture. ```console docker pull ghcr.io/pycqa/bandit/bandit ``` ```console docker pull --platform= ghcr.io/pycqa/bandit/bandit:latest ``` -------------------------------- ### Bandit Custom Formatting Example Usage Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst Illustrates the usage of custom message templates with Bandit, showing how to format output using various tags and Python's string formatting capabilities. ```APIDOC CUSTOM FORMATTING: Available tags: {abspath}, {relpath}, {line}, {test_id}, {severity}, {msg}, {confidence}, {range} Example usage: Default template: bandit -r examples/ --format custom --msg-template \ "{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}" Provides same output as: bandit -r examples/ --format custom Tags can also be formatted in python string.format() style: bandit -r examples/ --format custom --msg-template \ "{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}" See python documentation for more information about formatting style: https://docs.python.org/3/library/string.html ``` -------------------------------- ### Bandit Configuration via YAML File Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a YAML configuration file for Bandit, specifying excluded directories, tests to run, and tests to skip. ```yaml # FILE: bandit.yaml exclude_dirs: ['tests', 'path/to/file'] tests: ['B201', 'B301'] skips: ['B101', 'B601'] ``` -------------------------------- ### Bandit Configuration via INI File Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a .bandit INI file to configure Bandit, specifying directories to exclude and tests to run. ```ini # FILE: .bandit [bandit] exclude = tests,path/to/file tests = B201,B301 skips = B101,B601 ``` -------------------------------- ### Example Bandit Test Plugin Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/index.rst A complete example of a Bandit test plugin function that detects unsafe deserialization. It uses the `@bandit.checks('Call')` decorator and returns a `bandit.Issue` object with severity and confidence levels. ```python @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." ) ``` -------------------------------- ### Bandit Configuration with pyproject.toml Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a Bandit configuration file using the pyproject.toml format. It demonstrates how to specify excluded directories, tests to run, skips, and lists of functions related to shell execution and subprocesses. ```toml [tool.bandit] exclude_dirs = ["tests", "path/to/file"] tests = ["B201", "B301"] skips = ["B101", "B601"] [tool.bandit.any_other_function_with_shell_equals_true] no_shell = [ "os.execl", "os.execle", "os.execlp", "os.execlpe", "os.execv", "os.execve", "os.execvp", "os.execvpe", "os.spawnl", "os.spawnle", "os.spawnlp", "os.spawnlpe", "os.spawnv", "os.spawnve", "os.spawnvp", "os.spawnvpe", "os.startfile" ] shell = [ "os.system", "os.popen", "os.popen2", "os.popen3", "os.popen4", "popen2.popen2", "popen2.popen3", "popen2.popen4", "popen2.Popen3", "popen2.Popen4", "commands.getoutput", "commands.getstatusoutput" ] subprocess = [ "subprocess.Popen", "subprocess.call", "subprocess.check_call", "subprocess.check_output" ] ``` -------------------------------- ### Bandit Configuration via TOML File Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a TOML configuration file (e.g., pyproject.toml) for Bandit, specifying excluded directories, tests to run, and tests to skip. ```toml # FILE: pyproject.toml [tool.bandit] exclude_dirs = ["tests", "path/to/file"] tests = ["B201", "B301"] skips = ["B101", "B601"] ``` -------------------------------- ### Bandit Configuration with Test Selection and Overrides Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example YAML configuration for Bandit, showing how to specify included tests, skipped tests, and override plugin settings. ```yaml ### profile may optionally select or skip tests exclude_dirs: ['tests', 'path/to/file'] # (optional) list included tests here: tests: ['B201', 'B301'] # (optional) list skipped tests here: skips: ['B101', 'B601'] ### override settings - used to set settings for plugins to non-default values any_other_function_with_shell_equals_true: no_shell: [os.execl, os.execle, os.execlp, os.execlpe, os.execv, os.execve, os.execvp, os.execvpe, os.spawnl, os.spawnle, os.spawnlp, os.spawnlpe, os.spawnv, os.spawnve, os.spawnvp, os.spawnvpe, os.startfile] shell: [os.system, os.popen, os.popen2, os.popen3, os.popen4, popen2.popen2, popen2.popen3, popen2.popen4, popen2.Popen3, popen2.Popen4, commands.getoutput, commands.getstatusoutput] subprocess: [subprocess.Popen, subprocess.call, subprocess.check_call, subprocess.check_output] ``` -------------------------------- ### Bandit Configuration with YAML Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of a Bandit configuration section for the 'try_except_pass' plugin test. This demonstrates how to configure specific plugin options, in this case, `check_typed_exception`. ```yaml try_except_pass: check_typed_exception: True ``` -------------------------------- ### Bandit Configuration Snippet Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/index.rst An example of a configuration snippet generated from a `gen_config` function, showing default settings for a specific plugin. This YAML format is used in Bandit's configuration files. ```yaml try_except_continue: {check_typed_exception: false} ``` -------------------------------- ### Bandit Plugin Check Example Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md Demonstrates how to define a custom Bandit check using the `bandit.checks` decorator. This check targets AST 'Call' nodes and identifies unsafe deserialization patterns. ```python @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." ) ``` -------------------------------- ### Example Bandit Formatter Implementation Source: https://github.com/pycqa/bandit/blob/main/doc/source/formatters/index.rst Demonstrates the basic structure of a Bandit formatter plugin. It defines a `report` function that takes issue data and writes it to a file object, using `bson.dumps` for serialization. This function is intended to be registered as a plugin. ```python def report(manager, fileobj, sev_level, conf_level, lines=-1): result = bson.dumps(issues) with fileobj: fileobj.write(result) ``` -------------------------------- ### Bandit Plugin gen_config Function Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/index.rst Example of a `gen_config` function for Bandit plugins, used to provide default configuration settings when no configuration file is present or a plugin's section is missing. It returns a dictionary of configuration options. ```python def gen_config(name): if name == 'try_except_continue': return {'check_typed_exception': False} ``` -------------------------------- ### Registering Bandit Plugins with Setuptools Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md Shows how to register custom Bandit formatters and plugins using the `entry_points` argument in a `setup.py` file with setuptools. ```python entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']} entry_points={'bandit.plugins': ['mako = bandit_mako']} ``` -------------------------------- ### Register Bandit Extensions in setup.py (setuptools) Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md This snippet illustrates how to register custom Bandit formatters and plugins using the `entry_points` dictionary within a `setup.py` file when using setuptools directly. It defines mappings from an entry point name (e.g., 'bson') to a Python module and function/object (e.g., 'bandit_bson:formatter'). ```Python entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']} entry_points={'bandit.plugins': ['mako = bandit_mako']} ``` -------------------------------- ### Registering Bandit Plugins with pbr Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md Illustrates how to register custom Bandit formatters and plugins in the `setup.cfg` file when using pbr for packaging. ```ini [entry_points] bandit.formatters = bson = bandit_bson:formatter bandit.plugins = mako = bandit_mako ``` -------------------------------- ### Registering Bandit Plugins with pbr Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/index.rst Shows how to register Bandit plugins and formatters in a `setup.cfg` file when using pbr (Python Package Builder). ```ini [entry_points] bandit.formatters = bson = bandit_bson:formatter bandit.plugins = mako = bandit_mako ``` -------------------------------- ### Suppressing Specific Bandit Findings Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of suppressing all Bandit findings on a line using '# nosec'. ```python self.process = subprocess.Popen('/bin/echo', shell=True) # nosec ``` -------------------------------- ### Run Bandit with a Specific Profile Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst This command executes Bandit against the 'examples/' directory, utilizing only the plugins defined in the 'ShellInjection' profile. ```bash bandit examples/*.py -p ShellInjection ``` -------------------------------- ### Bandit Test Decorators Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md Examples of decorators used in Bandit to mark test functions with the types of Python statements they examine. ```python @checks('Call') ``` ```python @checks('Import', 'ImportFrom') ``` ```python @checks('Str') ``` -------------------------------- ### Registering Bandit Formatters with Setuptools Source: https://github.com/pycqa/bandit/blob/main/doc/source/formatters/index.rst Shows how to register a custom Bandit formatter plugin using `setuptools` in the `setup.py` file. It specifies the entry point group `bandit.formatters` and maps a name (e.g., 'bson') to the formatter function within a module (e.g., `bandit_bson:formatter`). ```setuptools entry_points={'bandit.formatters': ['bson = bandit_bson:formatter']} ``` -------------------------------- ### Bandit Configuration Files Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst Lists the files that Bandit uses for configuration. This includes the primary '.bandit' file for command-line arguments and the legacy '/etc/bandit/bandit.yaml' for configuration. ```APIDOC Configuration Files: .bandit file that supplies command line arguments /etc/bandit/bandit.yaml legacy bandit configuration file ``` -------------------------------- ### Suppressing Specific Bandit Findings by Test ID Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of suppressing specific Bandit findings (B602, B607) on a line while allowing others to be reported. ```python self.process = subprocess.Popen('/bin/ls *', shell=True) # nosec B602, B607 ``` -------------------------------- ### Bandit Command-Line Options Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst Detailed descriptions of Bandit's command-line options, including their purpose, accepted values, and default behaviors. This serves as a reference for configuring and running Bandit scans. ```APIDOC OPTIONS: -h, --help show this help message and exit -r, --recursive find and process files in subdirectories -a {file,vuln}, --aggregate {file,vuln} aggregate output by vulnerability (default) or by filename -n CONTEXT_LINES, --number CONTEXT_LINES maximum number of code lines to output for each issue -c CONFIG_FILE, --configfile CONFIG_FILE optional config file to use for selecting plugins and overriding defaults -p PROFILE, --profile PROFILE profile to use (defaults to executing all tests) -t TESTS, --tests TESTS comma-separated list of test IDs to run -s SKIPS, --skip SKIPS comma-separated list of test IDs to skip -l, --level report only issues of a given severity level or higher (-l for LOW, -ll for MEDIUM, -lll for HIGH) -l, --severity-level={all,high,medium,low} report only issues of a given severity level or higher. "all" and "low" are likely to produce the same results, but it is possible for rules to be undefined which will not be listed in "low". -i, --confidence report only issues of a given confidence level or higher (-i for LOW, -ii for MEDIUM, -iii for HIGH) -l, --confidence-level={all,high,medium,low} report only issues of a given confidence level or higher. "all" and "low" are likely to produce the same results, but it is possible for rules to be undefined which will not be listed in "low". -f {csv,custom,html,json,sarif,screen,txt,xml,yaml}, --format {csv,custom,html,json,sarif,screen,txt,xml,yaml} specify output format --msg-template MSG_TEMPLATE specify output message template (only usable with --format custom), see CUSTOM FORMAT section for list of available values -o OUTPUT_FILE, --output OUTPUT_FILE write report to filename -v, --verbose output extra information like excluded and included files -d, --debug turn on debug mode -q, --quiet, --silent only show output in the case of an error --ignore-nosec do not skip lines with # nosec comments -x EXCLUDED_PATHS, --exclude EXCLUDED_PATHS comma-separated list of paths (glob patterns supported) to exclude from scan (note that these are in addition to the excluded paths provided in the config file) (default: .svn,CVS,.bzr,.hg,.git,__pycache__,.tox,.eggs,*.egg) -b BASELINE, --baseline BASELINE path of a baseline report to compare against (only JSON-formatted files are accepted) --ini INI_PATH path to a .bandit file that supplies command line arguments --exit-zero exit with 0, even with results found --version show program's version number and exit ``` -------------------------------- ### Register Bandit Extensions in setup.cfg (pbr) Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md This configuration snippet shows how to register custom Bandit formatters and plugins in a `setup.cfg` file when using pbr. It uses the INI-like format under the `[entry_points]` section to define the `bandit.formatters` and `bandit.plugins` groups with their respective mappings. ```Configuration [entry_points] bandit.formatters = bson = bandit_bson:formatter bandit.plugins = mako = bandit_mako ``` -------------------------------- ### Bandit Issue Example for B109 Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/b109_password_config_option_not_marked_secret.rst Illustrates how Bandit reports issues related to password configuration options not marked as secret, showing severity and confidence levels. ```none >> Issue: [password_config_option_not_marked_secret] oslo config option possibly not marked secret=True identified. Severity: Medium Confidence: Low Location: examples/secret-config-option.py:12 11 help="User's password"), 12 cfg.StrOpt('nova_password', 13 secret=secret, 14 help="Nova user password"), 15 ] >> Issue: [password_config_option_not_marked_secret] oslo config option not marked secret=True identified, security issue. Severity: Medium Confidence: Medium Location: examples/secret-config-option.py:21 20 help="LDAP ubind ser name"), 21 cfg.StrOpt('ldap_password', 22 help="LDAP bind user password"), 23 cfg.StrOpt('ldap_password_attribute', ``` -------------------------------- ### Display Bandit help message Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Show the full help message for Bandit, listing all available command-line options and arguments. ```console bandit -h ``` -------------------------------- ### Suppressing Specific Bandit Findings by Full Test Name Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of suppressing a specific Bandit finding (assert_used) by its full test name, allowing other findings on the same line to be reported. ```python assert yaml.load("{}") == [] # nosec assert_used ``` -------------------------------- ### Using Bandit with JSON Formatter Source: https://github.com/pycqa/bandit/blob/main/doc/source/formatters/json.rst This shows how to run Bandit from the command line and specify the JSON formatter for output. This is useful for integrating Bandit reports into automated workflows or CI/CD pipelines. ```bash bandit -f json -o report.json your_python_file.py ``` -------------------------------- ### Suppressing Bandit Vulnerability Errors Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Example of how to suppress individual Bandit vulnerability errors by appending '# nosec' to a code line. It's recommended to include a comment explaining the reason for suppression. ```python # The following hash is not used in any security context. It is only used # to generate unique values, collisions are acceptable and "data" is not # coming from user-generated input the_hash = md5(data).hexdigest() # nosec ``` -------------------------------- ### Registering Bandit Formatters with pbr Source: https://github.com/pycqa/bandit/blob/main/doc/source/formatters/index.rst Illustrates how to register a custom Bandit formatter plugin using `pbr` in the `setup.cfg` file. Similar to setuptools, it defines the `bandit.formatters` entry point group and associates a name with the formatter's location. ```pbr [entry_points] bandit.formatters = bson = bandit_bson:formatter ``` -------------------------------- ### Bandit Project Dependencies Source: https://github.com/pycqa/bandit/blob/main/requirements.txt This snippet lists the Python packages required for the Bandit project. The order is significant for pip installation. Each entry includes the package name, version constraint (if any), and the license type. ```python PyYAML>=5.3.1 # MIT stevedore>=1.20.0 # Apache-2.0 colorama>=0.3.9;platform_system=="Windows" # BSD License (3 clause) rich # MIT ``` -------------------------------- ### Run Bandit with Context Lines and Severity Filter Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst This command runs Bandit on all Python files in the 'examples/' directory. It displays three lines of context around detected issues and only reports on high-severity findings. ```bash bandit examples/*.py -n 3 --severity-level=high ``` -------------------------------- ### Bandit Command-Line Interface Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst This section details the command-line options available for the Bandit security linter. It covers options for recursive scanning, output aggregation, context lines, configuration files, test selection, skipping tests, severity and confidence levels, output formatting, message templating, output files, verbosity, debugging, quiet mode, ignoring 'nosec' comments, excluding paths, baseline reports, INI file paths, and exit code behavior. ```bash bandit [-h] [-r] [-a {file,vuln}] [-n CONTEXT_LINES] [-c CONFIG_FILE] [-p PROFILE] [-t TESTS] [-s SKIPS] [-l] [-i] [-f {csv,custom,html,json,sarif,screen,txt,xml,yaml}] [--msg-template MSG_TEMPLATE] [-o [OUTPUT_FILE]] [-v] [-d] [-q] [--ignore-nosec] [-x EXCLUDED_PATHS] [-b BASELINE] [--ini INI_PATH] [--exit-zero] [--version] [targets [targets ...]] ``` -------------------------------- ### Bandit Project Dependencies Source: https://github.com/pycqa/bandit/blob/main/doc/requirements.txt Specifies the Python packages required for the Bandit project. The order is significant for pip installation, impacting the integration process. Includes Sphinx for documentation and its Real-Time Descriptor theme, along with a copy button extension. ```python sphinx>=4.0.0 # BSD sphinx-rtd-theme>=0.3.0 sphinx-copybutton ``` -------------------------------- ### Run Bandit with a specific profile Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Execute Bandit on files in the `examples/` directory, limiting the scan to only plugins defined in the `ShellInjection` profile. ```console bandit examples/*.py -p ShellInjection ``` -------------------------------- ### Scan Python files with context and high severity filtering (short options) Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Scan all Python files in the `examples/` directory, showing 3 lines of context for findings and only reporting issues with high severity using short command-line options. ```console bandit examples/*.py -n 3 -lll ``` -------------------------------- ### Bandit B604 Warning: shell=True Usage Source: https://github.com/pycqa/bandit/blob/main/doc/source/plugins/b604_any_other_function_with_shell_equals_true.rst This warning (B604) is triggered when functions that execute shell commands are used with the `shell=True` argument. This can be a security risk if user-controlled input is passed to these commands, potentially leading to command injection. The `any_other_function_with_shell_equals_true` function is an example that might trigger this warning. ```python import subprocess # Example that might trigger B604 if user_input is not sanitized subprocess.run("echo 'hello'", shell=True) # Function that might be flagged by Bandit def any_other_function_with_shell_equals_true(user_input): subprocess.run(f"echo {user_input}", shell=True) ``` -------------------------------- ### Running Bandit with a pyproject.toml Configuration Source: https://github.com/pycqa/bandit/blob/main/doc/source/config.rst Command to run Bandit with a specified configuration file (`pyproject.toml`) and recursively scan the current directory (`.`). ```console bandit -c pyproject.toml -r . ``` -------------------------------- ### Example Bandit Check for Unsafe Deserialization Source: https://github.com/pycqa/bandit/blob/main/CONTRIBUTING.md This Python code snippet demonstrates how to define a custom Bandit check. It uses the `@bandit.checks('Call')` decorator to register the function to be called for 'Call' AST nodes. The check inspects the `context.call_function_name_qual` to detect unsafe deserialization patterns and reports an issue using `bandit.Issue` with specified severity and confidence. ```Python @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." ) ``` -------------------------------- ### Bandit Custom Formatting Tags Source: https://github.com/pycqa/bandit/blob/main/doc/source/man/bandit.rst Demonstrates how to use custom message templates with Bandit for tailored output. It lists available tags like absolute path, relative path, line number, test ID, severity, message, confidence, and range. Examples show default and formatted tag usage, including Python string formatting. ```bash bandit -r examples/ --format custom --msg-template "{abspath}:{line}: {test_id}[bandit]: {severity}: {msg}" ``` ```bash bandit -r examples/ --format custom --msg-template "{relpath:20.20s}: {line:03}: {test_id:^8}: DEFECT: {msg:>20}" ``` -------------------------------- ### Scan Python files with context and high severity filtering Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Scan all Python files in the `examples/` directory, showing 3 lines of context for findings and only reporting issues with high severity. ```console bandit examples/*.py -n 3 --severity-level=high ``` -------------------------------- ### Bandit Action Inputs Source: https://github.com/pycqa/bandit/blob/main/doc/source/ci-cd/github-actions.rst This section documents the various inputs available for the PyCQA/bandit-action, detailing their purpose, whether they are required, and their default values. These inputs allow customization of the Bandit scan, such as specifying configuration files, test profiles, severity levels, and exclusion paths. ```APIDOC BanditActionInputs: configfile: description: Config file to use for selecting plugins and overriding defaults. required: False default: "DEFAULT" profile: description: Profile to use (defaults to executing all tests). required: False default: "DEFAULT" tests: description: Comma-separated list of test IDs to run. required: False default: "DEFAULT" skips: description: Comma-separated list of test IDs to skip. required: False default: "DEFAULT" severity: description: Report only issues of a given severity level or higher. Options include all, high, medium, low. Note: all and low may produce similar results, but undefined rules will not be listed under low. required: False default: "DEFAULT" confidence: description: Report only issues of a given confidence level or higher. Options include all, high, medium, low. Note: all and low may produce similar results, but undefined rules will not be listed under low. required: False default: "DEFAULT" exclude: description: Comma-separated list of paths (glob patterns supported) to exclude from the scan. These are in addition to excluded paths provided in the config file. required: False default: ".svn,CVS,.bzr,.hg,.git,__pycache__,.tox,.eggs,*.egg" baseline: description: Path of a baseline report to compare against (only JSON-formatted files are accepted). required: False default: "DEFAULT" ini: description: Path to a .bandit file that supplies command-line arguments. required: False default: "DEFAULT" targets: description: Source file(s) or directory(s) to be tested. required: False default: "." ``` -------------------------------- ### Bandit Baseline Report Source: https://github.com/pycqa/bandit/blob/main/doc/source/start.rst Instructions on using the baseline feature to compare current scans against a previous report, including generating a JSON baseline file. ```console bandit -b BASELINE ``` ```console bandit -f json -o PATH_TO_OUTPUT_FILE ```