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
autoescapeoption. - HTML escaping does not replace URL-scheme validation or protections for JavaScript contexts. Keep template source trusted, and do not bypass escaping by applying
safeto 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:
autoescapeescapes values rendered into HTML.- Use
select_autoescapeto enable it for selected file extensions.
- Use