Skip to content

server-side-template-injection

Ensure server side templates are validated

Using arbitrary user input to create a server-side template is dangerous as it may be susceptible to server-side template injection (SSTI) and cross-site scripting attacks (XSS). Often this is equivalent to a remote code execution, depending on the capabilities of the templating language.

Examples

Insecure Example

import flask

app = flask.Flask(__name__)

@app.route("/error")
def error(e):
    template = """{  extends "layout.html"  }
{  block body  }
    <div class="center-content error">
        <h1>Oops! That page doesn't exist.</h1>
        <h3>%s</h3>
    </div>
{  endblock  }
""".format(
        # Injecting arbitrary user input inside the template!
        request.url
    )
    return flask.render_template_string(template), 404

Secure Example

import flask

app = flask.Flask(__name__)

@app.route("/error")
def error(e):
    template = """{  extends "layout.html"  }
{  block body  }
    <div class="center-content error">
        <h1>Oops! That page doesn't exist.</h1>
        <h3></h3>
    </div>
{  endblock  }
"""
    # Simply use the templating language to inject user input
    return flask.render_template_string(template, request.url), 404