Jinja autoescaping is disabled

Jinja autoescaping is disabled

Description

When Jinja autoescaping is disabled, user input rendered as HTML may not be encoded appropriately. This can allow cross-site scripting (XSS). Enable autoescaping when rendering untrusted values in HTML.

Potential impact

  • XSS: An attacker may inject scripts that run in another user’s browser, potentially compromising their account.
  • Phishing: Malicious links or fake login forms may be shown to users.
  • Data theft: An attacker may obtain sensitive user information.

Remediation

  • Enable the Jinja environment’s autoescape option.
  • HTML escaping does not replace URL-scheme validation or protections for JavaScript contexts. Keep template source trusted, and do not bypass escaping by applying safe to user input.

Examples

Before

python
# Unsafe Jinja2 code
from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('template.html')
html_content = template.render(user_input=user_input)

After

python
# Safe Jinja2 code
from jinja2 import Environment, FileSystemLoader, select_autoescape

env = Environment(
    loader=FileSystemLoader('templates'),
    autoescape=True
    # Or use `autoescape=select_autoescape(['html', 'xml'])` for selected extensions
)
template = env.get_template('template.html')
html_content = template.render(user_input=user_input)

Explanation:

  • Before: User input is rendered as HTML without automatic escaping, allowing injected markup or scripts to be interpreted by the browser.
  • After: autoescape escapes values rendered into HTML.
    • Use select_autoescape to enable it for selected file extensions.

References