A template engine is a small compiler. It takes a template, turns its expressions into code, and runs that code against the data you pass in. Server-side template injection (SSTI) happens when user input ends up in the template instead of the data. The attacker is no longer filling in a blank: they are writing the program.
In most engines that leads to remote code execution, because template expressions can reach the language's object model. This post covers the one distinction that prevents SSTI, how it shows up in Jinja2, Twig, EJS, Java and Go, why sandboxes are not a fix, and what to do when users genuinely need to write templates.
Template or data: the whole bug in two lines
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.get("/hello")
def hello():
name = request.args.get("name", "")
return render_template_string(f"<h1>Hello {name}</h1>") # name becomes template source@app.get("/hello")
def hello():
name = request.args.get("name", "")
return render_template_string("<h1>Hello {{ name }}</h1>", name=name) # name is dataIn the first version, ?name={{7*7}} renders Hello 49. That is the usual probe: if arithmetic is evaluated, input is being compiled. From there, Jinja2 expressions can walk from any object to its class, to module globals, and to os, which is a short step to running commands as the web server.
In the second version the template is a constant and name is a value in the context. Jinja2 escapes it for HTML, and nothing the user types is ever compiled. Every fix for SSTI is a variation of this: keep the template constant, pass input only as context.
Where SSTI appears, engine by engine
| Language | Engine | Calls that compile a string as a template |
|---|---|---|
| Python | Jinja2, Flask | render_template_string(src), Environment().from_string(src), Template(src) |
| Python | Django, Mako | django.template.Template(src), mako.template.Template(src) |
| PHP | Twig | $twig->createTemplate($src), the template_from_string() function |
| PHP | Smarty | display() / fetch() with a string: or eval: resource |
| JavaScript | EJS, Pug, Handlebars, Nunjucks | ejs.render(src), pug.compile(src), Handlebars.compile(src), nunjucks.renderString(src) |
| Java | FreeMarker, Velocity | new Template(name, new StringReader(src), cfg), Velocity.evaluate(ctx, out, tag, src) |
| Go | text/template, html/template |
template.New("x").Parse(src) |
| Ruby | ERB, Liquid | ERB.new(src), render inline: src |
The source string is rarely request.args directly. It is usually built by concatenation ("Dear " + name + ",\n" + body), loaded from a database row a user can edit, or assembled from a "custom message" setting. Stored template injection, where a value saved today is rendered as a template by a background job next week, is the variant code review misses most often.
Twig: createTemplate versus render
// Vulnerable: the request value is part of the template source
$template = $twig->createTemplate('Hello ' . $_GET['name']);
echo $template->render([]);// Safe: a fixed template file, the request value passed as context
echo $twig->render('hello.html.twig', ['name' => $_GET['name'] ?? '']);createTemplate exists for templates stored outside the filesystem, such as rows in a CMS table. That is legitimate, but then every author of that row can run Twig code, so it must be restricted to trusted administrators and combined with the sandbox discussed below.
When the data slot is not just data
Passing input only as context is necessary but not always sufficient. Some engines read options from the same object as the variables. CVE-2022-29078 in EJS 3.1.6 (NVD score 9.8) allowed template injection through settings[view options][outputFunctionName]. An Express handler that rendered with the whole query object, res.render("profile", req.query), let an attacker set an internal option and inject code that ran when the template compiled.
// Risky: the entire query object becomes locals, including option-shaped keys
app.get("/profile", (req, res) => res.render("profile", req.query));
// Better: pass only the named values the template uses
app.get("/profile", (req, res) => res.render("profile", { name: String(req.query.name ?? "") }));The same rule protects against a quieter leak: passing os.environ or process.env into a template context makes every secret in the environment one expression away from any template author.
Sandboxes reduce risk; they do not remove it
Jinja2 and Twig both ship sandboxes that restrict attribute access and function calls. They are useful, and they keep getting bypassed:
- CVE-2024-56326: before Jinja 3.1.5, a stored reference to a string's
formatmethod could be passed to a filter and escape the sandboxed environment. - CVE-2025-27516: before Jinja 3.1.6, the
|attrfilter gave another route to the plainformatmethod and arbitrary code. - CVE-2024-45411: under some circumstances Twig did not run its sandbox security checks. Fixed in 1.44.8, 2.16.1 and 3.14.0.
The Jinja sandbox documentation is direct about it: "The sandbox alone is not a solution for perfect security." It also warns that a small template can produce huge output, and recommends running with CPU and memory limits and passing only the data a template needs.
When users must write templates
Email templates, invoice layouts and notification messages are often user-authored by design. Options, from strongest to weakest:
- Use a logic-less format. Plain placeholder substitution (
Hello {{first_name}}) with a fixed list of allowed variable names, implemented with a string replace or a logic-less engine, cannot run code. - Render in isolation. If you need a full engine, render in a separate worker with no credentials, no network, a time limit and a memory limit.
- Sandbox, patch and minimise. Use the engine's sandbox, keep it on the latest release, use immutable sandboxes where offered (Jinja's
ImmutableSandboxedEnvironment), and pass small plain dictionaries rather than ORM objects with methods. - Restrict who can author. Treat template authoring as a privileged permission, and audit changes to stored templates.
Go is a partial exception: its templates cannot import packages, but Parse on user input still lets the author call any exported method on the data you pass, and text/template does no HTML escaping at all. Keep templates constant there too, and use html/template for HTML.
Review checklist
- Grep for the compile calls in the table. Each argument should be a constant or a file name chosen by the code.
- Follow concatenations and f-strings into template calls; they are the most common source.
- Find templates loaded from the database and check who can edit them.
- Check that render calls pass a named, minimal context, not
req.query,req.body,request.__dict__or the environment. - Pin and patch template engines like any other parser.
Finding SSTI with Vulkro
Vulkro Core traces request data into template compilation in each supported language:
vulkro scan . --format json > findings.json
vulkro explain py-taint-ssti-001| Rule | What it flags |
|---|---|
py-taint-ssti-001 |
Request data reaching render_template_string, from_string or a Template(...) constructor |
js-taint-ssti-001 |
Request data reaching EJS, Pug, Handlebars and similar compile or render-string calls |
java-taint-ssti-001, java-velocity-param-template-splice |
Request data compiled by a Java template engine or spliced into a Velocity template |
go-taint-ssti-001 |
Request data parsed as a Go template |
php-ssti |
A superglobal in a Twig createTemplate / render template argument, or a Smarty string: / eval: resource |
RUBY-SSTI-001 |
A request value compiled with render inline:, ERB.new or Liquid |
process-env-in-template-context |
The whole process environment passed into a runtime-compiled template context |
A constant template name with request data in the context does not fire, which is exactly the fixed pattern above.
FAQ
What is server-side template injection?
A vulnerability where user input is compiled as part of a template instead of being passed in as data. Because template expressions can reach the host language's objects, it usually leads to remote code execution on the server.
Is render_template_string always vulnerable?
No. render_template_string("Hello {{ name }}", name=value) is safe because the template is constant and the value is data. It is vulnerable when user input is concatenated or formatted into the template string itself.
Does the Jinja2 sandbox prevent SSTI?
It reduces the impact, but it is not a complete defence. Jinja's own docs say the sandbox alone is not a solution for perfect security, and sandbox escapes were fixed in Jinja 3.1.5 and 3.1.6. Keep templates constant wherever possible.
See the API security use case and the Python language docs, or start a 14-day trial. Related: insecure deserialization in Python and command injection in Node and Python.