← All posts
Julien Delange Wednesday, October 19, 2022

Python Jinja2: always autoescape to avoid XSS attacks

Share

AUTHOR

Julien Delange, Founder and CEO

Julien is the CEO of Codiga. Before starting Codiga, Julien was a software engineer at Twitter and Amazon Web Services.

Julien has a PhD in computer science from Universite Pierre et Marie Curie in Paris, France.

See all articles

What is Python Jinja2?

The Jinja project is a templating engine for Python. With Jinja, you can generate HTML documents, configuration files, etc.

Jinja2 is the current version of the project. It is widely used in many other Python projects for writing micro-services, websites, etc.

What is an XSS attack?

An XSS attack is when a user includes malicious code that is rendered to other users. A common attack is sending JavaScript code in some data that is later rendered for many other users. The script can then gather data about the user, redirect them, etc.

There are two ways to mitigate XSS attacks:

  1. Always validate the user inputs and rejects malicious/dangerous code
  2. Escape values when rendering HTML

How the Python Jinja2 module can lead to XSS attacks?

Jinja2 allows you to render template and choose to escape values passed to the template. By default, autoescape is set to True.

The real issue is when the developer sets the autoescape value to False. In this case, the templating engine no longer escapes values, which may lead to XSS attacks.

For example, the following code will not use autoescape.

env = Environment(loader=PackageLoader("foobar"),
                  autoescape=False)
template = env.get_template("mytemplate.html")

How to avoid XSS attacks when using Jinja2 in Python?

To avoid XSS issues, ensure autoescape is set to True when you initialize Jinja2.

The following code ensures that autoescape is enabled.

env = Environment(loader=PackageLoader("foobar"),
                  autoescape=True)
template = env.get_template("mytemplate.html")

Automatically detect unsafe usage of Jinja2?

Codiga provides IDE plugins and integrations with GitHub, GitLab, or Bitbucket to detect when autoescape is set to False for Jinja2. This dedicated rule will ensure that autoescape is set to True when using Jinja2.

Check autoescape for Jinja2

To use this rule consistently, all you need to do is to install the integration in your IDE (for VS Code or JetBrains) or code management system and add a codiga.yml file at the root of your profile with the following content:

rulesets:
  - python-security

It will then check all your Python code against 100+ rules that detect unsafe and insecure code and suggests fixes for each of them.

More resources

Schedule a demo

Code analyzed in seconds with Codiga Automated Code Reviews.

Write code faster with the Codiga Coding Assistant.

Let's talk!