Jinja2 templating with autoescape=False¶
ID: py/jinja2/autoescape-falseKind: problemSecurity severity: 6.1Severity: errorPrecision: mediumTags: - security - external/cwe/cwe-079Query suites: - python-security-extended.qls - python-security-and-quality.qls
Click to see the query in the CodeQL repository
Cross-site scripting (XSS) attacks can occur if untrusted input is not escaped. This applies to templates as well as code. Thejinja2 templates may be vulnerable to XSS if the environment hasautoescape set toFalse. Unfortunately,jinja2 setsautoescape toFalse by default. Explicitly settingautoescape toTrue when creating anEnvironment object will prevent this.
Recommendation¶
Avoid setting jinja2 autoescape to False. Jinja2 provides the functionselect_autoescape to make sure that the correct auto-escaping is chosen. For example, it can be used when creating an environmentEnvironment(autoescape=select_autoescape(['html','xml'])
Example¶
The following example is a minimal Flask app which shows a safe and an unsafe way to render the given name back to the page. The first view is unsafe asfirst_name is not escaped, leaving the page vulnerable to cross-site scripting attacks. The second view is safe asfirst_name is escaped, so it is not vulnerable to cross-site scripting attacks.
fromflaskimportFlask,request,make_response,escapefromjinja2importEnvironment,select_autoescape,FileSystemLoaderapp=Flask(__name__)loader=FileSystemLoader(searchpath="templates/")unsafe_env=Environment(loader=loader)safe1_env=Environment(loader=loader,autoescape=True)safe2_env=Environment(loader=loader,autoescape=select_autoescape())defrender_response_from_env(env):name=request.args.get('name','')template=env.get_template('template.html')returnmake_response(template.render(name=name))@app.route('/unsafe')defunsafe():returnrender_response_from_env(unsafe_env)@app.route('/safe1')defsafe1():returnrender_response_from_env(safe1_env)@app.route('/safe2')defsafe2():returnrender_response_from_env(safe2_env)
References¶
Jinja2:API.
Wikipedia:Cross-site scripting.
Common Weakness Enumeration:CWE-79.