Skip to content

Lesson 4 of 20 · 16m

Template injection: when user input becomes program source

Why render_template_string('x' + name) is RCE, how {{config}} leaks secrets, and the sandboxed engines that survive user-authored templates.

Template engines compile {{7*7}} into code — that's the product. So when user input lands in the template source instead of the template's data, the engine evaluates it:

return render_template_string("Hello " + name)   # name = "{{7*7}}" → renders "Hello 49"

That is server-side template injection, and the distance from {{7*7}} to a shell is short. In Jinja2, {{config.items()}} reads your SECRET_KEY straight out of the app config — and a stolen signing key means forged sessions. The classic escalation climbs the object graph — {{''.__class__.__mro__[1].__subclasses__()}} — hunting for a class that reaches os or subprocess.Popen; published payloads like {{cycler.__init__.__globals__.os.popen('id').read()}} do it in one expression — in Flask/Jinja, the built-in lipsum global reaches os through __globals__ the same way. Twig's {{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} and Freemarker's <#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")} are the same exploit in different syntax.

The wrong mental model is "the template is just HTML with placeholders — escaping the value is enough." XSS escaping operates on output. SSTI happens before output exists: the attacker's text became program source. The same shape nails every eval-family API: eval, new Function, setTimeout(string), Python's exec, Ruby's eval, Freemarker's ?eval — a string slot that turns out to be an interpreter.

This bug class is bigger than template syntax. Equifax 2017 was expression injection: CVE-2017-5638 — Apache Struts evaluated the Content-Type header as an OGNL expression, and 147 million records plus a settlement of up to $700M followed. SpEL, MVEL, Java EL ${…}, and even Python's str.format ({0.__class__} leaks attributes through a format string) share the same shape: a string slot that turns out to be an interpreter.

From 49 to id

The exploit chain is mechanical. {{7*7}} returning 49 confirms evaluation. {{config}} or {{config.items()}} dumps app config — SECRET_KEY means forged session cookies, so secret disclosure alone can end the game. When nothing juicy is reachable directly, the attacker walks the object graph: __class__ → __mro__ → __subclasses__() and then whatever exposes os, subprocess, or a file read. Sandboxed engines add walls (SandboxedEnvironment blocks the dunder climb), which is why published escapes keep appearing — the sandbox raises the cost; it doesn't end the sport.

What actually fixes it

Never concatenate input into template source. Pass it as data — the engine escapes it and {{7*7}} stays literal text:

return render_template("greet.html", name=name)

If users genuinely author templates — CMS themes, notification builders, report engines — use a sandboxed or logic-less engine: Jinja2's SandboxedEnvironment, Mustache/Handlebars with an allowlisted helper set, Twig's sandbox mode with explicit allowed tags and filters. Run rendering under least privilege anyway; sandbox bypasses are a recurring CVE category — December 2024 shipped two in Jinja alone: CVE-2024-56201 through an indirect str.format path, CVE-2024-56326 through the |attr filter.

Audit the dynamic calls. render_template_string, Template(user_input), eval, Freemarker's StringTemplateLoader fed by request data, SpEL parseExpression on input — each is an SSTI doorway. And note that autoescaping (Twig autoescape, Jinja autoescape=True) protects against XSS in values; it does nothing for SSTI in source.

Related and often co-present: format-string and log-template injection — attacker text used as a %s/{attr} format string or a log template. Same rule: input is data, never the format.

Testing for it

Probe every string that lands in a rendered page with {{7*7}}, ${7*7}, #{7*7}, <%=7*7%>, *{7*7} and {{config}}. Probe {{request.args}} too — in Flask it echoes query params back through the render context. A 49, a populated config dict, or a rendered expression where your literal text should be means the engine is eating source — and from there it's a short walk to id running on your box.

Practice

Data into context, never into source; sandboxed engines for user-authored templates; render_template_string, Template(, parseExpression and eval in the review greps; and keep the engine current, because gadget-finding is a mature sport.

Keep reading

Related articles from the SudoSecurity blog.