Gaining Shell using Server Side Template Injection (SSTI)

David Valles
3 min readAug 22, 2018

--

This post is about Server Side Template Injection (SSTI) and a brief walkthrough of how it can be leverage to get a shell on the server hosting the application.

A template engine makes designing HTML pages easier by using static template files which at runtime replaces variables/placeholders with actual values in the HTML pages. Some popular and widely used template engines are Smarty, Twig, Jinja2, FreeMarker, Velocity.

Server Side Template Injection is possible when an attacker injects template directive as user input that can execute arbitrary code on the server. If you happen to view source of a web page and see below code snippets then it is safe to guess that the application is using some template engine to render data.

var greet = ‘Hello $name’;

<ul>

<% for(var i=0; i<data.length; i++)

{%>

<li><%= data[i] %></li>

<% }

%>

</ul>

<div>

<p> Welcome, {{ username }} </p>

</div>

I preferred hands-on learning to know SSTI better and found my playground in Xtreme Vulnerable Web Application (XVWA) written by Sanoop Thomas and Saman which contains SSTI as one of the challenges. I recommend give it a try and can be found at https://github.com/s4n7h0/xvwa

I injected my favorite probing string ${{1300+37}} to see if the application evaluates it. I get $1337 as response from the server. This response interprets that {{ }} is the syntax used by the template engine.

Injecting probe string
1337 in response

Big hint was on the page itself that it is a TWIG template engine. In my search on what more can I do with this injection than mere mathematical operation evaluation lead me to awesome research done by James Kettle wherein I found the below payload to get code execution on the server. As you can see below, this payload makes malicious use of template directive to execute “id” command.

Code execution payload
Output of command “id”

This is good but what would make me happier was a shell on the server. I quickly generated a php meterpreter payload and got it to execute on the server to get a remote shell. GAME OVER!

php meterpreter payload
Metasploit listener
Download and execute php meterpreter payload
Meterpreter Shell :)

Remediation will vary for different template engines but sanitizing user input before passing to template directive can greatly minimize the threat. Another option is to have safe or sandbox environment wherein either the dangerous directives are removed/disabled or it’s a hardened environment.

References:

https://portswigger.net/blog/server-side-template-injection

https://nvisium.com/blog/2016/03/11/exploring-ssti-in-flask-jinja2-part-ii.html

--

--