A scanner flagged server-side template injection. Is it real? Confirming an SSTI finding from a DAST scan

DedSec Security Research ·

Here is a hypothetical. A dynamic scan of a web application returns four results from its template-injection checks. The first, titled "Server-side template injection (arithmetic evaluation)" and rated high, is on /search. The scanner appended ${3482*2865} to the q parameter and the product appeared in the response. The second, also rated high, is on /preview, where the scanner's {{7*'7'}} came back as 49. The finding names the engine as Twig and links PHP remediation guidance. The third is /newsletter/signup, which got a "Thanks, check your inbox" page for every probe and was reported clean. The fourth is /profile, which also came back clean.

The two highs get escalated, and /search goes to the search team because the title says "server-side". The PHP advice for /preview goes to a team that writes Node.js. The two clean endpoints are not looked at again. As in the earlier posts in this series, each decision rests on the title rather than on what the scanner observed and what that observation can prove. The /search product came from a "quick maths" answer box that multiplies any two numbers it finds in a query, so nothing was compiled as a template. The 49 on /preview is real template injection, but in our lab Nunjucks gave 49 for that probe too, as did AngularJS and Vue in a browser, so the engine name was a guess. /newsletter/signup renders the input into a welcome email after the response has gone, so no response could ever show the result. /profile sits behind a cache that ignores the query string, and the probes were answered from it.

This post is for whoever is holding a template-injection finding from a dynamic scan, or a clean result they are about to rely on. It covers:

It is the sixteenth post in a series about confirming DAST findings. The earlier ones cover reflected XSS, SQL injection, OS command injection, Nuclei template matches, ffuf content discovery, path traversal, open redirect, SSRF through URL-fetch parameters, XXE, CRLF header injection, Host header injection, HTTP request smuggling, CORS misconfiguration, JWT validation and Arjun parameter discovery. The nearest neighbours are the XSS post, because a template injection point usually reflects its input first, and the command-injection post, because the end state of most server-side template injection is code execution.

Sources, and how each was checked. We made the measurements below on our test machine on 4 November 2026. It runs Ubuntu 24.04.4 on a virtual machine with two vCPUs of an AMD EPYC 9354P, and every server was bound to 127.0.0.1. The software was:

We read James Kettle's PortSwigger research paper "Server-Side Template Injection", published 5 August 2015, the OWASP Web Security Testing Guide v4.2 entry WSTG-INPV-18, the MITRE entry for CWE-1336 and the Jinja 3.1 sandbox documentation, all on the same day. Every quotation and claim attributed to them below was checked against those copies. Where we describe what a Nuclei template does, we read it in the cloned repository.

We did not test Twig, Smarty, FreeMarker, Velocity, Thymeleaf, ERB, Razor or any other PHP, Java, Ruby or .NET engine, because none of those runtimes was on the machine. We did not run any of the out-of-band templates, which execute a command on the target, or the Twig and Smarty templates, which do the same against engines we did not have. We did not run any other Nuclei template, any other scanner, a browser-based scanner, or a real WAF or CDN. We tested only query-string parameters, not request bodies, headers or cookies. We did not attempt to escape Jinja2's sandbox, and we did not test ImmutableSandboxedEnvironment, Django with DEBUG on, or any older engine version. The opening scenario is hypothetical. The numbers measure the engines and the one Nuclei template named above, at the versions stated, against our lab, and none of them measures AppSecD or how any product configures Nuclei.

What template injection is, in mechanism

A template engine turns a template, which is source code in a small language, plus a set of data into text. The safe pattern hands user input to the engine as data: render("Hello {{ name }}", name=user_input). The engine parses the template, which the developer wrote, and inserts the value wherever the template says. Whatever the value contains, it is never parsed.

Template injection is the other pattern: user input becomes part of the template source. In Python it is often an f-string or a concatenation passed to render_template_string or Environment().from_string. In Node.js it is a string passed to renderString, compile or render. Two common reasons are a "custom greeting" or "email template" feature that lets users write templates on purpose, and a developer who built the string first and rendered it second without noticing that the result is parsed. Either way the engine parses the input, and whatever the template language can express, the input can express.

What that language can express is what makes this a finding of its own. In Jinja2, Tornado, Mako, Nunjucks, EJS and Pug, expressions are general enough to walk from a value to its class, and from there to a module that can run commands. Kettle's paper is the standard reference for that path and for the sandbox escapes he demonstrated in 2015. CWE-1336 (Improper Neutralization of Special Elements Used in a Template Engine) is the usual classification, and MITRE lists it as a child of CWE-94 (Improper Control of Generation of Code). The entry also notes that template engines "can be used on the server or client, so both 'sides' could be affected by injection", which matters below.

How the probes work

Kettle's paper divides detection into two contexts, and WSTG-INPV-18 follows it.

Plaintext context. The input lands in the template's text, as in "Hello " + name. The probe is an expression in each common syntax: {{7*7}}, ${7*7}, <%= 7*7 %> and #{7*7}. If the response contains 49 where the probe was, something evaluated it. The arithmetic is chosen because the result is a string that does not appear in the request, so a match cannot be a plain echo. WSTG lists a{{bar}}b, a{{7*7}}, {var}, ${var}, {{var}}, <%var%> and [% var %] as common expressions to try.

Code context. The input lands inside an expression that already exists, as in "{{ user." + field + " }}". An arithmetic probe here is a syntax error or a lookup of an attribute that does not exist, and neither shows a product. Kettle's method is to break out of the expression: username}}<tag> closes it and puts an HTML tag after it.

Identification. Kettle describes a decision tree of engine-specific payloads, and gives {{7*'7'}} as a probe with two distinct successes: "49 in Twig, 7777777 in Jinja2, and neither if no template language is in use". Twig coerces the string to a number, and Python repeats the string seven times.

Errors. A probe with invalid syntax, often a "polyglot" such as ${{<%[%'"}}%\. that opens and fails to close several syntaxes at once, makes most engines raise a parse error. Kettle notes that the error message sometimes names the engine. The status code alone shows only that something failed.

Out of band. When nothing in the response reflects the rendered output, a scanner can send a payload that makes the server contact an address the scanner watches. For template injection, contacting anything means running code.

The claim a finding must support

An exploitable server-side template injection is a conjunction of three things:

  1. The input reaches the template source, not the template's data. The evidence has to show an evaluation that only a template parser would perform, distinct from an echo, a calculator, a cached response or a browser.
  2. The evaluation happens on the server. A browser-side template engine evaluating the same syntax is a different finding with a different impact.
  3. The engine and its configuration allow something that matters. That means reading data from the template's context, reaching objects outside it, or running code. Which of these is possible depends on the engine, any sandbox, and what the application passed in.

An arithmetic match speaks to point 1 only, and only weakly when the probe was 7*7. The rest of this post is about what turns it into points 1, 2 and 3, and what makes it look like them when it is not.

What nine engines did with the same probes, measured

We rendered each probe string as the template source in each engine, in-process, with an empty context. The probes we also sent over HTTP, to one lab endpoint per engine with alice in front of each probe, gave the same results. Chameleon was tested only in-process.

The Python results were the same with Jinja2's SandboxedEnvironment as with a plain Environment: arithmetic is something a sandbox is meant to allow.

Four things follow.

No single syntax covers the set. Each of the four plaintext probes found between one and three of the nine engines. A scanner that sends one syntax tests a few engines, not template injection in general.

**49 for {{7*'7'}} does not mean Twig.** We could not test Twig. In our set, the engine that gave 49 for that probe was Nunjucks, and in a browser, AngularJS and Vue did the same (see below). Every JavaScript-based engine we tried that has arithmetic gave 49 in whichever syntax it evaluates, because JavaScript's * converts '7' to a number. Every Python engine that evaluated the expression gave 7777777. So the probe tells you how the expression language treats a string times a number: Python-like or PHP- and JavaScript-like. Kettle's tree uses it as one branch among several, not as the whole answer.

Two engines have no arithmetic at all. Django's template language raised TemplateSyntaxError (Could not parse the remainder: '*7' from '7*7'), and Handlebars raised a parse error on every {{...}} probe we sent that contained an operator or a filter. Both are injectable when input reaches the template source, and other probes show it. Over HTTP, the Django endpoint returned ABC for {{'abc'|upper}} and 14 for {{ 7|add:7 }}. The Handlebars endpoint returned yes for {{#if 1}}yes{{/if}} and swallowed a {{! c }} comment. An arithmetic-only check finds neither.

The polyglot errored in eight of ten configurations. Jinja2 (plain and sandboxed), Mako, Tornado, Django, Nunjucks, Handlebars and EJS all raised an error. Chameleon and Pug rendered it as literal text.

Telling engines apart without running anything

These probes separated the engines in our set. Each one reads only what the template language itself provides.

A scanner's view of the lab, measured

We ran reflection-ssti three times against each of 19 lab endpoints, each with one query parameter, and counted the requests it sent from Nuclei's trace log. The template is short enough to describe in full. It picks two random integers between 1000 and 9999, and sends 14 payloads in turn, one per syntax, each wrapping the expression first*second. It appends each payload to the parameter's existing value, matches when the product appears in the response body, and stops at the first match. The random factors are a good design choice: a seven- or eight-digit product is unlikely to appear by chance, so the template avoids the most naive false positive, a page that already contains 49.

Every endpoint gave the same result in all three runs.

So on the 19 endpoints, the template reported 7 matches, of which 6 were template injection. It sent all 14 requests and found nothing on 12 endpoints, 7 of which had server-side template injection.

The payload that never arrived

Pug evaluates #{...}, and the template's seventh payload is exactly that. In Nuclei's debug output, the request line was GET /pug/greet?name=alice#{1717*7859} HTTP/1.1, with the # sent unencoded. Our Node.js server parsed everything after # as a URL fragment, and the response was <p>Hello alice</p>. We sent the same raw request line to the Flask app with a socket and it did the same. Encoded as %23%7B7*7%7D, the probe returned Hello alice49. The twelfth payload, a Velocity #set(...) expression, met the same fate. In our run, a payload that starts with # in a query string tested nothing, and the result looked the same as a clean one.

What scanners flag that is not server-side template injection

What scanners miss

Blind and out-of-band cases

We built three endpoints that render the input with a plain Jinja2 Environment and never show the result.

Synchronous, errors swallowed (/blind/sync). The template is rendered during the request, the output is thrown away, and any exception is caught. Every probe got the same page with a 200, including a syntax error. Time was the only signal. Over five requests each, the baseline had a median of 0.004 seconds. A nested loop of 1,000 by 1,000 iterations, which prints the outer counter, had a median of 0.168 seconds. At 3,000 by 1,000 the median was 0.573 seconds, and the slowest of the five was 0.663. The delay scaled with the loop, which is the evidence. A loop is a pure template construct and needs no access to anything outside the engine. It does spend the server's CPU, so on a system you do not own, keep it small and stop once the delay scales.

Synchronous, errors surface (/blind/err). The output is discarded, but an exception becomes a 500. alice{{7*7}} got a 200 and alice{{7*}} a 500. alice{{ 'a' }} got a 200 and alice{{ 'a' } a 500. The evidence is the pair: a valid expression succeeds and a minimally broken one fails. On /brace500, which has no template, all four probes got a 500, so the pair does not form there.

Asynchronous (/blind/async). The request puts the input on a queue and returns "Thanks, check your inbox". A worker renders a welcome email later. Every probe got the same page, including a syntax error. Response time did not follow the loop: the medians were 0.002, 0.008 and 0.015 seconds for the baseline and the two loop sizes. The outbox, which only the system's owner can read, contained Dear alice49, welcome. and render failed: TemplateSyntaxError. A response-based check cannot see this. Without code execution, the evidence has to come from wherever the output goes: the email, if the tester controls the address, or the logs.

Out of band. The nuclei-templates repository has 19 out-of-band SSTI templates in dast/vulnerabilities/ssti/oob/. We read jinja2-oob, mako-oob and tornado-oob. Each payload reaches Python's os module and runs nslookup against the scanner's interaction host. The Jinja2 and Mako payloads walk to it from an object the template can reach. The Tornado payload imports it with a template {% import os %} directive. A DNS lookup is a harmless command, but it is a command, and the template's match is proof of code execution on the target. That is the strongest evidence a template-injection check can produce. It is also an action a tester needs explicit authority for, on a system that may belong to someone else. We did not run these templates. On our own lab, a chain of the same shape that ran echo executed under a plain Jinja2 Environment and raised SecurityError under SandboxedEnvironment. So against a sandboxed Jinja2 endpoint, an out-of-band check of this shape reports nothing, while the arithmetic check still matches.

The sandbox question

Jinja2 ships SandboxedEnvironment, and its documentation says it "can be used to render untrusted templates", intercepting attribute access, method calls, operators and more. The same page says "The sandbox alone is not a solution for perfect security", warns that a small template can produce a very large output, says to run the application with limits on CPU and memory, and says to pass only the data relevant to the template. We sent the same probes to the Flask render_template_string endpoint, which uses a plain environment, and to a SandboxedEnvironment endpoint whose context held one user object.

Three readings follow.

In the plain environment, the probes reached outside the template without running anything. Flask's template context included its config object, so {{ config.SECRET_KEY }} returned the application's signing key. With Flask, that key signs the session cookie. 788 is the number of classes the interpreter had loaded, reached from an empty string. posix is an attribute of the os module, reached from a template global. None of these ran a command, and the last two show that the path to one is open. On a system you do not own, stop before the first of them.

In the sandbox, the object-graph paths were closed and the context was not. The sandbox blocked every underscore attribute we tried. It also returned tok_lab_7f2e91 from {{ user.api_token }}, because api_token is an ordinary attribute of an object the application passed in. The sandbox protects Python's internals, not your data. Whatever the template can reach through its context, an injected template can print.

The sandbox limited ranges, not work. 'a'*50000000 built a 50-million-character string in 0.046 seconds inside the sandbox. A nested loop of 2,000 by 1,000 iterations completed in 0.081 seconds. The documentation says this directly: the sandbox needs resource limits around it.

So a sandbox changes the severity of a template-injection finding without removing it. It is the right tool when users are supposed to write templates. For the bug where input was concatenated into a template by accident, the fix is to stop doing that. We did not test sandbox escapes, which is the subject of most of Kettle's paper, or any other engine's sandbox.

Confirming a finding by hand

The procedure below is general practice. All of it needs authorisation to test the target, and should use a test account. Steps 6 and 7 need more than that. Step 6 goes towards code execution, and step 7's loop spends the server's CPU, so both need explicit authority for those actions as well.

  1. Reproduce with your own numbers. Send {{1337*7331}}, or the syntax that matched, with factors the scanner did not use. Look for 9801547 and for the absence of the probe text. Then send it in a way that cannot be served from the same cache entry: vary something that is part of the cache key, or send it to the origin directly if you can reach it. A different query string is not enough on its own. In our lab nginx keyed on the path alone, so query strings changed nothing. Confirm with any cache-status header, such as X-Cache, and with any timestamp in the body.
  2. Check that a template parser is responsible, not a feature. Send the same arithmetic in the other syntaxes. A template engine accepts one or two of them. A calculator accepts all of them, or the bare 1337*7331 with no delimiters.
  3. Check where it is evaluated. Fetch the page with curl and read the raw body. If the raw body holds the literal probe and only the browser shows the product, the finding is client-side.
  4. Send a non-arithmetic probe. Try a comment such as {# x #}, which should vanish, a filter such as {{'abc'|upper}}, and a minimally broken expression next to a valid one, such as {{ 'a' } against {{ 'a' }}. Only a parser explains all three.
  5. Identify the engine with the probes in the fingerprinting section. If an error page shows a stack trace, it usually names the engine.
  6. Establish reach without executing anything. In Jinja2, {{ ''.__class__ }} returned <class 'str'> without a sandbox and empty output with one, so it shows whether underscore attributes are blocked, and that tells you whether a sandbox is in place. If you are authorised to go further, {{ cycler.__init__.__globals__.os.name }} shows that the os module is reachable without calling anything in it. Do not read config, environment variables or files on a system you do not own: a secret you have printed is a secret that needs rotating.
  7. For blind cases, use the error differential or a small, scaling loop. For asynchronous rendering, put the probe where the output goes, such as an email you control. Run out-of-band payloads only with authority to execute code.
  8. Keep the evidence: each request and response pair, the engine and how you identified it, whether a sandbox is in place, and what the template context exposes.

The fix

All of this is general practice, except where it says it was measured.

The static side

Template injection is easy to see in source when the template is built in the same function: render_template_string(f"...{x}..."), Environment().from_string("..." + x), mako.template.Template(x), tornado.template.Template(x), Django's Template(x), nunjucks.renderString(x, ...), ejs.render(x, ...), pug.render(x) and Handlebars.compile(x). The taint sink is the argument that becomes the template source, not the data argument.

That distinction is where static rules go wrong. A rule that treats render_template_string as a sink by name would flag our fixed endpoint, which calls the same function with a constant template and the input as data. We did not run a static rule against the lab. The SAST false-positive post covers sink matching that goes wrong in mechanism. A rule that credits HTML escaping as a sanitiser for this sink is wrong too: we measured escaping on and evaluation still happening. And a template built in one function and rendered in another is a cross-function data flow, the case that needs taint tracking rather than a pattern.

What source does not show:

Those are the parts of the confirmation that need the running system.

A triage checklist for a DAST template-injection finding

  1. Did the evidence show a computed result that the request did not contain, with factors chosen for that request?
  2. Does the product appear in the raw response, or only in a browser?
  3. Does the endpoint compute arithmetic on purpose? Try every syntax and a bare expression.
  4. Was the response cached? Repeat with a change to something that is part of the cache key, or directly against the origin, and compare cache-status headers such as X-Cache and any timestamps in the body.
  5. Which parameter carried the probe that was evaluated? Check whether the scanner injected several at once.
  6. Do a non-arithmetic probe and a valid-against-broken pair agree?
  7. Which engine is it, and how was that established? Do not accept an engine name inferred from 49 alone.
  8. Is a sandbox in place, and what does the template context expose?
  9. For a clean result: was the engine one with arithmetic, was the input in plaintext context, did every payload character arrive, was the output visible in a response at all, and did the run reach the application? The scan-passed post covers the last.
  10. Retest after the fix with the probe that matched and with a code-context breakout, directly against the application and not through a cache.

The hypothetical findings, resolved

Back to the four hypothetical findings.

/search. In the scenario, the high was the search page's answer box. It returned the product for all four syntaxes and for a bare 1337*7331, and {{7*'7'}} produced no answer at all. The code has no template engine on that path. The finding was closed as a false positive, with those requests attached.

/preview. In the scenario, the high was real and the engine was wrong. {{'abc'|upper}} returned ABC and {{7*'7'}} returned 49, which in this application's Node.js stack pointed to Nunjucks. A stack trace from a broken expression confirmed it. The preview feature concatenated a user's saved snippet into the template source. The fix passed the snippet as data, and the retest returned every probe as literal text. Because nobody could say what the template context had exposed, the team also rotated the service's credentials.

/newsletter/signup. In the scenario, the clean result was blind and asynchronous. A tester signed up with a mailbox they controlled and the name alice{{1337*7331}}, and the welcome email read "Dear alice9801547". The email worker concatenated the name into the template source. It was changed to pass the name as data.

/profile. In the scenario, the clean result came from a cache keyed on the path alone. Sent directly to the application, name=alice{{1337*7331}} returned the product. The template was fixed, and the cache key was changed to include the query string, because a cache that ignores the parameters a page depends on serves one user's page to another.

Where AppSecD fits

AppSecD's dynamic and API testing runs Nuclei, Dalfox, SQLMap, Commix, Katana, Arjun, FFuf and Interactsh for out-of-band detection, plus 150+ native checks and API discovery across 50+ web frameworks. Its static analysis includes dataflow taint analysis that traces source to sink across functions. Its findings are deduplicated across scans and move through new, reopened and fixed states, with maker-checker approval so a finding cannot be closed unilaterally.

That is the whole claim. data/products.ts is the single source of truth for what these products do. It names Nuclei and Interactsh, and it does not mention template injection, template engines or sandboxes. So this post does not claim that AppSecD tests for template injection. Nor does it claim anything about:

The measurements, the confirmation procedure, the fixes and the checklist above are general practice, not a description of how AppSecD works internally, and they apply to any scanner's output, ours included. The scenario in this post is hypothetical and does not describe any AppSecD deployment, user or finding.

More about AppSecD · All posts