What Is SSTI? Server-Side Template Injection Explained
A complete technical guide to Server-Side Template Injection (SSTI): how template engines evaluate attacker-controlled templates, and how to detect, verify, and prevent it.
Short answer
Server-Side Template Injection happens when untrusted user input is concatenated into a template string that a server-side template engine later evaluates. The template engine can no longer distinguish between the template's structure (its flow control, variable resolution, and method calls) and the attacker-supplied payload — and so it executes the latter as if it were part of the template's own logic.
The idea in one minute
Imagine a form-letter generator that works like this: you give it a note card with blanks, and it reads the blanks from a stack of sticky notes. The card says: "Dear [TITLE] [NAME], your reservation for [DATE] is confirmed." On your sticky notes you wrote "Mr.", "Smith", and "tomorrow." Everything works fine.
Now imagine the sticky note for [NAME] does not say "Smith." It says: ], your reservation for tomorrow is canceled. Actually, print a new card that says "Dear [Sir, I have transferred your entire balance to my account. Thank you. Sincerely, The machine looks at your sticky note, finds the blank, and shoves the whole thing in — not caring that your "name" contains another blank marker. It reads [TITLE] a second time and starts looking for another sticky note. The machine is doing exactly what you told it; the problem is you let someone write on the sticky note before you read it.
A template engine works identically. The template is the card: Hello {{name}}. The engine's job is to find {{name}}, resolve it against a context dictionary, and insert the resulting value. If name itself contains {{config}}, and the application builds the template by concatenation — template = "Hello " + user_input — then the engine renders {{config}} as an instruction on its second pass. The boundary between "the template's code" and "the user's data" collapses.
How SSTI actually works
A typical vulnerable pattern passes user input directly into the template string:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route("/greet")
def greet():
name = request.args.get("name", "world")
template = f"Hello {name}!"
return render_template_string(template)
render_template_string compiles and evaluates the entire string as a Jinja2 template. If name is world, the output is Hello world!. If name is {{7*7}}, the engine sees {{ as the start of an expression, evaluates 7*7, and returns Hello 49!.
That arithmetic result — 49 — is the definitive detection signal in Jinja2-based SSTI. No normal name string evaluates to a computed product. The template engine just did what template engines do: it interpreted the syntax it found.
There are two broad exploitation categories:
| Category | How it's confirmed | Example technique |
|---|---|---|
| Blind template injection | No computed value appears in the response, but a side effect (timing, HTTP callback) confirms execution | {% if 1==1 %}delay{% endif %} with {{ ''.__class__.__mro__ }} |
| Verified template injection | Expression output appears in the response body | {{7*7}} returning 49, or {{config}} dumping Flask app configuration |
The request flow
sequenceDiagram
participant Attacker
participant App as Vulnerable Application
participant Engine as Template Engine
Attacker->>App: Input containing template syntax instead of plain data
App->>Engine: Template string built with attacker input concatenated in
Engine-->>App: Template compiled and evaluated, attacker syntax executed
App-->>Attacker: Rendered output reveals expression results, config, or errors
A minimal example
Vulnerable greeting endpoint:
from flask import Flask, request, render_template_string
app = Flask(__name__)
@app.route("/profile")
def profile():
user = request.args.get("user", "guest")
template = f"<h1>Welcome, {user}!</h1>"
return render_template_string(template)
Submitting user={{7*7}} produces <h1>Welcome, 49!</h1> — proof that the engine evaluated the payload. From here, an attacker escalates by traversing Python's object chain: {{''.__class__.__mro__[1].__subclasses__()}} to enumerate loaded classes, find one like os.Popen or subprocess.Popen, and invoke it:
{{''.__class__.__mro__[1].__subclasses__()[X](['id'], stdout=-1).communicate()}}
The fix is to never concatenate user input into the template string. Instead, pass the user input as a context variable to a static template:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/greet")
def greet():
name = request.args.get("name", "world")
return render_template("greet.html", name=name)
In greet.html:
<h1>Welcome, {{name}}!</h1>
Here, {{name}} is a placeholder resolved from the context dictionary — the user input never enters the template string itself, so there is no way for it to inject new template syntax. The template file is static and compiled once at startup; user-controlled values are rendered as escaped strings within that fixed structure.
Why the vulnerability exists
- User input is concatenated or formatted into a template string before being passed to the render function — the most common root cause, and the hardest to catch in code review when it is buried in a helper or composed across multiple files
- The application uses a
render_template_string-style function (present in most templating libraries) instead of a static template file with context-bound variables - Developer awareness is low: many engineers know to parameterize SQL queries but do not think of template strings as a similar code/data boundary
- Template engines are designed to be powerful — they expose object traversal, method invocation, and sometimes direct OS access — so any injection into the template layer is almost always a full sandbox escape
What attackers look for
- Any user-controlled value that appears in the rendered page and might be part of a template path or inline render call: usernames displayed on profiles, search terms echoed back, error messages that include input, site-wide announcement text
- Form fields that accept markup or formatting syntax (markdown, textile, custom shortcodes) — if the server converts them using a template engine, the input field is an injection point
- The presence of a known template engine in the tech stack (Jinja2 for Flask/Django, Twig for PHP, FreeMarker or Velocity for Java, Pug or EJS for Node.js)
- HTTP headers or cookies that the application logs or displays on an admin panel —
User-Agent,Referer, and custom headers often end up in internal dashboards that render via a template
Detection
- Static/code review: search for calls to
render_template_string,Template(),template.render(),compile, or string concatenation immediately before a render call. In Node.js, look forres.render()with a dynamically constructed path; in Java,Template.getInstance()ortemplate.process()with concatenation. - DAST: submit template expressions as every user-controlled input:
{{7*7}},{{7*'7'}},${7*7},#{{7*7}},<%= 7*7 %>. Each syntax targets a different engine family. The canonical Jinja2 test is{{7*7}}→ response contains49. - Blind detection: where no expression output is reflected, inject a conditional delay:
{% if 1==1 %}{% endif %}(heavy loop) or a sleep call if the engine allows it. A measurable timing differential confirms injection without requiring visible output. - Error-based detection: submit malformed syntax like
{{alone. If the server returns a detailed stack trace namingjinja2,Twig,FreeMarker, or similar, it confirms both the engine family and the injection point.
Verification: real vulnerability or false positive?
Confirmed when you can show a repeatable evaluation signal tied directly to the template syntax:
{{7*7}}produces49in the response body — a computed value that cannot result from simple string echoing — and submitting{{7*8}}produces56(the value changes as the arithmetic changes)- A typo control like
{{7*x}}returns a template error, an empty string, or the literal text{{7*x}}, while the arithmetic payload returns a number — establishing a toggleable on/off signal - A blind timing payload produces a consistent delay (across several trials) while a no-op control does not, and the delay disappears when the input is escaped or sanitized
A single occurrence of 49 in a response is not enough if it could be a coincidence (e.g., a user named "49" or a static page element). Toggle the payload and confirm the response changes deterministically with the injection.
Real-world impact
SSTI is widely considered the most dangerous web vulnerability class after SQL injection, because template engines sit in the application layer with full access to the runtime environment:
- Remote code execution: most template engines expose Python, PHP, or Java objects through the template context, and traversing the class hierarchy (
__class__.__mro__.__subclasses__()) leads directly tosubprocess.Popen,os.system, orRuntime.exec()— giving the attacker a shell - Full server compromise: with RCE established, the attacker can read arbitrary files, exfiltrate environment variables (including database credentials and API keys), install persistence, or pivot to internal network hosts
- Data exfiltration via
{{config}}: in Flask/Jinja2 applications, theconfigobject is automatically available in the template context and contains the app's SECRET_KEY, database URIs, and any other environment-pulled configuration — a single injection point can leak the entire deployment topology - Internal network scanning: with RCE in hand, the compromised server becomes a beachhead for lateral movement against services that do not expect traffic from the application server (internal APIs, databases, cloud metadata endpoints)
Prevention
- Never concatenate user input into a template string. Use static template files and bind user data as context variables. This is the same principle as parameterized queries for SQL: keep the structure (template) separate from the values (context).
- Use
render_template(file-based) notrender_template_stringin Flask; in other frameworks, prefer file-based compilation over inline compilation wherever user data is involved.render_template_stringshould be reserved for cases where the entire template is trusted (e.g., generated by the system, not the user). - Sandbox the template engine if dynamic templates are unavoidable: restrict available globals, disable access to
__class__,__mro__,__subclasses__, and__builtins__. Jinja2'sSandboxedEnvironmentprovides a starting point but is not a complete defense — motivated bypasses exist. - Content Security Policy as a depth-in-depth measure: a strict CSP limits what an RCE-capable attacker can do with inline script execution, but does not prevent the RCE itself.
- Least-privilege execution: run the application process as a non-root user with minimal filesystem write permissions — containment buys time when injection is discovered after deployment.
Related vulnerabilities
- Cross-Site Scripting (XSS) — SSTI often produces XSS as a side effect (injecting
<script>tags into rendered output), but the primary risk is server-side code execution, not client-side script injection - Command injection — SSTI escalation nearly always becomes command injection via
os.systemorsubprocess.Popen; the distinction is the entry point (template syntax vs. shell syntax) - SQL injection — structurally identical root cause: data crosses into a code evaluation boundary because concatenation replaced parameterization
- Path traversal — if a template path, not the template content, is user-controlled, an attacker can load arbitrary template files from the filesystem
Testing methodology (do this safely)
- Only test targets you are authorized to test — SSTI testing that escalates to RCE will execute commands on the server, which carries operational risk and legal implications if unauthorized.
- Start with the arithmetic polyglot
{{7*7}}and its variations — this is the safest possible probe because it produces a visible output without side effects. No database writes, no file access, no network calls. - If the arithmetic probe returns
49, confirm with a second probe ({{7*8}}→56) before escalating further. A single match is a lead; a repeatable toggle is a finding. - Do not execute destructive commands (
rm,dd,shutdown, network flood) under any circumstances. If RCE is confirmed for reporting purposes, prefer read-only commands (id,whoami,ls) and document the output without persisting changes. - Resolve a non-existent subdomain or hostname via the probe to generate a DNS callback — a safer alternative to blocking sleeps.
- After testing, restore any modified context state. Template engines can cache compiled templates; if your payload altered application configuration, verify the change is reverted.
Further reading
- PortSwigger Web Security Academy: Server-Side Template Injection
- OWASP Cheat Sheet Series: Server-Side Template Injection Prevention Cheat Sheet
- MITRE: CWE-1336 — Improper Neutralization of Special Elements used in a Template Engine
- PortSwigger research: "Server-Side Template Injection: RCE for the modern webapp" by James Kettle (2015)
Nyxeara perspective
SSTI is the vulnerability class where the line between a web weakness and a full system compromise is thinnest. One {{ pair can go from a reflected expression to an interactive shell in two lines of payload. That severity is why detection must be precise: {{7*7}} returning 49 is not a curiosity — it is confirmation that the server's template engine has accepted attacker-supplied instructions, and the only remaining question is how deeply the runtime allows traversal. The safest answer is to prevent the separation from collapsing in the first place: keep the template structure fixed and let user data occupy only the slots designed for it. No sandbox, no allowlist, no input filter — just the same code/data discipline that keeps SQL injection out of your queries.