== Why is this an issue?

User-provided data, such as URL parameters, POST data payloads, or cookies, should always be considered untrusted and tainted. Constructing HTML content directly from tainted data enables attacker(s) to inject special crafted values to abuse template engine's rendering process. Successful server side template injection (SSTI) attack can lead to arbitrary file read or operating system commands execution.


Template engine are used by web server to render rich HTML content, generally web pages or emails. Template injection usually happens when the template content has been dynamically generated from unvalidated user inputs.


This problem can be avoided by:

* Using static template that are read from files rather than building templates dynamically
* Using template variables to inject dynamic values at render time
* Using template engine advanced control structure (like blocks or include) to dynamically build complex templates


=== Noncompliant code example

[source,python]
----
from flask import request, render_template_string

# /hello?username={{config}} will display the entire flask configuration and potential secrets
@app.route('/hello')
def hello():
    username = request.args.get('username')
    template = f"<p>Hello {username}</p>" # User input is used directly in the string to be rendered
    return render_template_string(template) # Noncompliant
----


=== Compliant solution

[source,python]
----
from flask import request, render_template_string

@app.route('/hello')
def hello():
    username = request.args.get('username')
    template = "<p>Hello {{ name }}</p>"
    return render_template_string(template, name=username) # Compliant
----


== Resources

* https://owasp.org/Top10/A03_2021-Injection/[OWASP Top 10 2021 Category A3] - Injection
* https://owasp.org/www-project-top-ten/2017/A1_2017-Injection[OWASP Top 10 2017 Category A1] - Injection
* https://cwe.mitre.org/data/definitions/94[MITRE, CWE-94] - Improper Control of Generation of Code
* https://medium.com/@nyomanpradipta120/ssti-in-flask-jinja2-20b068fdaeee[SSTI in Flask/Jinja2]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Change this code to not construct HTML content directly from user-controlled data.


endif::env-github,rspecator-view[]
