Python

Taken and summarised from https://snyk.io/blog/python-security-best-practices-cheat-sheet/

Input Sanitisation

  • schema is “a library for validating Python data structures, such as those obtained from config-files, forms, external services or command-line parsing, converted from JSON/YAML (or something else) to Python data-types.

  • bleach is “an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes.”

Major frameworks come with their own sanitation functions, like Flask’s flask.escape() or Django’s django.utils.html.escape(). The goal of any of these functions is to secure potentially malicious HTML input like:

>>> import bleach
>>> bleach.clean('an XSS <script>navigate(...)</script> example')
'an XSS &lt;script&gt;navigate(...)&lt;/script&gt; example'

SQL Injection

A typical example is an SQL injection. Instead of stitching strings and variables together to generate an SQL query, it is advisable to use named-parameters to tell the database what to treat as a command and what as data.

# Instead of this …
cursor.execute(f"SELECT admin FROM users WHERE username = '{username}'");
# ...do this...
cursor.execute("SELECT admin FROM users WHERE username = %(username)s", {'username': username}); 

Or even better, use Object-Relational Mapping (ORM), such as sqlalchemy, which would make the example query look like this:

query = session.query(User).filter(User.name.like('%{username}'))

Here you get more readable code, as well as ORM optimizations like caching, plus more security and performance!

Usage of Virtual Envrionments

This means that instead of using a global Python version and global Python dependencies for all your projects, you can have project-specific virtual environments that can use their own Python (and Python dependency) versions!

As of Python version 3.5, the use of venv is recommended and with version 3.6 pyvenv was deprecated.

Disable Debugging Mode

By default, most frameworks have debugging switched on. For example, Django has it enabled in settings.py. Make sure to switch debugging to False in production to prevent leaking sensitive application information to attackers.

String Formatting

Python has a built-in module named string. This module includes the Template class, which is used to create template strings.

Consider the following example.

from string import Template
greeting_template = Template(“Hello World, my name is $name.”)
greeting = greeting_template.substitute(name=”Hayley”)

For the above code, the variable greeting is evaluated as: “Hello World, my name is Hayley.”

This string format is a bit cumbersome because it requires an import statement and is less flexible with types. It also doesn’t evaluate Python statements the way f-strings do. These constraints make template strings an excellent choice when dealing with user input.

Last updated