Python Security: Top 5 Best Practices 
Tags: python, security
Published: 2020-04-05 05:28:16

Even the best developers can’t account for all security vulnerabilities. No application is ever fully secured, no matter how much you might like it to be. Python applications are no exception. You can even find security flaws in the standard library documentation. However, that does not mean you should stop trying to write secure software. This article walks you through the key best practices for securing python code.

## What Is Python?
Python is an object-oriented, high-level programming language with dynamic semantics. Python enables fast application development with built-in data structures, dynamic binding, and dynamic typing. 

The syntax of Python is readable and easy to learn and thus reduces the cost of maintenance. Python supports packages, and modules that enable code reuse and program modularity. The Python standard library and the interpreter are available in source or binary form for free-for-all major platforms, and can be freely distributed.

## 5 Python Security Best Practices
The below list reviews the top five Python security best practices you need to start using.

**1. Carefully download packages**
Developers usually use the pip standard package installer or [Pipenv](https://pipenv-fork.readthedocs.io/en/latest/) to install packages. However, the [Python Package Index](https://pypi.org/) (PyPI) that distributes packages may include malicious code. PyPI has a standard process for reporting security issues. PyPI immediately addresses reports about malicious packages or problems, but it does not review newly added packages.

You can always expect to find malicious packages in PyPI. Before downloading, you need to research the package you want to install and carefully spell out the package name. Attackers can exploit a misspelled package name to execute malicious code.

**2. Stay up-to-date on vulnerabilities**
A quick response to any open source vulnerability is critical for successful remediation of problems within your code. Remediation means upgrading to a newer open source dependency version, patching, and changing your code to ensure to avoid vulnerable functions. 

You are not expected to discover vulnerabilities on your own. That’s what [vulnerability databases](https://vuln.whitesourcesoftware.com/) are for. These platforms collect and categorize vulnerabilities, and often provide this information for free, as a service to the public.

**3. Use the latest Python version** 
Some developers still use Python 2 versions, even though Python 3 was released back in 2008. The problem is that Python 2.7 and older versions do not have the same security updates as Python 3. 

For instance, exception chaining and input methods were improved in Python 3. As a result, attackers may exploit inputs of Python 3 code that run in a Python 2.7 environment. The Python community stopped the support for Python 2.7 in 2020. So you should deploy new versions of Python to avoid any potential risks.

**4. Never include password in commits**
GitHub is an open-source and publically available version control system. Anyone can access your GitHub repository and use your code. Make sure not to include any passwords in your files, or URL descriptions. Passwords will always remain in a log or database, once committed to GitHub or a similar service. 

**5. Be careful with string formatting**
Python offers four flexible string formatting approaches. However, flexible formatting syntax like the f-strings can be vulnerable to exploits. This is why developers should pay attention when formatting user-generated strings. 

The Python built-in string module can help you overcome this problem. Built-in string modules are based on the template class that enables you to create template strings. For instance, the code below asks users to enter their name and then displays the name:

`from string import Template`
`name_template = Template(“Hello, my name is $name.”)`
`greeting = name_template.substitute(name=”James”)`

The output is a string of “Hello, my name is James”. This string module is not as flexible as f-string. This is why string modules are a good choice for handling user inputs.

## Top Python Security Tools
Take a look at some of the most common Python security tools and scanners.

**Bandit**
[Bandit](https://bandit.readthedocs.io/en/latest/config.html) is an open-source tool aimed at finding common Python security issues. Bandit scans each file, builds an [AST](https://docs.python.org/3/library/ast.html#module-ast) module from it, and runs relevant plugins against the AST nodes. After the scanning, Bandit generates a report with the status of each file.

Key features include:

* **Test plugins**—supports various tests that help you detect security issues in Python code. You can create these tests as plugins to extend the functionality of Bandit.
* **Blacklist plugins**—you can blacklist imports and function calls. This functionality is an integrated part of one of the Bandit tests. You can filter this test according to normal plugin filtering rules.
* **Report formatters**—supports various formatters that can output Python security issues. You can create these formatters as plugins and to extend the functionality of Bandit.

**Pyntch**
[Pyntch](https://pypi.org/project/pyntch/) is a static code analysis tool for Python. Pyntch can identify potential runtime errors before actually running a code by scanning a source code statically. 

The scanning process analyzes all possible variable types, function arguments, attributes, and return values of each function or method. Then it identifies possible issues caused by attributes not found, type mismatch, or other types of exceptions.

Pyntch gathers the following information:

* **Possible types of objects**—of each variable, class attribute, function argument to detect exceptions.
* **Functions or instance methods**—that you can call at each function call.
* **Calling locations**—for each method or function.
* **Uncaught exceptions**—like type mismatch, access to undefined attributes, iteration over non-iterable objects and more.

**Spaghetti**
[Spaghetti](https://pysal.org/spaghetti/) is an open-source network-based spatial data analysis library. The library is based on the [Python Spatial Analysis Library](http://pysal.org/) (PySAL) network module. You can use Spaghetti to build graph-theoretic networks and analyze the network events. 

Key features include:
* **Network representation**—creates and visualizes network objects.
* **Spatial network analysis**—demonstrating network representation and cluster detection.
* **Optimal facility location**—demonstrating network-based optimal facility location modeling.

**Requires**
[Requires](https://requires.io/) monitors the requirements of your Python project and notifies you whenever a dependency is outdated. 

Key features include:

* **Tracking security updates**—for all the dependencies of a project.
* **Filter directive**—enables you to filter PyPI releases before matching them to your requirements.
* **Badges**—provides badges for tracking projects status. These badges were generated using the [shields.io](https://shields.io/).

## Conclusion
Developers usually do not include secure coding practices when learning a new programming language. Many developers are not aware of the security risks in using Python standard libraries. Make sure to follow these security best practices to make your Python applications secure. You can also leverage [artificial intelligence](https://www.datamation.com/artificial-intelligence/top-artificial-intelligence-software.html) (AI) technologies to automate and improve the process.