DEV Community

Cover image for Python Security: Top 5 Best Practices
LeahFB
LeahFB

Posted on • Edited on

Python Security: Top 5 Best Practices

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 to install packages. However, the Python Package Index (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 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 is an open-source tool aimed at finding common Python security issues. Bandit scans each file, builds an 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 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 is an open-source network-based spatial data analysis library. The library is based on the Python Spatial Analysis Library (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 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.

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 (AI) technologies to automate and improve the process.

Top comments (7)

Collapse
 
mburszley profile image
Maximilian Burszley • Edited

The problem is that Python 2.7 and older versions do not have the same security updates as Python 3.

This is factually wrong. As long as they are maintained versions, they are getting security updates. Use the latest patch version (x.x.*)

I have no feedback otherwise as I haven't heard of those tools but OWASP makes good, open-source tools for web apps and Snyk is big when it comes to static analysis.

Collapse
 
evanepio profile image
Evan Porter

It's not factually wrong: python.org/dev/peps/pep-0373/#main...

2.7.18 is the last release of 2.x, based on the code from January 1st 2020 - no more changes/updates will be accepted and the code is frozen. They will make one more official release of 2.x based on the January 1st 2020 code (2.7.18) and that release will be more ceremony than anything else.

Collapse
 
mburszley profile image
Maximilian Burszley

Reading comprehension. as long as they are maintained versions

Thread Thread
 
evanepio profile image
Evan Porter

Sorry, I wasn't clear on what I meant. Maybe this is clearer: python.org/doc/sunset-python-2/

As of January 1st, 2020 no new bug reports, fixes, or changes will be made to Python 2, and Python 2 is no longer supported.

Thread Thread
 
mburszley profile image
Maximilian Burszley

Perfectly clear, I just can't tell if you're being obtuse or struggle with English in general.

Collapse
 
jpeyret profile image
jpeyret • Edited

This so wrong it's not even funny.

Python 2.7, God bless its soul, is now end-of-life-d. There are no new security patches coming out. With a little bit of luck, there will be no huge security holes in the language itself until people have migrated off from it, but it's far from certain this will be the case. However, worse than that, 3rd party libraries will most likely not put in any great amount of effort to back-patch releases that are 2.7 only. And that's going to be a much bigger issue.

Django 2.x is Python 3 only, for example. And as a webserver, a Django 1.x is going to be front and center as far as exposure goes. Plus, the attacker knows that all the other libraries on a Django 1 site are 2.7-based, even if Django itself was secure.

Python 2-to-3 migration is not that big of a deal. 40K LOC took me 3 weeks, less than a year ago, starting with a very high unittest coverage and the longtime habit of writing idiomatic 3.x code in 2.7 i.e. print(x) rather than print x. Then again, I had been thinking about it for a while, not just digging my head in the sand, pretending it wasn't a problem.

Please know what you are talking about before posting security advice, because this type of claim, if believed, would put many people at risk.

Collapse
 
pyrobits profile image
Bruno de Lima

Nice article, short reading and very informative :)