Skip to content

Server-side template injection (SSTI)

When is it relevant

A new or changed code path where user-controlled text becomes part of a template's source, not just its data. Examples: - compiling templates from strings with EJS, Pug, Handlebars, Nunjucks, Lodash _.template, FreeMarker (new Template(name, new StringReader(src), cfg)) or Velocity; - email or notification templates that users can edit; - expression engines.

It also applies when request objects are passed whole as render options.

Attack

Template syntax in the input runs on the server. In EJS, for example, <%= process.mainModule.require('child_process').execSync('id') %> runs a shell command, and in FreeMarker <#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")} does the same. That can expose secrets and environment variables or give full remote code execution. Passing req.query or req.body straight into res.render can also inject engine options.

Mitigation

  • Load templates from files or constants, and pass user input only as data.
  • If users must author templates, use a logic-less engine (Mustache, or Handlebars without custom helpers) and render them in a sandbox.
  • Pass render functions only the fields they need, never whole request objects.

Test

  • Point-in-time: put the engine's expression syntax ({{7*7}}, <%= 7*7 %>) in every field that reaches a template and check it comes out literally.
  • Continuous: a SAST rule that flags templates compiled from strings with input, and a unit test on any user-authored template renderer.

Examples

Mitigation options

Option When it fits Docs
Pass input as data, never as template source Almost always EJS
Fixed template files chosen from an allowlist The template itself must vary Express API
Logic-less engine for user-authored templates Users genuinely need to write templates OWASP injection

In Express, template injection is usually remote code execution, not just information disclosure: EJS, Pug and Handlebars compile to JavaScript.

Vulnerable — user input compiled as a template

router.post('/preview', requireAuth, (req, res) => {
  const html = ejs.render(req.body.template, { user: req.user })
  res.send(html)
})

Vulnerable — user input chooses the template

res.render(req.query.page, { user: req.user })     // also path traversal

Vulnerable — user input reaches the options object

ejs.render(template, data, req.body.options)

EJS has had remote code execution through options such as outputFunctionName and filename (for example CVE-2022-29078), so the options argument must never come from a request.

Mitigated — input is data

<!-- views/preview.ejs -->
<h1><%= title %></h1>
<div><%= body %></div>
res.render('preview', { title: req.body.title, body: req.body.body })

Mitigated — allowlist the template name

const PAGES = new Set(['about', 'pricing', 'contact'])
const page = PAGES.has(req.query.page) ? req.query.page : 'about'
res.render(page, { user: req.user })

Docs: res.render

Mitigated — logic-less engine for user templates

const output = Mustache.render(userTemplate, {
  name: customer.name,
  total: formatMoney(invoice.total),
})

Mustache has no expression evaluation, so a template can reference the values you pass and nothing else. Render it in a worker with a timeout if the templates are untrusted.

Docs: mustache.js

Bypasses to check

  • Check then change: the template string is validated or escaped, then concatenated with another fragment before compiling.
  • Any compile-from-string API, even when only part of the string is user input: a subject line, an email signature, a report header.
  • lodash.template, nunjucks.renderString, handlebars.compile, pug.compile, new Function, vm.runInNewContext.
  • Sandboxes that are not sandboxes: vm in Node shares the process and is not a security boundary.
  • Escaping applied to the rendered output rather than to the template source — by then the code has already run.
  • The template name reaching res.render from input, which combines template selection with path traversal into the views directory.

What to grep for

  • ejs.render(, ejs.compile(, renderString(, Handlebars.compile(, pug.compile(, _.template(
  • res.render( with a variable as the first argument
  • new Function(, eval(, vm.

Mitigation options

Option When it fits Docs
Pass input as data, never as template source Almost always Nunjucks API
Fixed template files chosen from an allowlist The page or partial itself must vary Nunjucks loaders
A different engine built for untrusted templates Users genuinely need to write templates LiquidJS · mustache.js

Nunjucks compiles templates to JavaScript and has no sandbox. Its docs say plainly that it isn't safe to run user-defined templates or to put user content into a template's source. Template code can reach the JavaScript Function constructor through any function it can see: the built-in globals range, cycler and joiner, any function in the context, or even a string literal's constructor. So injected template syntax is remote code execution, not just a leak of the template variables. Autoescape doesn't help: it escapes output, after the injected code has already run.

Vulnerable — user input compiled as a template

router.post('/preview', requireAuth, (req, res) => {
  res.send(env.renderString(req.body.template, { user: req.user }))
})

Vulnerable — user input concatenated into a template

const subject = env.renderString(`Welcome, ${user.name}!`, { company })

Only part of the string comes from the user, which makes it easy to miss. renderString treats the whole string as source, so a name containing {{ … }} runs.

Vulnerable — two-stage rendering

const body = env.renderString(emailTemplate, { name: user.name }) // name is data: safe
const html = env.renderString(body, { company })                   // body is source: not safe

The first render correctly treats name as data. The second compiles the first one's output, and name is now part of it.

Vulnerable — user input chooses the template

res.render(req.query.page, { user: req.user })
{% include section %}

res.render, {% include %}, {% extends %} and {% import %} all accept a name from data. FileSystemLoader blocks ../ out of the views folder, but its check is a plain prefix match (resolved.indexOf(base) === 0). So ../views-private/x.html still loads when a sibling folder's name starts with the views folder's name.

Mitigated — input is data

{# views/preview.html #}
<h1>{{ title }}</h1>
<div>{{ body }}</div>
res.render('preview.html', { title: req.body.title, body: req.body.body })
const subject = env.renderString('Welcome, {{ name }}!', { name: user.name, company })

The template source is a file or a constant; user text only ever arrives as a context value, which Nunjucks prints and never evaluates.

Docs: renderString · res.render

Mitigated — allowlist the template name

const PAGES = new Map([
  ['about', 'pages/about.html'],
  ['pricing', 'pages/pricing.html'],
])
res.render(PAGES.get(req.query.page) ?? 'pages/about.html', { user: req.user })

Map the input to a fixed path rather than checking it and then using it, so nothing the user sent ever reaches the loader. Do the same for any variable passed to {% include %}.

Docs: Nunjucks include

Mitigated — user-authored templates in an engine built for them

const { Liquid } = require('liquidjs')
const liquid = new Liquid({ ownPropertyOnly: true, strictFilters: true })

const output = await liquid.parseAndRender(userTemplate, {
  name: customer.name,
  total: formatMoney(invoice.total),
}, { renderLimit: 1000 })

Liquid templates can read the values you pass and call the filters you register, but can't call arbitrary functions. ownPropertyOnly stops lookups from walking up the prototype chain. Pass plain data, never objects with methods, and set render limits so a template can't loop forever. Mustache is the simpler choice when templates only need variable substitution.

Docs: LiquidJS options · mustache.js

Bypasses to check

  • Check then change: the user text is checked for {{ or {%, then decoded, trimmed, or concatenated with another fragment before renderString. Blocklists also miss {#, custom tag delimiters set in tags: { variableStart: … }, and whitespace-control forms like {{- and {%-.
  • Any compile-from-string API: renderString, nunjucks.compile, new nunjucks.Template(src), env.getTemplate with a custom loader that returns user text as source (a database- or CMS-backed loader).
  • Two-stage rendering: the output of one render (or a stored, already-rendered string) fed back in as source, such as email templates, notification text, or "preview".
  • Template names from input reaching res.render, {% include %}, {% extends %} or {% import %}, including the loader's prefix-match gap with sibling folders, and multiple search paths.
  • "Sandboxes" that aren't: Node's vm module and stripping constructor from the context. Template code can still reach Function through built-ins like range or a string literal's constructor.
  • Objects with methods in the render context (models, services, req, app). Even without SSTI they widen what an injected template can call.

What to grep for

  • renderString(, nunjucks.compile(, new nunjucks.Template(, new Template(
  • res.render( or env.render( with a variable as the first argument
  • {% include, {% extends, {% import, {% from followed by a variable
  • getSource( in custom loaders, tags: in nunjucks.configure
  • vm., new Function(, eval(

Mitigation options

Option When it fits Docs
Pass input as data, never as template source Almost always FreeMarker data model
Fixed template files chosen from an allowlist The page or partial itself must vary Template loading
A dedicated, locked-down Configuration for user templates Users must edit templates (reports, emails) and you accept the residual risk FAQ: untrusted templates
A logic-less engine Users only need to fill in placeholders Mustache.java · Liqp

FreeMarker's own FAQ says templates from untrusted authors aren't safe even with every option locked down. The usual way in is the ?new built-in, which instantiates any class that implements TemplateModel. FreeMarker ships two such classes that run code: freemarker.template.utility.Execute (a shell command) and ObjectConstructor (any Java constructor). In FreeMarker 2.3.x, the default new_builtin_class_resolver is UNRESTRICTED_RESOLVER, and Spring Boot doesn't change it. Injected template text is remote code execution.

Vulnerable — user input compiled as a template

public String render(String templateSource, Project project) throws Exception {
    Template template = new Template("report", new StringReader(templateSource), freemarker);
    StringWriter out = new StringWriter();
    template.process(Map.of("project", project), out);
    return out.toString();
}
<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}

This is the "customizable report template" or "email template" feature. It reuses Spring's view Configuration (FreeMarkerConfig.getConfiguration()), so it inherits the unrestricted resolver. Passing only one object (project) doesn't help, because ?new needs nothing from the data model. A template that was saved earlier and rendered later is the same sink. Look for where the source string came from, not only where it's rendered.

Vulnerable — user input concatenated into a template

String src = "Hello " + user.getDisplayName() + ", your order ${order.id} shipped.";
new Template("mail", new StringReader(src), cfg).process(model, out);

Only part of the string comes from the user. A display name containing ${…} or <#…> runs.

Vulnerable — re-rendering output, ?interpret and ?eval

<#assign inline = userText?interpret>
<@inline/>
${userExpression?eval}

?interpret compiles a string as a template at render time, and ?eval evaluates it as an expression. Both turn data into code inside a template that is itself safe. The same goes for Java code that renders a template, stores the output, and later compiles that output as a template.

Vulnerable — user input chooses the view

@GetMapping("/pages")
public String page(@RequestParam String name) {
    return "pages/" + name;          // view name from input
}

FreeMarker's loader keeps the template path inside the template root, so this usually leaks other templates rather than files. But a view name also selects Spring's view resolver: with a redirect: or forward: prefix it becomes an open redirect or an internal forward. And if Thymeleaf is also on the classpath, __${…}__ in the name is an expression injection. Map the name through an allowlist.

Mitigated — input is data

// templates/report.ftlh holds the fixed layout
Template template = freemarker.getTemplate("report.ftlh");
template.process(Map.of("name", project.getName(), "status", project.getStatus(),
                        "intro", userIntroText), out);
<h1>${name}</h1>
<p>Status: ${status}</p>
<p>${intro}</p>

The template is a file. User text arrives only as a value, which FreeMarker prints and never parses. Offer "customization" as a choice of fixed sections or fields, not as editable template source.

Docs: Configuration.getTemplate

Mitigated — allowlist the template name

private static final Map<String, String> PAGES = Map.of(
        "about", "pages/about",
        "pricing", "pages/pricing");

@GetMapping("/pages")
public String page(@RequestParam String name) {
    return PAGES.getOrDefault(name, "pages/about");
}

Docs: Spring MVC view names

Mitigated — user templates in a separate, locked-down configuration

Configuration userTemplates = new Configuration(Configuration.VERSION_2_3_33);
userTemplates.setNewBuiltinClassResolver(TemplateClassResolver.ALLOWS_NOTHING_RESOLVER);
userTemplates.setAPIBuiltinEnabled(false);
userTemplates.setTemplateLoader(null);                     // no <#include> / <#import>
userTemplates.setOutputFormat(HTMLOutputFormat.INSTANCE);  // auto-escape values
userTemplates.setObjectWrapper(new SimpleObjectWrapper(Configuration.VERSION_2_3_33));

Map<String, Object> model = Map.of(                         // plain values only
        "name", project.getName(),
        "status", project.getStatus(),
        "taskCount", tasks.size());

new Template("report", new StringReader(userSource), userTemplates).process(model, out);

ALLOWS_NOTHING_RESOLVER disables ?new entirely. SimpleObjectWrapper and a model of plain strings and numbers mean there are no Java objects whose getters the template can walk (project.class.protectionDomain…). Don't reuse Spring's view Configuration for this. Run it with a timeout, since a template can still loop. If users need only placeholders, Mustache or Liquid is a smaller surface than this.

Docs: TemplateClassResolver · setAPIBuiltinEnabled · SimpleObjectWrapper · FAQ: untrusted templates

Bypasses to check

  • Check then change: the source is checked for <# or ${, then decoded, trimmed or concatenated before new Template(...). Blocklists also miss the square-bracket syntax ([#assign …], when the configuration auto-detects it), <@…> macro calls, the legacy #{…} interpolation, and ?interpret hidden in data.
  • TemplateClassResolver.SAFER_RESOLVER treated as a sandbox. It blocks only Execute, ObjectConstructor and JythonRuntime. Any other TemplateModel class on the classpath, including your own, is still constructible.
  • Java objects in the data model. With the default DefaultObjectWrapper, getters chain freely: project.class.protectionDomain renders (verified on 2.3.33). The default member-access policy blocks the best-known escapes (getClassLoader, Class.forName), but every object you pass widens the surface. Spring beans, request, session, springMacroRequestContext or the application context in the model are much worse.
  • ?api enabled (api_builtin_enabled=true, or spring.freemarker.settings.api_builtin_enabled), which exposes the Java API of any wrapped object.
  • <#include> / <#import> in user templates resolving through the shared template loader, which reads any template in the app.
  • FreeMarker before 2.3.30, which predates DefaultMemberAccessPolicy and allows more reflection from templates. Check the version in pom.xml or build.gradle.
  • Strings rendered by Velocity, Thymeleaf (TemplateEngine.process on a string), Spring SpelExpressionParser or JEXL in the same feature: each is its own expression engine.

What to grep for

  • new Template(, new StringReader( next to a template, StringTemplateLoader, putTemplate(
  • FreeMarkerConfig, getConfiguration(), FreeMarkerConfigurer reused outside views
  • ?new, ?interpret, ?eval, ?api in templates
  • setNewBuiltinClassResolver, new_builtin_class_resolver, api_builtin_enabled, spring.freemarker.settings
  • return "…" + in @Controller methods (view name built from input)

Mitigation options

Option When it fits Docs
Templates from files only (render_template) Default; input is only ever data render_template
SandboxedEnvironment for user-authored templates Users must write templates (emails, notifications) Jinja sandbox
A logic-less format (str.format_map with a fixed dict, or string.Template) Simple placeholders such as {name} string.Template

Vulnerable — user text inside the template source

@app.get('/hello')
def hello():
    return render_template_string(f"<h1>Hello {request.args['name']}</h1>")
    # name = {{ cycler.__init__.__globals__.os.popen('id').read() }}

The input becomes part of the template, so Jinja evaluates it. Through __globals__ and __class__.__mro__, that reaches os and runs commands.

Vulnerable — "user-editable email templates" with the normal environment

tmpl = app.jinja_env.from_string(org['welcome_template'])
tmpl.render(user=user)

Mitigated — the input is data, not the template

return render_template_string('<h1>Hello {{ name }}</h1>', name=request.args.get('name', ''))

Docs: render_template_string

Mitigated — a sandbox for user-authored templates

from jinja2.sandbox import ImmutableSandboxedEnvironment
env = ImmutableSandboxedEnvironment(autoescape=True)
out = env.from_string(org['welcome_template']).render(name=user['name'], org=org['name'])  # plain values only

The sandbox blocks access to underscore attributes and unsafe methods. Pass it plain strings and numbers, never app objects, request objects or the config.

Docs: ImmutableSandboxedEnvironment

Bypasses to check

  • f-strings, % or .format() building the string passed to render_template_string or from_string.
  • Sandboxed templates given rich objects (an ORM model, request, config, g). Their methods can leak secrets or change state.
  • Old Jinja versions with sandbox escapes, such as CVE-2019-10906 and CVE-2016-10745. Check the version.
  • str.format(**user_input)-style "templates" that allow {0.__class__} attribute access. Use string.Template instead.

What to grep for

  • render_template_string(, from_string(, Template(, Environment(, jinja_env
  • SandboxedEnvironment, f" or .format( near template calls, __globals__

Resources