Problem Framing
Server-Side Template Injection (SSTI) is a critical web security vulnerability that allows an attacker to inject malicious code into server-side templates, leading to arbitrary code execution on the server [1][2][3][4][5][6]. This occurs when applications improperly handle user input that is then processed by a templating engine. The primary danger of SSTI lies in its potential to grant attackers Remote Code Execution (RCE), enabling them to compromise the entire server, steal sensitive data, or disrupt services [1][2][3][4][5][6]. Unlike Cross-Site Scripting (XSS), which impacts the client-side browser, SSTI directly targets the server's runtime environment [7][8].
Template engines are ubiquitous in modern web development, used to dynamically generate content such as HTML pages, emails, and reports by embedding placeholders for variables and logic within static templates [1][7][2][4][5]. Examples of popular engines include Jinja2 (Python), Twig (PHP), FreeMarker (Java), ERB (Ruby), and Handlebars (JavaScript) [7][8][9][10]. The vulnerability arises when user-supplied data is treated as executable template code rather than inert data [1][7][3][5]. This can happen when developers directly concatenate user input into template strings or use functions like render_template_string() in Flask without proper sanitization or context separation [1][3][11][12][13][14].
The impact of SSTI can range from information disclosure (e.g., configuration files, sensitive keys) to complete server compromise, depending on the template engine's capabilities and the application's security posture [1][2]. The severity is often critical due to the potential for RCE [1][2][3][4].
Core Mechanics
SSTI vulnerabilities are fundamentally about the unsafe interpretation of user-controlled input within a templating engine's parsing and rendering process. The core mechanism involves tricking the template engine into evaluating data provided by an attacker as executable code or template directives.
At a high level, the exploit process follows these stages:
- Identify Input Points: Locate any part of the application where user input is reflected in the server's response and might be processed by a template engine. This could be URL parameters, form fields, HTTP headers, or even data embedded in less obvious places like email templates [4][15][10].
- Detect Template Injection: Inject basic template syntax or mathematical expressions to see if they are evaluated by the server. Common indicators include seeing the result of an arithmetic operation (e.g.,
{{7*7}}rendering as49) or specific error messages that reveal the template engine in use [7][4][15][10]. Polyglot payloads, which combine syntax from multiple engines, can be useful for initial detection [16][15][17][9][18]. - Identify the Template Engine: Different engines use distinct syntaxes and have varying capabilities. Recognizing the engine (e.g., Jinja2, Twig, FreeMarker) is crucial for crafting effective payloads [7][8][16][15][10]. Error messages are often a good source for identifying the engine.
- Explore the Sandbox and Attack Surface: Once injection is confirmed, the attacker explores the available objects, variables, and functions exposed by the template engine and its context. This often involves inspecting built-in objects like
config,request, orselfin Jinja2, or using reflection-based techniques in Java environments [19][3][11][20][21][13][22][23][24][25][10]. - Achieve Code Execution: The ultimate goal is typically RCE. This is achieved by finding a way to access modules like
osorsubprocess(in Python) orjava.lang.Runtime(in Java) to execute arbitrary operating system commands or code [1][3][11][5][21][13][25][10].
The core mechanics rely on the template engine's ability to access and manipulate objects and execute functions. When user input is directly interpolated into template syntax, it can bypass intended data rendering and trigger code execution paths. For instance, Jinja2's ability to access object attributes via __init__.__globals__ or __class__.__mro__ allows navigation of Python's class hierarchy to reach sensitive modules [19][3][11][21][13][23][24][25]. Similarly, Java template engines might expose reflection capabilities or specific utility classes like freemarker.template.utility.Execute that can be abused for RCE [20][26][27][28].
Notable Techniques
Exploiting SSTI vulnerabilities often involves sophisticated techniques to navigate the template engine's environment and bypass security controls. The methods vary significantly based on the template engine and the application's specific implementation.
Jinja2 (Python)
Jinja2 is a prevalent engine in Python web frameworks like Flask. Exploitation often targets its ability to access Python's internal objects and execute arbitrary Python code [19][3][11][21][13][23][24][25][10].
- Object Traversal: Attackers leverage object introspection (
__class__,__mro__,__subclasses__) to navigate the Python class hierarchy and access built-in modules. A common path to RCE involves reaching theosmodule via objects likeconfig,request,self, or even basic types like strings or integers [19][3][11][21][13][23][24][25][10]. A typical RCE payload can look like:
{{ self.__init__.__globals__.__builtins__.__import__('os').popen('id').read() }}
- Filter Bypasses: When direct attribute access is blocked (e.g.,
__class__or.notation), attackers use alternative methods like the|attr()filter or__getitem__to access attributes and methods [30][31][24][25]. String concatenation using|joinor character encoding can bypass character blacklists [30][31][24].
- Global Objects: Jinja2 provides global objects like
config,request, andsessionthat offer access to application configuration, request details, and session data, which can be valuable for information disclosure or further exploitation [19][3][24][25].
Twig (PHP)
Twig, common in PHP applications like Symfony, also allows for RCE, often through similar methods as Jinja2 or by exploiting specific Twig features [32][33][13][34][35][9][18].
_selfandenvObjects: Accessing_self.envcan reveal the Twig environment, which may have methods likeregisterUndefinedFilterCallbackthat can be misused to execute arbitrary functions.
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id")}}
- Filter Chaining: Similar to Jinja2, Twig allows chaining filters to achieve code execution. The
|filter('system')pattern can be used to execute commands [7].
- Sandbox Escapes: Twig often has a sandbox to limit dangerous function calls. Exploiting SSTI may require bypassing this sandbox, often by redefining or chaining callbacks [32][36][33][37].
FreeMarker (Java)
FreeMarker is widely used in Java applications. Exploiting it typically involves leveraging Java's reflection capabilities or specific utility classes [20][38][13][39][26][27][28][10].
ExecuteUtility Class: Versions prior to FreeMarker 2.3.30 are often vulnerable to RCE via thefreemarker.template.utility.Executeclass, which can be instantiated to run OS commands [20][38][13][39][26][27][28].
<#assign ex="freemarker.template.utility.Execute"?new()> ${ex("id")}
- Reflection: Java's reflection API can be abused to access classes and methods dynamically. Classes like
org.springframework.util.ReflectionUtilsororg.apache.commons.lang3.MethodUtilscan be used to invoke methods on sensitive classes likejava.lang.Runtime[19][40][41][28].
?lower_abcBypass: In cases with character blacklisting, the?lower_abcor?upper_abcbuilt-in can be used to encode characters and bypass filters, allowing reconstruction of dangerous class names and payloads [27].
ERB (Ruby)
ERB is Ruby's default templating engine. Exploitation often involves direct code execution via Ruby syntax or accessing controller/server objects [1][42][43][44][45][17][10].
- Direct Code Execution: ERB allows embedding Ruby code directly using
<%= ... %>tags. This can be used to execute system commands.
<%= system('id') %>
- Introspection: Ruby's strong metaprogramming and introspection capabilities (
self,methods,instance_variables) can be used to explore the application's internals and potentially access sensitive data or trigger dangerous functions [42][17].
- Safe Levels: ERB has a
safe_levelparameter that can restrict certain operations. Exploitation might require bypassing these restrictions or finding contexts where they are not enforced [42][45].
Other Template Engines
- Velocity (Java): Similar to FreeMarker, Velocity exploitation often involves accessing
java.lang.Runtimevia reflection or using expression language features [7][2][28][10].
#set($x = $class.inspect("java.lang.Runtime")) ${x.getRuntime().exec("id")}
- Handlebars (JavaScript): SSTI in Handlebars can lead to RCE in Node.js environments, often by abusing
process.mainModule.requireor custom helper functions [46][47][48][49]. Prototype pollution can also be leveraged to influence template compilation and execute arbitrary code [47][49].
- ServiceNow (Jelly): ServiceNow's Jelly templating engine is vulnerable to SSTI via injection into parameters like
jvar_page_title. Exploitation can involve accessing Java classes to execute arbitrary commands [50][51].
General Exploitation Techniques
- Information Disclosure: Beyond RCE, SSTI can be used to read sensitive configuration files (e.g.,
/etc/passwd), environment variables, or application secrets [19][3][4][5][21][13][10].
- Blind SSTI: In scenarios where direct output is not visible, time-based or error-based techniques can be used to infer information and confirm injection points [16][15][52][9][10].
- Sandbox Escapes: Many template engines offer sandboxing to mitigate SSTI risks. Exploitation often requires finding bypasses for these sandboxes, such as exploiting weak regex patterns, misconfigurations, or leveraging obscure built-in functions [19][32][36][33][20][40][53][41][54][18].
Detection & Prevention
Detecting and preventing SSTI requires a multi-layered approach, focusing on both secure coding practices and diligent security testing.
Detection Strategies
- Fuzzing with Template Syntax: Inject common template delimiters (
{{...}},${...},<%= ... %>,#{...}) and mathematical expressions (7*7) into user-controllable input fields. Monitor for evaluated results or characteristic error messages [7][4][15][17][9][10][14]. - Analyze Error Messages: Deliberately trigger errors by injecting invalid syntax or references to non-existent objects/functions. Error messages can often reveal the template engine name, version, and sometimes internal file paths [7][16][55][15][17][9][10][18].
- Identify Input Sinks: Focus on endpoints or functionalities that render user-supplied data within templates, especially those using dynamic template rendering functions like
render_template_string()[3][11][12][21][13][14]. - Review Documentation: Understand the template engine's capabilities, built-in objects, security considerations, and known vulnerabilities. This is crucial for crafting specific payloads [16][15][17][10][14].
- Automated Tools: Utilize specialized tools like Tplmap [7][16][56][15][57][58][59][9][6][10] or SSTImap [7][16][15][57][59] to automate the detection and exploitation process across various template engines.
Prevention Measures
- Avoid Direct User Input in Templates: The most effective prevention is to never concatenate or directly embed unsanitized user input into template strings. Instead, pass user input as separate data parameters to the template rendering function [1][3][11][12][5][21][13][24][6][14].
- Insecure:
render_template_string(f"Hello, {user_input}")[21] - Secure:
render_template("greeting.html", username=user_input)[21]
- Input Validation and Sanitization: Rigorously validate and sanitize all user inputs before they are processed by the application or passed to template engines. This includes encoding special characters and using allowlists where appropriate [8][5][13][6].
- Use Sandboxing: If user-supplied templates are a business requirement, leverage the template engine's sandboxing features. Configure engines to restrict access to dangerous functions, built-ins, or classes [8][5][21][6][10][18].
- Disable Dangerous Features: Turn off or restrict functionalities that allow dynamic template evaluation from user input, or that expose powerful introspection capabilities.
- Keep Dependencies Updated: Regularly update template engine libraries and frameworks to the latest versions to benefit from security patches [19][8][47][60][39].
- Secure Configurations: Ensure template engines are configured securely, disabling features that are not strictly necessary for application functionality.
- **Content Security Policy (CSP): Implement a strong CSP to mitigate the impact of potential injection, even if SSTI is present [47][5].
- **Web Application Firewalls (WAFs): Deploy WAFs with rules specifically designed to detect and block common SSTI patterns and payloads, though WAFs should not be the sole defense mechanism [5].
Tooling
Several tools are instrumental in the detection, identification, and exploitation of SSTI vulnerabilities.
- Tplmap: A widely used Python-based tool for automatic SSTI detection and exploitation. It supports numerous template engines and various sandbox escape techniques to gain OS-level access [7][16][56][15][58][59][9][6][10]. Tplmap can identify injection points, template engines, and execute OS commands or establish shells [56][58][59].
- SSTImap: A modern, Python 3 alternative to Tplmap, offering an interactive interface and enhanced capabilities for detection and exploitation [7][16][15][57][59]. It builds upon Tplmap's research and adds new techniques, including interactive modes for easier exploitation [57].
- Hackmanit/TInjA: An efficient scanner for SSTI and Code Injection, leveraging novel polyglots for detection [16][15][59].
- PayloadsAllTheThings: A comprehensive GitHub repository that serves as a critical resource for SSTI payloads across various template engines and languages (Python, Java, PHP, JavaScript, Ruby, Go) [16][43][46][15][47][61][28][59].
- Search.py (DoubleSigma): A script designed to recursively traverse attributes of the
requestobject, useful for identifying exploitable objects in Flask/Jinja2 applications [24][25].
- Burp Suite / ZAP Extensions: Extensions for web proxies can integrate with tools like Tplmap or provide their own SSTI scanning capabilities, often through custom fuzzing lists or decision trees for engine identification [15][24][9][10].
Recent Developments
The SSTI landscape is continually evolving, with new research highlighting sophisticated bypass techniques and vulnerabilities in emerging technologies.
- ServiceNow RCE (CVE-2024-4879): A critical vulnerability in ServiceNow's Jelly templating engine allows unauthenticated RCE by chaining title injection, template injection mitigation bypass, and filesystem filter bypass. The exploit involves injecting payloads into parameters like
jvar_page_title[50][51].
- Grav CMS Twig Sandbox Bypass (CVE-2025-66294): This vulnerability allows authenticated users to bypass Twig's sandbox via weak regex sanitization in
cleanDangerousTwigandevaluate_twigfunctions, enabling RCE [32][36][33][37]. The exploit involves manipulating Twig's internal mechanisms, likeregisterUndefinedFilterCallback, to execute arbitrary code [37].
- Thymeleaf Vulnerabilities (CVE-2026-40478, CVE-2021-43466): Vulnerabilities in Thymeleaf, particularly when combined with Spring EL, have allowed RCE. Techniques involve exploiting expression preprocessing (
__...__) or using reflection to bypass restrictions [19][53][41][62]. The__...__syntax can lead to double evaluation, enabling exploitation even when input is partially escaped [53][41].
- Go SSTI: Research into Golang's built-in
html/templateandtext/templatemodules has uncovered SSTI vulnerabilities. These often arise from improper handling oftemplate.FuncMapor by abusing context objects (e.g.,gin.Context,echo.Context) to call methods that perform file operations or execute commands [63][61][64][65].
- Filter Bypasses and Advanced Obfuscation: Researchers continue to find creative ways to bypass blacklisting filters and character restrictions in various template engines. Techniques include using obscure built-in functions, string manipulation, encoding, and leveraging alternative syntax or object traversal paths [30][31][24][27][66][25].
- New Engine Discoveries: Research continues to identify SSTI vulnerabilities in less commonly targeted template engines or in specific configurations of popular ones, underscoring the broad attack surface presented by templating technologies [65][27][63].
Where to Go Deeper
For practitioners looking to deepen their understanding and practical skills in SSTI, the following resources provide invaluable insights:
- PortSwigger Web Security Academy: Offers comprehensive modules on SSTI, including detailed explanations, methodologies, and interactive labs for hands-on practice [6][10][18][14]. Their research pioneered much of the modern understanding of SSTI.
- HackTricks: A vast repository of security knowledge, with dedicated sections on SSTI covering various template engines (Jinja2, Twig, FreeMarker, ERB, etc.), detection techniques, exploitation payloads, and filter bypasses [25][67][9][23].
- PayloadsAllTheThings (GitHub): An extensive collection of security payloads, including a comprehensive section on SSTI with engine-specific techniques and general payloads for various languages and frameworks [16][43][46][15][47][61][28][59].
- Tplmap/SSTImap Documentation and Repositories: These tools are essential for automating SSTI testing. Understanding their capabilities, usage, and the underlying research they incorporate is key [7][16][56][15][57][58][59].
- Blog Posts and Write-ups: Numerous security blogs and write-ups detail specific SSTI findings in real-world applications and CTFs. These offer practical examples of exploit development and bypasses. Key sources include InfosecWriteups, Medium articles, and security vendor blogs (Snyk, Rapid7, Payatu, Xygeni, etc.) [68][69][8][70][3][71][72][73][74][75][21][13][76][48][22][77][63][61][29][78][60][34][26][27][10].
- Conference Talks: Presentations from security conferences like Black Hat often delve into cutting-edge SSTI research and advanced exploitation techniques [79][18][80].
- CVE Advisories and Security Bulletins: Monitoring new CVEs related to SSTI in popular software (e.g., Confluence, Grav CMS, Tandoor Recipes, ServiceNow) provides insights into current attack vectors and vendor patching strategies [81][32][82][36][33][83][84][85][20][86][87][62][88][40][50][89][51][29][78][60][39][54][65].
Understanding the nuances of different template engines, their security models, and common exploitation patterns is crucial for effective SSTI testing and defense.