33from sqlalchemy.ext.compiler import compiles
34
35import jinja2
36jinja2_env = jinja2.Environment( 37 loader=jinja2.FileSystemLoader( 38 os.path.join(lore.env.ROOT, lore.env.APP, 'extracts') 39 ), 40 trim_blocks=True, 41 lstrip_blocks=True 42)
43
44try:
666 env.require(lore.dependencies.JINJA)
667 import jinja2
668
669 _jinja2_env = jinja2.Environment( 670 loader=jinja2.FileSystemLoader( 671 os.path.join(os.path.dirname(__file__), 'template') 672 ), 673 trim_blocks=True, 674 lstrip_blocks=True 675 )
676 return _jinja2_env.get_template(name).render(**kwargs)
677
Using Jinja2 templates without autoescaping enabled leaves application vulnerable to [XSS attacks](https://owasp.org/www-project-top-ten/2017/A72017-Cross-SiteScripting_(XSS).
Autoescaping is the concept of automatically escaping special characters. Special characters for HTML, XML and XHTMl are &, >, <, " as well as '. These characters carry specific meanings so need to be replaced by so called entities
if you want to use them for text. Not doing so makes application susceptible to Cross Site Scripting (XSS) attacks.
When configuring the Jinja2 environment, the option to use autoescaping on input can be specified. By default, autoescaping is disabled. When enabled, Jinja2 will filter input strings to escape any HTML content submitted via template variables.
Bad practice
from jinja2 import Environment
template_env1 = Environment() # Insecure. Autoescape set to False by default
template_env2 = Environment(autoescape=False) # Insecure
Recommended
from jinja2 import Environment
template_env = Environment(autoescape=True) # Secure
References:
- Autoescaping in Jinja
- OWASP Top 10 2021 Category A03 - Injection
- OWASP Top 10 2021 Category A06 - Vulnerable and Outdated Components
- SANS Top 25
- CWE 79 - Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')