Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 80 ยท Web Application Security

Server-Side Template Injection

Understand how server-side template injection happens when user input becomes template code, how to detect it safely, and how to fix it with data binding and sandboxes.

Web applications use template engines such as Jinja2, Twig, Freemarker or Blade to build pages: you write a template with placeholders, and the engine fills them with data. A template is not just text with holes. Most engines can evaluate expressions, call functions and read object attributes. That power is fine while the template comes from the developer, but it becomes dangerous when an attacker's input is treated as part of the template itself.

That is server-side template injection (SSTI): user-controlled text is concatenated into a template string before the engine parses it, so the attacker's text runs as template code on the server. Depending on the engine, the impact ranges from leaking configuration and secrets to remote code execution. SSTI belongs to the injection family you met in SQL Injection and Parameterized Queries and The OWASP Top 10, and its root cause is the same: mixing code and data.

This lesson shows how SSTI arises, how a defender can recognize and test for it safely, and how to eliminate it. The demos use Jinja2 and Python's own formatting, and only reveal harmless information from a local sandbox.

Data versus template

There are two ways to put a visitor's name into a page.

Safe: the template is fixed, and the name is data passed to it:

Python
template = "Hello, {{ name }}!"
render(template, name=user_input)

Dangerous: the user's text becomes part of the template source:

Python
template = "Hello, " + user_input + "!"   # now user_input is template CODE
render(template)

In the first case, even if user_input is {{ 7*7 }}, the engine prints those characters. In the second case, the engine evaluates it and prints 49. The vulnerability usually appears when developers build templates dynamically: custom email or notification messages, "customizable" page footers, error pages that echo the URL, report builders, or wikis that let users write markup with an engine's syntax.

flowchart LR
    U["User input"] -->|"concatenated into template string"| T["Template source"]
    T --> E["Template engine parses and evaluates"]
    E --> O["Output (and any code the input contained)"]
    D["Safe design: input as variable data"] -.-> E

The mistake happens before rendering: the input reached the template source instead of the data.

Seeing it in a lab

The Jinja2 library lets us show the difference harmlessly. The "secrets" below exist only inside this demo.

Python Template source vs template data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The probe {{ 7 * 7 }} is the standard, harmless detection test: if the response contains 49 rather than the original characters, the input was evaluated. The next probe shows the realistic impact: the template could read an object that the developer put in the render context, here the application's configuration. In real engines, attackers can often navigate from any available object to the language runtime's internals, which is why SSTI frequently ends in full server compromise. We will not demonstrate those payloads; what matters is understanding that evaluation of untrusted text is the vulnerability.

Not just Jinja: format strings too

The same bug exists in plain string formatting. Python's str.format lets a template reach attributes of objects passed to it, so formatting with a user-supplied format string can leak data:

Python User-controlled format strings leak object data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python's own documentation warns about this pattern. Similar issues exist in other languages whenever a "string template" feature can read attributes or call methods.

How defenders detect SSTI

  • Code review: search for places where a template is built from strings: Template( with concatenation or f-strings, render_template_string, eval-like helpers, Environment.from_string, and user-editable templates stored in a database (Security Code Review, SAST and Testing). Static analysis tools flag many of them.
  • Safe testing in your own application: send benign polyglot probes made of template delimiters from several engines (such as {{7*7}}, ${7*7}, <%= 7*7 %>) and look for an evaluated result (49) in the response, or a template error message. An error mentioning the engine is also evidence. Test only systems you own or are authorized to test.
  • Logs and WAF signals: requests with {{, {%, ${, #{ and <% in parameters that should be plain text deserve a look (Spotting Attacks in Logs). They are a hint, not proof, because legitimate content can contain them.
  • Error pages: stack traces that mention a template engine in response to odd input suggest the input reached it (Secrets, Logging and Error Handling).

Preventing SSTI

  1. Never build templates from user input. Keep templates in files you control. Pass user text only as variables. This one rule removes almost all SSTI.
  2. Let the engine escape output, so even when data contains markup it is shown as text (Cross-Site Scripting and Output Encoding).
  3. If users must supply templates (email builders, report designers, CMS themes), reduce the power of the language:
    • Use a logic-less template engine such as Mustache or Handlebars-style engines with helpers disabled. They support placeholders and simple loops but cannot call methods or evaluate arbitrary expressions.
    • Or use the engine's sandbox mode (such as Jinja2's SandboxedEnvironment), and still treat it as defense in depth, because sandboxes have been bypassed in the past.
    • Whitelist the variables and filters available to user templates, and expose plain data (strings, numbers) rather than rich objects.
  4. Run the rendering with least privilege: a separate low-privilege process or container, no secrets in the environment, restricted network and file access, CPU/time limits (Secure Architecture and Design Patterns, Cloud and Container Security).
  5. Validate input where it makes sense (Input Validation and Sanitization), but do not depend on blocklists of {{; engines have many syntaxes.
  6. Keep the engine updated and disable debug features in production.

Here is what a sandbox does with an attempt to touch a Python internals attribute, which is the first step of many real attacks:

Python Sandboxed environment and logic-less rendering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The normal engine reveals a runtime object, the sandbox refuses to expose the attribute (by default it silently renders nothing; with strict mode it raises an error), and the logic-less renderer simply ignores anything that is not a known variable name. Use a vetted logic-less engine in production rather than hand-written code; the point here is that less power means less to exploit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the root cause of server-side template injection?

    When input is concatenated into the template string, the engine treats it as code. Passing input as data keeps it as text.
  2. 2. You send {{7*7}} to a field and the page shows 49. What does this indicate?

    If the expression result appears instead of the literal characters, the engine evaluated your input. Only test systems you are authorized to test.
  3. 3. Which is the best fix when a feature does not need user-defined templates?

    Separating code from data removes the vulnerability. Blocklists miss other engines' syntaxes and encodings.
  4. 4. If users must write templates (for example for email campaigns), what is the best approach?

    Reduce the language's power, restrict what variables are available, and isolate the renderer, since sandboxes alone have been bypassed.

Summary

  • SSTI happens when untrusted text is placed in a template's source, so the engine evaluates it; impact ranges from information leaks to remote code execution.
  • Probing with benign expressions such as {{7*7}} reveals evaluation; test only systems you are authorized to test.
  • The same class of bug appears with format strings that read object attributes.
  • Fix it by keeping templates fixed and passing input as data; use auto-escaping.
  • If users need templates, use a logic-less engine or sandbox, expose only simple data and isolate the renderer with least privilege.
  • Review code for dynamic template construction and watch logs for template delimiters in parameters.

Next: HTTP Security Headers.