Skip to main content

Improper Neutralization of Input using Jinja2

PY526
improper_neutralization
CWE-79
⛔️ Error
🔒 Professional Plan

This rule checks for the usage of the Jinja2 Environment class to ensure that autoescaping is enabled. Autoescaping helps prevent cross-site scripting (XSS) attacks by automatically escaping data that is rendered into HTML templates. This rule flags instances where the Environment is instantiated without autoescape=True or without using select_autoescape().

Not enabling autoescaping can lead to XSS vulnerabilities, where malicious users can inject scripts into web pages. This can result in a range of security issues, including data theft, session hijacking, and other malicious activities.

Example

from jinja2 import Environment
from jinja2 import FileSystemLoader


templateLoader = FileSystemLoader(searchpath="/")
env = Environment(loader=templateLoader)

Remediation

To fix code that is flagged by this rule, ensure that the Jinja2 Environment is instantiated with autoescape=True or by using select_autoescape(). This ensures that data rendered into templates is properly escaped, mitigating the risk of XSS vulnerabilities.

from jinja2 import Environment
from jinja2 import FileSystemLoader


templateLoader = FileSystemLoader(searchpath="/")
env = Environment(autoescape=True, loader=templateLoader)

False Positives

In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY526) or rule category name (improper_neutralization).

Fix Iconfix
from jinja2 import Environment
from jinja2 import FileSystemLoader


templateLoader = FileSystemLoader(searchpath="/")
# suppress: PY526
env = Environment(loader=templateLoader)

See also