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:
49 and 7777777 distinguish engines less cleanly than the folklore saysIt 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:
reflection-ssti from dast/vulnerabilities/ssti/, in DAST mode with interaction testing switched off.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.
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.
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.
An exploitable server-side template injection is a conjunction of three things:
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.
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.
{{7*7}}:** 49 in Jinja2, Tornado and Nunjucks. A parse error in Django and Handlebars. Literal text in Mako, Chameleon, EJS and Pug.${7*7}:** 49 in Mako and Chameleon. Literal text in the other seven.<%= 7*7 %>:** 49 in EJS. A syntax error in Mako. Literal text in the other seven.#{7*7}:** 49 in Pug. Literal text in the other eight.{{7*'7'}}:** 7777777 in Jinja2 and Tornado, and 49 in Nunjucks. A parse error in Django and Handlebars. Literal text in Mako, Chameleon, EJS and Pug.${7*'7'},** sent to the Python engines only: 7777777 in Mako and Chameleon. Literal text in the other three Python engines.<%= 7*'7' %> and #{7*'7'},** sent to the Node.js engines only: 49 in EJS and in Pug respectively.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.
These probes separated the engines in our set. Each one reads only what the template language itself provides.
{{'abc'|upper}} gave ABC in Jinja2 and a NameError in Tornado, which has no | filter syntax. {{ self }} gave <TemplateReference None> in Jinja2 and a NameError in Tornado.ABC for the filter, and Nunjucks implements much of Jinja2's syntax. {{7*'7'}} separated them: 7777777 against 49.${...} as Python. ${self} gave a mako.runtime.TemplateNamespace object in Mako and a NameError in Chameleon.{{'abc'|upper}} and {{ 7|add:7 }} succeeded where arithmetic failed.{# c #}x rendered as x in Jinja2, Tornado, Django and Nunjucks. It is a quiet probe: nothing reflects, and only a parser removes the comment.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.
render_template_string, Jinja2's SandboxedEnvironment, Tornado and Nunjucks matched on the second payload, {{...}}. Mako matched on the first, ${...}, and EJS on the third, <%=...%>.3482 × 2865 = 9975930 from a "quick maths" box that multiplies any two numbers it finds in a search query. Nothing on that endpoint is a template.{{ user.name }} is a syntax error. Pug, for a reason covered below. Each sent all 14 payloads and reported nothing.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.
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.
${...}, {{...}}, <%=...%> and #{...}: none of the nine engines we tested accepts all four syntaxes. Also, {{7*'7'}} produced no answer at all.Hello alice{{7*7}}. In the browser, the DOM read Hello alice49. With {{1234*5678}} it read Hello alice7006652, and with {{7*'7'}} it read Hello alice49 in both. Nuclei's response matcher, which reads the raw body, did not match. A scanner that reads the rendered DOM would see the product. HTML escaping does not touch {, so it does nothing here. This is client-side template injection, the other half of CWE-1336. Its impact is script execution in the victim's browser, so it is an XSS-class finding, not code execution on the server. Report it under the right name.name=alice{{7*7}}, which is injectable, and got Hello alice49. The next request carried {{7*7}} in the lang parameter, which is not injectable, and got a cache HIT with the same Hello alice49 and the same server timestamp in the body. Sent directly to the app, that request returned Hello alice and the literal lang=en{{7*7}}. With a fixed probe like 7*7, a cache attributes one parameter's result to another. Random factors per request break that, as long as each probe carries its own numbers.reflection-ssti put the payload into both in the same request, and the match it reported named name=alice{{5829*1297}}&lang=en{{5829*1297}}. The response body was Hello alice7560213 followed by the literal lang=en{{5829*1297}}, so the body shows which input was evaluated and the match URL does not. Read the body to see which input produced it before assigning the finding to a parameter.{ or <, and has no template. The polyglot's 500 there looks exactly like the polyglot's 500 on a real Jinja2 endpoint. A finding based on "the polyglot caused a 500" needs the differential described under blind cases.reflection-ssti did not match, because an echo of {{3585*4726}}, one of the probes it sent to the WAF, is not 16942710. A check that matches on keywords or on the probe itself, rather than on a computed result, would read that page as a hit. We did not test such a check.Hello {{ user.<input> }}. All 14 payloads missed. By hand, name returned alice, email returned the email address, and an attribute that does not exist returned an empty greeting, which is the "blank result" Kettle describes. name<tag> raised a syntax error. name}}<tag> returned Hello alice<tag> }}, and name}}{{7*7 returned Hello alice49. That is the breakout, and it is the confirmation.# above. Any character that a client, proxy or framework strips, normalises or treats as a delimiter changes what the probe tests.name=alice{{7*7}} and name=alice{{1234*5678}} both got a HIT with Hello alice. Sent directly, the second returned Hello alice7006652. Run through the cache, reflection-ssti sent 14 requests and reported nothing. The app's log showed that one of the 14 reached it, a ${...} probe that Jinja2 leaves alone, and nginx answered the other 13 without reaching the app. Sent directly, the template matched on its second request.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.
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.
{{7*7}}:** 49 in both.{{ config.SECRET_KEY }}: the lab's secret key in the plain environment. Undefined in the sandbox, whose context did not include config.{{ user.api_token }}: undefined in the plain environment, whose context did not include user. The lab token in the sandbox.{{ ''.__class__ }}: <class 'str'> in the plain environment. Empty output in the sandbox.{{ ''.__class__.__mro__[1].__subclasses__() }} piped to length: 788 in the plain environment. SecurityError in the sandbox.{{ cycler.__init__.__globals__.os.name }}: posix in the plain environment. SecurityError in the sandbox.{{ range(100001) }} piped to length: 100001 in the plain environment. OverflowError in the sandbox, whose limit is 100,000.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.
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.
{{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.1337*7331 with no delimiters.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.{# 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.{{ ''.__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.All of this is general practice, except where it says it was measured.
render_template_string("<p>Hello {{ name }}</p>", name=...), returned every probe as literal text.<class 'str'> into <class 'str'>, and it evaluated {{7*7}} all the same. Escaping acts on what a template produces, not on what it parses.SandboxedEnvironment, which Jinja's documentation says "can be used to render untrusted templates", or a sandbox that another engine documents for the same purpose. Pass a context built for the purpose, never a whole request, configuration or ORM object. Wrap rendering in CPU, memory and time limits. Keep the engine up to date, because sandbox escapes are found and fixed.[first_name], replaced by plain string substitution. It does not need a template language.ng-non-bindable on the containing element stops compilation. In Vue 2, v-pre does the same.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.
X-Cache and any timestamps in the body.49 alone.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.
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.