Skip to content

How to Use Bandit to Scan Your Python Code for Security Vulnerabilities

Avatar photo

https://www.linkedin.com/in/kumar-nikhil811/

As software developers, we all want to write code that is both functional and secure. However, writing secure code can be challenging, especially if you’re not familiar with the latest security best practices. That’s where Python code vulnerability scanners like Bandit can be incredibly helpful. Bandit is a security linter for Python code that can be used to detect common security issues in your Python code. It analyzes your Python code and reports potential security issues like vulnerabilities, insecure cryptographic practices, and hardcoded secrets.

In this blog, we’ll explore how to use Bandit to scan your Python code for security issues, starting with how to install and run the tool.

Installing Bandit

To install Bandit, you can use pip, the Python package manager. Simply run the following command in your terminal:

pip install bandit

Once Bandit is installed, you can start using it to scan your Python code.

Running Bandit on your code

To run Bandit on your Python code, Navigate to the directory containing your Python code and simply run the following command:

#using dot(.) notation it will scan all the python files which is inside that directory
bandit -r .  

#if we want to scan any specific file we can enter the path of that python file
bandit -r /path/to/your/code

This will recursively scan all files and directories under the specified path for security issues. Bandit will generate a report highlighting any potential security issues it finds.

By default, Bandit checks for issues with severity levels of medium and higher. If you want to include low-severity issues in the report, you can use the -ll option:

bandit -r . -ll

This will include low-severity issues in the report.

You can also specify additional options to customize the behaviour of Bandit. For example, you can specify a severity level threshold to filter out low-severity issues:

bandit -r /path/to/your/code -s MEDIUM

This command will only report issues with a severity level of MEDIUM or higher.

You can also exclude certain files or directories from the scan by using the -x option followed by the path to exclude:

bandit -r . -x some_directory/

This will exclude the some_directory the directory from the scan.

Bandit can be a useful tool to help you identify potential security issues in your Python code and improve the overall security of your application.

Example of scanning a python code that has no vulnerabilities:

[root@nikhil library]# bandit -r yum_install.py
[main]  INFO    profile include tests: None
[main]  INFO    profile exclude tests: None
[main]  INFO    cli include tests: None
[main]  INFO    cli exclude tests: None
[main]  INFO    running on Python 3.9.6
[node_visitor]  WARNING Unable to find qualified name for module: yum_install.py
Run started:2023-03-07 11:04:17.198120

Test results:
        No issues identified.

Code scanned:
        Total lines of code: 16
        Total lines skipped (#nosec): 0

Run metrics:
        Total issues (by severity):
                Undefined: 0
                Low: 0
                Medium: 0
                High: 0
        Total issues (by confidence):
                Undefined: 0
                Low: 0
                Medium: 0
                High: 0
Files skipped (0):
[root@nikhil library]# ls

In the below example, I just ran the bandit command to see low-level vulnerabilities:

[root@nikhil library]# bandit -r linuxcmd.py  -ll
[main]  INFO    profile include tests: None
[main]  INFO    profile exclude tests: None
[main]  INFO    cli include tests: None
[main]  INFO    cli exclude tests: None
[main]  INFO    running on Python 3.9.6
Run started:2023-03-07 11:05:51.854262

Test results:
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:38:17
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
37
38                              os.system("mkdir "+fold_name)
39

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:44:2
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
43
44                      os.system("touch "+file_name)
45

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:57:2
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
56                      user_name = input("Enter name you want to add in the OS:")
57                      os.system("useradd "+user_name)
58

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:62:2
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
61                      font_col = input("Enter any number:")
62                      os.system("tput setaf "+str(font_col))
63

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:68:2
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
67
68                      os.system("echo "+mes_sage)
69

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:73:17
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
72                              remove_dir = input("enter folder name you want to delete:")
73                              os.system("rm -rf " + remove_dir)
74

--------------------------------------------------
>> Issue: [B605:start_process_with_a_shell] Starting a process with a shell, possible injection detected, security issue.
   Severity: High   Confidence: High
   CWE: CWE-78 (https://cwe.mitre.org/data/definitions/78.html)
   Location: linuxcmd.py:81:2
   More Info: https://bandit.readthedocs.io/en/1.7.4/plugins/b605_start_process_with_a_shell.html
80
81                      os.system("date > "+f_name)
82

--------------------------------------------------

Code scanned:
        Total lines of code: 48
        Total lines skipped (#nosec): 0

Run metrics:
        Total issues (by severity):
                Undefined: 0
                Low: 8
                Medium: 0
                High: 7
        Total issues (by confidence):
                Undefined: 0
                Low: 0
                Medium: 0
                High: 15
Files skipped (0):
[root@nikhil library]#

Interpreting the Bandit report

Once Bandit has finished scanning your code, it will generate a report listing any potential security issues it found. The report will include details about each issue, such as the location in the code where the issue was found, the severity level of the issue, and a description of the issue.

It’s important to carefully review the Bandit report and address any potential security issues it identifies. You can use the report to prioritize your efforts, focusing on the most severe issues first.

Common security issues identified by Bandit

Some of the most common security issues that Bandit can identify include:

  • Use of weak or easily guessable passwords
  • Use of weak or outdated encryption algorithms
  • SQL injection vulnerabilities
  • Cross-site scripting (XSS) vulnerabilities
  • Use of insecure random number generators
  • Use of unsafe file I/O functions

Each of these issues can be a serious security risk, so it’s important to address them as soon as possible. Fortunately, Bandit can help you identify these issues so you can fix them before they become a problem.

Best practices for using Bandit

To get the most out of Bandit, there are some best practices you should follow:

  • Run Bandit on your code regularly to catch potential security issues early in the development process.
  • Integrate Bandit into your development process to ensure that all code is scanned for security issues before it is deployed.
  • Consider using other tools and techniques, such as penetration testing and code reviews, to supplement Bandit and ensure that your code is as secure as possible.

By following these best practices, you can use Bandit to help ensure that your Python code is as secure as possible.

Conclusion

Overall, Bandit is a powerful tool for identifying potential security vulnerabilities in your Python code. By regularly scanning your code with Bandit and addressing any issues it identifies, you can help ensure that your code is as secure as possible. It’s important to remember that Bandit is just one tool in your security toolbox and should be used in conjunction with other techniques, such as penetration testing and code reviews, to ensure that your code is as secure as possible.

In today’s digital age, security is more important than ever. As software developers, we have a responsibility to ensure that our code is as secure as possible. By using tools like Bandit to identify and address potential security vulnerabilities, we can help protect our users and our organizations from potential attacks. So don’t hesitate to start using Bandit today and take the first step towards writing more secure code!

Disclaimer:

The views expressed and the content shared in all published articles on this website are solely those of the respective authors, and they do not necessarily reflect the views of the author’s employer or the techbeatly platform. We strive to ensure the accuracy and validity of the content published on our website. However, we cannot guarantee the absolute correctness or completeness of the information provided. It is the responsibility of the readers and users of this website to verify the accuracy and appropriateness of any information or opinions expressed within the articles. If you come across any content that you believe to be incorrect or invalid, please contact us immediately so that we can address the issue promptly.

Avatar photo


https://www.linkedin.com/in/kumar-nikhil811/
Nikhil Kumar is a DevOps Engineer with 5years of experience in the field. Alongside a successful career in technology, he has also cultivated a passion for writing, having authored several articles and blogs on the subjects of DevOps and the Cloud. With a keen interest in exploring the intersection of technology and the written word, he brings a unique perspective to the conversation.

Comments

1 Response

  1. […] today’s rapidly evolving digital landscape, security automation has become a crucial aspect of ensuring the safety and integrity of IT environments. By leveraging […]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.