Top 10 Python security best practices

On the sleepy island of Gozo, security isn’t a concern. Tourists can leave their bags on the beach and go off on an adventure without worrying that their belongings will be stolen. In my home city, however, we say that “if you don’t tie it down, it’s not yours.” Everything can be stolen. Similarly, the internet is the biggest and busiest city in the world! If it can be read, copied, written, or injected with SQL, it’s not yours.

While writing code that’s secure from any outsider exploits can be hard, it’s supposed to make our lives easier in the long run. Even if it’s a simple application to inform users of innocent local events, there are sometimes bad actors who will make it into a phishing scam to take money from pensions. So what can you do to prevent this?

One way is to follow the best practices for writing secure code for Python applications—and even mark down in your calendar to at least read one new article per month. Python is one of the most popular programming languages in cybersecurity due to its simple syntax and readability. In this post, we’ll look at the top 10 Python security best practices, starting with the easiest to implement then moving up to the hardest to implement in our code.

Python security best practices

Without further ado, here are the top 10 Python security best practices you need to start using now.

1. Use the most recent version of Python

Python 3 was released all the way back in December 2008, and yet some people are still using older versions of Python for their projects. One issue with this is Python 2.7 and older don’t have the same security updates as Python 3. For example, input methods and exception chaining have been improved in Python 3. If you run code in Python 2.7 that was written in Python 3, the inputs may be exploited.

In addition, Python 2.7 will lose its support in 2020, so if you’re too attached to Python 2.7 to scale up to Python 3, you’ll have to eventually. The more applications you deploy using older versions of Python, the more pain it will be in the future to update them all.

If you want information on the newest version of Python, check python.org for the most recent release. And if you’re unsure what version of Python you’re currently using, run the following on your local machine to check:

python --version

Now that we have the latest version of Python, let’s create a safe virtual environment.

2. Use a virtual environment

Instead of installing packages globally on your machine, use a virtual environment for each project. This means that if you install a package dependency with malicious code in one project, it will not affect the others. Each project’s packages are isolated from each other.

Virtualenv supports an isolated Python environment by creating a separate folder for packages used in the specific project.

Install the following:

pip install virtualenv

Activate this in the project location:

venv\Scripts\activate.bat

Alternatively, you can look into Pipenv, which has a lot more tools to develop secure applications with.

3. Set debug = false

For some Python frameworks, such as Django, debug is set to true by default in new projects. This can be helpful in development to show errors in our code, but isn’t so useful when we deploy the project to live on a server available to the public. Displaying errors in our code publicly could show a weakness in our security that will be exploited.

So when deployed live, always set the following:

Debug = false

You can find the Debug option in settings.py if you’re using a framework like this.

Debug = true top 10 python security best practices

4. Never commit anything with a password

Assuming most developers are using GitHub, double-check that you haven’t committed a file, readme, or a description of a URL with your password in it. Once committed to GitHub or a similar service, the password will always be there somewhere in a log or database for anyone to find. In May 2019, for example, a hacker stole hundreds of passwords saved in plain text in GitHub repositories and demanded a ransom of 0.1 Bitcoin each.

Consciously avoid adding passwords or API keys in your source code.

Check out Git-Secrets to help prevent committing passwords or other sensitive information to GitHub.

5. Look out for poisoned packages

For most programmers, a programming language is only as strong as its libraries. Python has several impressive libraries that are easy to install through Pip.

Double-check that you’re using legitimate and updated packages. It’s possible to install packages for both Python and Node.js that have malicious code in them. Check that you have exactly the right names for each package. “00Seven” is a completely different package from”000Seven.”

Other than double-checking the package’s name, you can also use platforms like Sqreen, which checks your application for packages with malicious code and checks for legitimate packages with known problems or outdated versions. Have a look at their Application Security Management solution to get more visibility into your apps and protect them against attacks triggering vulnerabilities.

6. Check import paths

There are three types of import paths in Python: absolute, relative, and implicit.

An implicit path means that the address of the package is not specific. So the program uses a module of the same name somewhere on your system. This might install a package with malicious code. There have been a number of Trojan horse cases from malicious code in Python packages, specifically PyPi. Moreover, some were not detected for a year.

Instead, use an absolute path to avoid such confusion. Just by using the full address of the package, we clearly know the correct package to use and that it has been checked for malicious code. This is the safest method.

from safe_package import safe_module

A relative path indicates the location of the module relative to the current folder.

from ..some_package import less_danger

7. Protect against SQL injections

So what kind of a person injects SQL into a database anyway? Some bot on a server somewhere that will destroy millions of badly programmed websites, in the hope that enough people will click on their affiliate links.

Furthermore, SQL injections can also drop sensitive data from insecure tables. So please take SQL injections seriously and follow updated procedures in protecting your database from SQL injections. Read more here.

SQL injections have famously exposed users’ sensitive data through multiple WordPress plugins, and even the government of India has had their database left wide open from bus booking websites. It remains number one on the OWASP Top Ten list for a reason. 

8. Use pycryptodome for cryptography

As highlighted in a previous article, stop using pycrypto for your cryptography toolkit. A vulnerability was highlighted, and since then, no security update has been released to fix the problem. The project hasn’t been updated in years, in fact.

But that’s cool. Just use pycryptodome instead:

pip install pycryptodome

9. Use Bandit

Install the package Bandit for each Python project. Bandit scans your code for well-known vulnerabilities, such as common issues with YAML. It ranks the security risk from low to high and tells you which lines of code in question are causing the problem.

pip install bandit
bandit path/project.py

Bandit scans the selected Python file and presents the report in an abstract syntax tree.

Bandit is quick, easy to use, and highly recommended.

Bandit top 10 python security best practices

10. Keep your servers up to date

Sometimes potential dangers have nothing to do with the code but rather the servers. You must check that all your software is updated and compatible with your Python code. Random human error can destroy work that took years of planning. So make sure that the software and security management systems are up to date.

In conclusion

I hope you found this list of the top 10 Python security best practices useful. There are several reasons why Python is so popular in cybersecurity.

  • It’s easy to use.
  • Easy-to-read data structures.
  • Easy to debug.
  • Object-oriented language.
  • Flexible.
  • Clean.
  • Powerful libraries.
  • Python can be used for almost every type of application from the web to financial technology.

Therefore, when programming your Python application, security and respecting the privacy of your users must be top concerns. The internet security landscape is changing constantly, and it seems like the more complicated programming languages get, the easier it is to find vulnerabilities to exploit.

It can be hard to figure out what to do to make your applications more secure, but following these top 10 Python security best practices, and keeping up with further research into cybersecurity, can help.