Template engines, such as Twig, Django, and Jinja2, provide automatic escaping of template variables to prevent cross-site scripting (XSS) attacks, but this protection can be explicitly disabled.

Why is this an issue?

Template engines provide auto-escaping as a safety mechanism that transforms HTML special characters in variable output before rendering, preventing user-controlled input from being interpreted as HTML or JavaScript by the browser. Disabling this protection — through settings like autoescape: false, escape-bypass filters like |safe, or equivalent configuration — allows untrusted input to pass through unmodified and be executed by the browser as markup or script.

What is the potential impact?

When auto-escaping is disabled, an attacker who can control the content of template variables can inject malicious HTML or JavaScript into pages served to other users. An attacker could steal session tokens, redirect users to phishing pages, or perform unauthorized actions on behalf of the victim.

How to fix it in Django Templates

Code examples

The following examples configure the template engine to disable its auto-escaping feature, allowing template variables to be rendered without HTML encoding.

Noncompliant code example

<!-- Django templates -->
<p>{{ variable|safe }}</p><!-- Noncompliant -->
{% autoescape off %}<!-- Noncompliant -->

Compliant solution

<!-- Django templates -->
<p>{{ variable }}</p>
{% autoescape on %}

How to fix it in Jinja

Code examples

The following examples configure the template engine to disable its auto-escaping feature, allowing template variables to be rendered without HTML encoding.

Noncompliant code example

<!-- Jinja2 templates -->
<p>{{ variable|safe }}</p><!-- Noncompliant -->
{% autoescape false %}<!-- Noncompliant -->

Compliant solution

<!-- Jinja2 templates -->
<p>{{ variable }}</p>
{% autoescape true %}

Resources

Documentation

Standards