Python code scanning: Enterprise-level code security vulnerability scanning Bandit

Table of contents

What is Bandit?

Features

Installation & Configuration

Configure Bandit

Pycharm configuration external tools

Use practice

Command line parameters

Check a single file

Check the entire directory

Scanning of a single file or project directory in PyCharm

a use case

Application scenarios

Summarize

References


Note: Subsequent technology sharing, immediate updates, and more timely technical information and learning technical materials will be releasedon the official account CTO Plus . Please follow the official account: CTO Plus

In the previous article, we introduced Bandit as a tool specifically used to scan security vulnerabilities in Python code. Code security vulnerability scanning is one of the important links to ensure software security. During the software development process, there are many potential security vulnerabilities. In order to discover and repair these vulnerabilities in a timely manner, we need to use professional security scanning tools. Bandit can help us check potential security risks in the code, such as code injection, XSS attacks, SQL injection and leakage of sensitive information, etc.

In this article, I will introduce this popular code security vulnerability scanning tool, Bandit, under the Python 3.11 version. I will introduce the characteristics, usage and application scenarios of Bandit in projects, and demonstrate its usage through a practical case. and effect.

This article "Python Code Scanning: Enterprise-Level Code Security Vulnerability Scanning Bandit" is the last article in the "Code Standards and Scanning" series. You can read the previous articles according to your own situation. At the same time, follow-up articles from the public account CTO Plus are welcome. :

" Static Scanning of Enterprise-Level Python Code - Introduction to Code Specifications, Logic, Grammar, Security Checks, and Automatic Code Arrangement "

" Reading through the Python PEP8 Code Specification "

" Python Code Scanning: New Generation Python Linter Tool Ruff "

" Python code scanning: an artifact to improve the quality of Python code-pylint detailed explanation and usage guide "

" Python Code Scanning: Lightweight Python static code analysis tool pyflakes "

" Python code scanning: a powerful tool for Python code specification and error checking-flake8 detailed explanation and practice "

" Python code scanning: the best choice for static type checking mypy "

" Python code scanning: automatically remove redundancy in Python code-autoflake usage tips and examples "

" Python code scanning: a powerful tool for Python code formatting-yapf detailed explanation and best practices "

" Python code scanning: the black magic of formatting Python code with one click - black usage tutorial "

" Python Code Scanning: Import Statement Automatic Sorting Tool-isor Usage Guide and Examples "

" Python code scanning: a tool to automatically repair Python code style - autopep8 detailed explanation and examples "

" Python Code Scanning: Enterprise-Level Code Security Vulnerability Scanning Bandit "

What is Bandit?

Bandit is a Python-based code security vulnerability scanning tool used to detect security issues in Python code. It can help developers promptly discover and repair security vulnerabilities in code and improve software security. Bandit uses the AST module in the standard library to parse Python source code into a tree composed of Python syntax nodes. Bandit allows users to write custom tests. After testing is completed, Bandit will generate a security report for the source code.

Features

Python Bandit has the following characteristics:

1. Static code analysis: Python Bandit checks for security vulnerabilities by statically analyzing source code and can find potential security issues without running the code.

2. Customized rules (multiple vulnerability detection rules): Python Bandit provides a series of default rules. The built-in multiple vulnerability detection rules include code injection, XSS attacks, SQL injection, etc., and also supports custom rules. We can define our own rules based on the needs of the project to meet specific security requirements.

3. Advanced detection: Python Bandit can detect a variety of common security issues, such as code injection, XSS attacks, sensitive information leakage, weak passwords, etc. It uses a series of algorithms and pattern matching techniques to improve detection accuracy.

4. Report generation: Python Bandit can generate detailed reports, including the description, location and recommended fixes of each security issue. These reports help us quickly locate and resolve security issues.

5. Easy integration and flexible configuration options: Bandit can be integrated with other tools (such as CI/CD tools, editor plug-ins-PyCharm, etc.) to facilitate automated scanning. At the same time, Bandit provides a wealth of configuration options that can be customized according to project needs.

I will conduct a detailed analysis of the source code and principles of this tool later. Articles following the official account CTO Plus are welcome. If you have any questions, please leave a message in the background.

Installation & Configuration

Using Python Bandit is very easy, just follow these steps:

1. Install Python Bandit: Python Bandit can be installed through the pip command, as shown below:

pip install bandit

After the installation is complete, you can see an executable file bandit.exe in the D:\env311\Scripts directory.

Configure Bandit

Bandit does not require configuration by default. If we need to do some configuration according to the actual needs of our project, we can pass a configuration file named bandit.yaml. We can create the file in the project root directory and specify the rules and rules that need to be checked. Other configuration options. Here is a simple configuration file example:

include:
  - "*.py"

exclude:
  - "tests/*"

plugins:
  blacklist_calls:  # 检测黑名单函数调用
    functions:
      - os.system
      - subprocess.Popen

In the above configuration file, include specifies the files that need to be checked, exclude specifies the files or directories that need to be excluded from checking, and plugins specifies the rules and blacklist function calls that need to be checked.

Pycharm configuration external tools

Bandit can be installed as an external tool in PyCharm. Open Preferences and navigate to Tools > External Tools. There, add a new tool with the following configuration. For other configuration options, please refer to the official documentation. Here are my configuration options:

After the configuration is completed, we can use the autopep8 tool in PyCharm

Use practice

Here are some best practices to consider when using Bandit to scan for code security vulnerabilities:

1. Combined with version control: It is recommended to use Bandit's scanning operation in conjunction with a version control system. This can perform scanning operations before code submission or in a continuous integration environment, helping us to discover and fix security issues in the code in a timely manner.

2. Cooperate with editor plug-ins: Bandit provides plug-in integration with many popular editors (such as VS Code, PyCharm, etc.). By installing the corresponding plug-in, you can check code security vulnerabilities in real time in the editor and give timely feedback to improve code quality.

3. Regular scanning and updates: Code security vulnerabilities are a dynamic problem, and new vulnerabilities and attack methods are constantly emerging. Therefore, it is recommended to regularly use Bandit to scan code security vulnerabilities, and to update Bandit tools and rules in a timely manner to ensure the security of the code.

4. Combine with other tools: Bandit is an excellent code security vulnerability scanning tool, but it is not the only option. In actual use, it can be combined with other security scanning tools (such as OWASP ZAP, SonarQube, etc.) to perform comprehensive scanning to further improve the security of the code. I will introduce these other security checking tools in detail later in the development process of the SDLC product. Please stay tuned for the technical articles behind CTO Plus .

Command line parameters

Here I summarize some commonly used command line parameters of the Bandit tool. For others, please refer to the official documentation:

--recursive: Recursively process all files in the directory.

--exclude=<patterns>: Set file or directory patterns to exclude.

--configfile=<file>: Specify the configuration file.

Next, we will introduce several usage methods and an example.

Check a single file

A single Python file can be scanned for security vulnerabilities using the following command:

bandit /path/to/file.py

This will output security vulnerability issues and potential risks in the file.

Check the entire directory

All Python files in the entire directory can be scanned for security vulnerabilities using the following command:

bandit --recursive /path/to/directory

This will recursively traverse the directory and scan all Python files for security vulnerabilities.

Scanning of a single file or project directory in PyCharm

This will scan all Python files under the specified path and generate a corresponding security report. The output of Bandit includes information such as vulnerability level, vulnerability type, vulnerability description, and code location. Developers can promptly discover and fix security issues in the code based on the output results.

a use case

Suppose we have a Python file called example.py with the following content:

import os

def execute_command(command):
    os.system(command)

command = input("Enter a command: ")
execute_command(command)

There is a security vulnerability in this code, that is, the commands entered by the user are directly passed to the os.system function for execution, and there is a risk of code injection.

We can use Bandit to scan the code for security vulnerabilities. The command is as follows:

bandit example.py

After executing the above command, Bandit will output the following results:

[main]    INFO    profile include tests/*,*.py,*.pyw,*.cgi,*.fcgi,*.pyi,*.rpy,*.wsgi,*.cpx,*.pxd,*.pyx,*.pyd,*.so,*.dll,*.pyc,*.pyo

[main]    INFO    using config: .bandit

[main]    INFO    running on Python 3.9.1

[main]    INFO    loading plugins

[main]    INFO    plugins loaded: BanditBasics, BanditCall, BanditImports, BanditImportsBanned, BanditImportsBlacklist, BanditImportsEnvironment, BanditImportsStdlib, BanditNodeVisitor, BanditPreloader, BanditPythonVersion, BanditSecurityGuard, BanditSecurityNodeVisitor, BanditSecurityPreloader, BanditSecuritySyntaxCheck, BanditSyntaxCheck, BanditUast, BanditVisitor, BanditVisitorBase, BanditVisitorFactory, BanditVisitorPreloader

[main]    INFO    running on os Posix

[main]    INFO    [bandit.core.manager] Issue [B607:blacklist_calls] Consider possible security implications associated with subprocess module.

[main]    INFO    [bandit.core.manager] Issue [B607:blacklist_calls] Consider possible security implications associated with os.system function.

[main]    INFO    [bandit.core.manager] Issue [B701:blacklist] Use of possibly insecure function - consider using safer 'subprocess.run' instead.

As can be seen from the above results, Bandit detected security vulnerabilities in the code and gave corresponding warning messages.

According to the output of Bandit, we can see that there is a problem with blacklist function calls in the code, and it is recommended to use safer functions instead.

Application scenarios

Python Bandit can be applied in many projects, especially those involving user input and sensitive data processing. The following are some application scenarios of Python Bandit that I summarized:

1. Web applications: For web applications written in Python, Python Bandit can help us check security issues such as XSS attacks, SQL injection, and command injection in the code.

2. Code review (code security): When developing and deploying APIs, Python Bandit can help us check for security vulnerabilities in the code, such as sensitive information leaks, permission issues, and cross-site request forgery (CSRF).

3. Data processing: For projects that handle sensitive data, such as user passwords and credit card information, Python Bandit can help us check security issues in the code to ensure the security of the data.

4. Open source projects: For open source projects written in Python, Python Bandit can help us check security issues in the code to improve the quality and reliability of the project.

Summarize

Python Bandit is a powerful tool that can help us check for security vulnerabilities in Python code. It statically analyzes code to find potential security issues and generates detailed reports. We can use the recommendations in the report to fix security issues in the code to improve the quality and reliability of the code. In scenarios such as web applications, API development, data processing, and open source projects, Python Bandit can play an important role in helping us ensure the security of our code.

References

  1. Welcome to Bandit — Bandit documentation
  2. GitHub - PyCQA/bandit: Bandit is a tool designed to find common security issues in Python code.
  3. Python code specifications: Enterprise-level code static scanning - code specifications, logic, syntax, security checks, and automatic arrangement of code specifications (1)_pycharm Check code specifications_SteveRocket's blog-CSDN blog
  4. https://blog.csdn.net/zhouruifu2015/article/details/129877179

Python column
https://blog.csdn.net/zhouruifu2015/category_5742543


More information · Search the WeChat public account [ CTO Plus ] and follow it to get more information. Let’s learn and communicate together.

For a description of the public account, visit the following link


For more exciting news, follow my official account and learn and grow together.

About Articulate "Be a porter of knowledge and technology. Be a lifelong learning enthusiast. Be a technical circle with depth and breadth." I have always wanted to develop skills in the professional field icon-default.png?t=N7T8https://mp.weixin.qq. com/s?__biz=MzIyMzQ5MTY4OQ==&mid=2247484278&idx=1&sn=2b774f789b4c7a2ccf10e465a1b9def6&chksm=e81c2070df6ba966026fd7851efa824b5e2704e3fd34e 76228ca4ce64d93f7964cd4abe60f2b#rd

Standard Library Series-Recommended Reading:

Recommended
reading:

Guess you like

Origin blog.csdn.net/zhouruifu2015/article/details/131264465