Template engines, such as 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

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

from jinja2 import Environment

env = Environment() # Noncompliant: New Jinja2 Environment has autoescape set to false
env = Environment(autoescape=False) # Noncompliant:

Compliant solution

from jinja2 import Environment
env = Environment(autoescape=True) # Compliant

Resources

Documentation

Standards