Problem Framing
Server-Side Template Injection (SSTI) occurs when untrusted user input is incorporated into server-side templates without proper validation or sanitization, allowing an attacker to inject and execute malicious code on the server [1][2][3][4][5][6][7][8][9][10]. Unlike client-side vulnerabilities like Cross-Site Scripting (XSS), where malicious code executes in the user's browser, SSTI payloads are processed and executed by the template engine on the server itself [1][11]. This fundamental difference in execution context grants SSTI a significantly broader blast radius, potentially leading to information disclosure, arbitrary file access, privilege escalation, and most critically, Remote Code Execution (RCE) [1][2][12][6][7][8].
Template engines are ubiquitous in modern web development, used for generating dynamic content such as HTML, emails, configuration files, and reports. They separate presentation logic from application code, allowing developers to create reusable components and manage dynamic data efficiently [2][12][6]. Common examples include Jinja2 (Python), Twig (PHP), FreeMarker (Java), Velocity (Java), Handlebars (JavaScript), Pug (Node.js), and ERB (Ruby) [1][2][11][3][4][13][7][14][8][15][9]. The very nature of these engines, designed to interpret and execute expressions within templates, makes them susceptible to injection if user-controlled data is treated as template code rather than plain data [1][11][3].
The root cause of SSTI lies in how user input is handled. Securely, user input is passed as data to a pre-defined, trusted template. Insecurely, user input is directly concatenated or interpolated into the template string, becoming part of the template code itself [1][2][11]. This distinction is critical:
- Safe:
render_template_string("Hello {{ name }}", name=user_input). Ifuser_inputis{{7*7}}, the output is literally "Hello {{7*7}}!" [1][11]. - Unsafe:
render_template_string("Hello " + user_input). Ifuser_inputis{{7*7}}, the template becomes "Hello {{7*7}}" and renders as "Hello 49!" [1][11].
The impact of SSTI can be severe, ranging from sensitive information disclosure (e.g., configuration files, credentials) to complete server compromise through RCE [1][12][5][6][8][16][10]. Due to their potential for high impact and the widespread use of template engines, understanding SSTI is crucial for application security professionals [11][12][5][6].
Core Mechanics
The fundamental mechanism behind SSTI is the improper handling of user-supplied input within a server-side templating engine. This leads to the template engine interpreting the input as code rather than literal data, thereby executing arbitrary logic on the server [1][2][3][8].
The process generally follows these stages:
1. Input Vector Identification
The first step is to identify input fields or parameters that are reflected in the server's response and appear to be processed by a template engine [1][11][5][14][17][10]. This can include:
- URL parameters
- Form fields
- HTTP headers
- Cookies
- Data submitted in request bodies
- User-generated content in features like comments, profile fields, email templates, or content management systems [1][2][12][5][18][19][20][17][10]
2. Template Engine Detection
Once a potential injection point is found, the next critical step is to identify the specific template engine in use. Different engines have distinct syntaxes and object models, which dictate the available exploitation techniques. A common method for detection is to submit basic mathematical expressions within the expected template syntax. If the server evaluates the expression and returns the result (e.g., 49 for 7*7), it confirms that the input is being processed as code [1][11][3][5][21][7][14][8][22][17][10].
Different template engines use characteristic delimiters:
{{...}}: Jinja2, Twig, Handlebars, Mustache, Pug [1][11][13][23][8]${...}: FreeMarker, Velocity, Thymeleaf [1][11][15][23][8]<%...%>or<%=...%>: ERB (Ruby), EJS (Node.js) [11][23]#{...}: Pug (alternate syntax), Thymeleaf [1][11][15]<...>: Smarty [24][25][3][ ... ]: Velocity [15]#(...): Mako [15]<% ... %>: JSP [15]{@ ... }: JSTL [15]
By using a "polyglot" payload that mixes delimiters from various engines, or by observing error messages when submitting invalid syntax, one can often infer the engine. For instance, {{7*'7'}} might result in 7777777 for Jinja2/Twig but 49 for Mako [1][11][23][8]. Error messages themselves can also be invaluable, often revealing the template engine's name and version [1][11].
3. Payload Construction and Exploitation
Once the template engine is identified, the attacker crafts a payload to achieve their objective, typically RCE. This involves understanding the engine's object model, available functions, filters, and how to navigate through inherited classes to find executable code or sensitive information [1][11][3][5][7][8][26][27]. The goal is to reach objects or functions that can interact with the operating system, such as Python's os module, Java's Runtime class, or PHP's system() function [1][11][5][7][8][26][27].
Exploitation often involves:
- Information Disclosure: Accessing configuration objects (e.g., Jinja2's
config) to retrieve sensitive data [1][11][4][28][29][30][26][10]. - Object Chaining: Navigating Python's inheritance tree (e.g.,
''.__class__.__mro__[1].__subclasses__()) to discover available classes, including those that can execute commands [1][4][29][7][31][30][26][10]. - Utilizing Built-in Functions/Objects: Leveraging accessible objects like
request,self,cycler,lipsum, or framework-specific objects (e.g., Flask'sconfig, Grav'sgrav.twig) to find paths to execution [1][11][21][7][32][33][31][26][10]. - Sandbox Escapes: Bypassing security restrictions imposed by the template engine to gain access to restricted functionality [34][35][36][37][38][39][40][41][42][43][16].
- Command Execution: Using discovered methods to execute OS commands (e.g.,
id,ls,cat) or establish reverse shells [24][1][44][25][45][2][11][46][36][47][37][38][48][3][4][49][5][21][50][51][52][53][54][55][28][56][29][57][58][59][60][39][61][62][63][64][23][65][7][66][67][68][19][14][8][69][70][71][40][72][73][74][75][76][20][77][78][79][32][80][81][82][33][31][30][41][83][84][42][85][86][43][87][88][89][15][22][26][17][90][27][91][16][10].
4. Blind SSTI
In scenarios where direct output is not reflected, blind SSTI techniques are employed. These rely on observing indirect effects, such as time delays (Time-Based SSTI) or conditional errors (Error-Based or Boolean-Based SSTI) to infer the success of a payload [4][49][5][23][8][20][22][27]. For example, using a sleep(10) command in a payload and measuring the server's response time can confirm vulnerability [20].
Notable Techniques
The exploitation of SSTI vulnerabilities is highly dependent on the specific template engine and its configuration. However, several common techniques and approaches have emerged for detecting and exploiting these flaws across various platforms.
1. Basic Detection and Identification Payloads
The initial step in identifying SSTI is to use simple payloads that test for template engine evaluation. Mathematical expressions are a common and effective choice because their results are unlikely to appear coincidentally [1][11][3][5][23][7][14][8][22][17][10].
For example:
{{7*7}}(Jinja2, Twig, Handlebars)${7*7}(FreeMarker, Velocity, Thymeleaf)<%= 7*7 %>(ERB, EJS)#{7*7}(Pug, Thymeleaf)
If the response shows 49, it indicates server-side evaluation. Further probes like {{7*'7'}} can help differentiate between engines (e.g., Jinja2 vs. Twig) [1][11][23][8]. Triggering errors with invalid syntax (e.g., {{undefined_variable}} or (1/0).zxy) can also reveal the template engine's name or version [1][11][49][23][22].
2. Object Chaining for RCE
In engines like Jinja2 (Python) and Twig (PHP), much of the exploitation relies on navigating the object model to find pathways to execute code. This often involves starting from a common, accessible object and traversing its attributes and methods [1][3][4][29][7][80][31][30][26][10].
A classic Jinja2 technique involves starting from a string literal (e.g., "" or request) and using special attributes to reach the base object class, then its subclasses, and finally a class that can execute commands [1][4][29][7][31][30][26][10]:
''.__class__.__mro__[1].__subclasses__(): This chain accesses all loaded Python classes [1][4][31][30][26]. The specific index for a desired class (likesubprocess.Popenor_io._IOBase) can vary between Python versions and environments [1][29][30].configobject: In Flask applications, theconfigobject often holds sensitive information and can provide access to Python's built-in modules [1][11][4][28][29][30][26].selfobject: Some engines expose aselfobject that provides access to the environment, including the template engine's configuration and global functions [61][19][8][82][87][26][16].
For example, in Jinja2, to execute the id command: {{''.__class__.__mro__[1].__subclasses__()[157].__repr__.__globals__.get('__builtins__').get('__import__')('subprocess').check_output('id')}} [24]. A more stable approach uses accessible globals like cycler or lipsum: {{ cycler.__init__.__globals__.os.popen('id').read() }} [44][11][21][13][23][7][32][33][31][26].
3. Engine-Specific Execution Primitives
Each template engine provides distinct mechanisms for code execution:
- Smarty (PHP): Modifiers can directly call PHP functions.
{system('id')}or{'id'|shell_exec}achieve RCE [24]. - Pug (Node.js): Raw JavaScript interpolation allows direct access to Node.js modules like
child_process.#{require('child_process').execSync('ls')}is a common pattern [24][13]. - Twig (PHP): Can leverage global objects like
_selfto access the environment and register undefined filters to execute commands:{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id")}}[11][82][41][83][87][17][16]. It can also be exploited via filter chaining:{{['id']|filter('system')}}[11]. - FreeMarker (Java): The
freemarker.template.utility.Executeclass can be instantiated to run commands:${"freemarker.template.utility.Execute"?new()("id")}[11][50][7][71][84][86][43][15]. Sandbox bypasses often involve reflection or accessing class loaders [50][73][42][43][15]. - Velocity (Java): Similar to FreeMarker, uses reflection to access
java.lang.Runtime:#set($rt=$x.class.forName('java.lang.Runtime'))#set($ex=$rt.getRuntime().exec('id'))[11][15]. - ERB (Ruby): Direct execution of Ruby code is possible:
<%= system('id') %>or<%= `whoami` %>[11][52][53][54][55][23][14][8][15][22][27]. - Razor (.NET): Text Transform (.tt) files can contain C# or VB code executed via utilities like
TextTransform.exeorMSBuild.exe[45]. - Go (html/template): Exploitation relies on accessing exported methods of structs passed into templates, such as
{{.Secret "id"}}or{{.File "/etc/passwd"}}[74][75][76].
4. Filter Bypasses
Web Application Firewalls (WAFs) and custom sanitization filters often blacklist dangerous characters or keywords (e.g., __, ., [, ], eval, system) [44][36][37][38][60][39][33][31][30][87]. Bypassing these filters requires obfuscation and alternative syntax:
- String Concatenation/Manipulation: Building dangerous strings from smaller parts, using concatenation, or exploiting string formatting functions (e.g.,
|join,|formatin Jinja2,chr()in PHP/Python) [60][33][31][87][26]. - Hex Encoding: Representing banned characters or strings using their hexadecimal escape sequences (e.g.,
\x5ffor_) [44][21][60][39][80][31][26]. - Attribute Access via Functions/Methods: Instead of direct attribute access (e.g.,
obj.attr), using functions likeobj|attr('attr')(Jinja2) or dictionary-style access likeobj['attr'][60][39][31][30][87][26]. - Using Alternative Tags: If
{{...}}is blocked,{%...%}or line comments might be usable in some engines [31][26]. - Exploiting Object Properties/Methods: Using less common or indirectly accessible properties and methods that are not blacklisted, or exploiting reflection mechanisms [50][73][42][43][15].
Detection and Prevention
Detecting and preventing SSTI requires a multi-faceted approach, focusing on secure coding practices, robust input validation, and effective tooling.
1. Detection Strategies
Detecting SSTI vulnerabilities involves a combination of automated scanning and manual probing.
- Automated Scanners: Tools like Tplmap and SSTImap are designed to automate the detection and exploitation of SSTI [11][56][88][89]. These tools fuzz identified input points with common payloads and attempt to identify the template engine and exploit it.
- Manual Fuzzing: Systematically sending template syntax probes (mathematical expressions, polyglots, error-inducing payloads) to all user-controllable inputs is a fundamental manual technique [1][11][49][5][23][14][8][22][17][10]. Pay close attention to application responses, including error messages, performance delays, or unexpected output changes [1][11][5][8].
- Code Review: Analyzing application source code for insecure usage patterns, particularly the direct concatenation of user input into template strings or the use of functions like
render_template_stringwith untrusted data, is highly effective [1][2][46][4][92][29][65][7][80][88][10]. - Dependency Scanning: Regularly scanning project dependencies for known template engine vulnerabilities (e.g., specific CVEs in libraries like Twig, FreeMarker, Jinja2) is crucial [34][35][36][47][37][38][48][93][50][18][66][67][71][40][77][78][79][32][80][81][84][42][85][90].
2. Prevention Strategies
Preventing SSTI hinges on secure development practices and robust application architecture.
- Avoid Direct Input Interpolation: The most critical prevention measure is never to embed raw user input directly into template strings. Instead, always pass user input as parameterized data to the template engine [1][2][11][3][29][65][7][88][10]. Use functions like
render_template('template.html', variable=user_input)in Flask instead of string concatenation [1][11][29][65][88]. - Sanitize and Validate Input: Strictly validate and sanitize all user input before it is processed by the template engine. This includes encoding or escaping special characters that could be interpreted as template syntax [2][3][5][6][65][7][14][20][10].
- Utilize Template Engine Security Features: Leverage built-in security mechanisms such as sandboxing, safe modes, or automatic output escaping provided by template engines [35][37][6][65][90][16][10]. Disable dangerous functions or features that allow arbitrary code execution where possible [37][6][90][10].
- Use Predefined Templates: Where dynamic template generation is necessary, use predefined template structures and only substitute variables. Avoid allowing users to control the template content itself [6][65][7][90].
- Restrict Access and Functionality: Minimize the attack surface by limiting access to sensitive objects, modules, and functions that could be exploited for RCE [37][12][6][90].
- Implement Whitelisting: Instead of blacklisting dangerous characters or keywords (which are often bypassable), implement whitelisting of allowed characters, inputs, or template structures [38][60][33].
- Keep Dependencies Updated: Regularly update template engine libraries and other application dependencies to patch known SSTI vulnerabilities [3][6][67][80].
- Web Application Firewalls (WAFs): While not a primary defense, WAFs can help detect and block common SSTI payloads as an additional layer of security [6][14].
Recent Developments
The landscape of SSTI is constantly evolving, with new techniques and vulnerabilities being discovered. Recent trends highlight a focus on bypassing sophisticated defenses and exploiting less common template engines or specific framework integrations.
1. Advanced Sandbox Escapes and Filter Bypasses
Attackers continue to develop sophisticated methods to bypass security sandboxes and filters designed to prevent code execution. This includes:
- Exploiting Weak Regex or Sanitization: Vulnerabilities like CVE-2025-66294 in Grav CMS demonstrate how weak regular expressions can fail to sanitize nested template calls, allowing bypasses [36][38].
- Utilizing Uncommon Built-ins: Discovering and chaining less obvious built-in functions or objects within template engines to achieve execution, even when common methods are blocked [24][44][21][60][80][31][87][26].
- Encoding and Obfuscation: Employing character encoding (e.g., hex encoding, ASCII representations via
lower_abc) or string manipulation to obfuscate malicious payloads and evade detection [44][60][80][31][43][87][26]. - Method Confusion: In languages like Go, exploiting how methods are called on structs passed into templates can lead to unintended execution or file access [74][75][76].
- AST Injection: In JavaScript environments, manipulating the Abstract Syntax Tree (AST) via prototype pollution can lead to code execution in template engines like Handlebars and Pug [94].
2. Exploitation in Specific Frameworks and Applications
Numerous recent CVEs and research papers highlight SSTI vulnerabilities within specific applications and frameworks:
- Jinja2/Flask: Continued research into Jinja2 filter bypasses and payload size limitations for RCE in Flask applications [47][60][39][69][32][80][81][33][31][30][26].
- Twig/PHP: Exploitation in PHP frameworks like Symfony and CMSs like Grav and Craft CMS [34][36][37][38][95][82][41][83][87][17][16].
- FreeMarker/Java: SSTI in enterprise applications like Apache StreamPark and OpenMetadata, often involving sandbox bypasses [71][76][84][42][85][86][43][15].
- Thymeleaf/Java: Exploits in Spring Boot applications, particularly leveraging specific expression evaluation contexts or sandbox weaknesses [35][67][40][72][73].
- Go: Research into SSTI in Go applications, focusing on exploiting method calls and built-in template functionalities [57][74][75][76].
- ServiceNow: Multiple critical SSTI vulnerabilities (CVE-2024-4879, CVE-2024-5217) involving Jelly template injection leading to RCE [77][78][79].
- Other Engines: Exploitation in less common or specialized engines like Smarty [24], ERB [52][53][55][23][14][8], Handlebars [96][68][19][15], and custom or proprietary templating systems [25][93][95].
3. Supply Chain and CI/CD Risks
SSTI is not limited to traditional web applications. It can also manifest in CI/CD pipelines, configuration management tools (e.g., Helm charts), and automated scripting, posing supply chain risks [45][7]. Malicious code embedded in template files within a build pipeline could lead to execution in developer environments or during software deployment [45].
Where to Go Deeper
For those seeking to deepen their understanding of Server-Side Template Injection, a wealth of resources is available, spanning academic research, practical labs, tooling, and detailed write-ups.
1. Academic and Research Papers
Formal research provides foundational knowledge and often uncovers novel techniques.
- "A Survey of the Overlooked Dangers of Template Engines" (arXiv 2024) [12]: Offers a comprehensive look at RCE risks in template engines and identifies research gaps.
- PortSwigger Research Papers: James Kettle's seminal work, such as "Server-Side Template Injection: RCE for the Modern Web App" [64][16][10], originally presented at Black Hat USA 2015, laid much of the groundwork for SSTI exploitation techniques.
- OWASP Testing Guide: The OWASP Web Security Testing Guide provides structured methodologies for testing SSTI vulnerabilities [17].
2. Comprehensive Online Resources and Write-ups
Community-driven platforms and blogs offer practical insights, exploit examples, and exploit chains.
- HackTricks: Features extensive sections on SSTI, covering various engines, detection, exploitation, and bypass techniques [26][9].
- PayloadsAllTheThings: A continuously updated repository of payloads for various vulnerabilities, including a dedicated SSTI section with engine-specific examples [49][53][13][23][22].
- PortSwigger Web Security Academy: Offers free labs specifically designed for practicing SSTI detection and exploitation [61][10].
- CTF Write-ups: Numerous write-ups from Capture The Flag competitions detail practical SSTI findings and exploitation chains in real-world scenarios [24][44][46][36][47][37][38][48][50][18][62][63][69][70][32][80][81][84][42][85][88].
- Security Blogs and Articles: Platforms like Medium, 0xpriv.dev, rcesecurity.com, synack.com, and others regularly publish detailed analyses of SSTI vulnerabilities and new exploitation techniques [1][25][3][97][4][5][21][52][28][98][29][57][58][59][60][39][61][65][7][99][19][14][8][40][72][73][74][75][76][20][79][80][82][31][86][43][87].
3. Exploitation Tools
Automated tools significantly streamline the SSTI hunting process.
- Tplmap: A long-standing and comprehensive tool for detecting and exploiting SSTI vulnerabilities across numerous template engines [11][49][23][14][89][22][17][27].
- SSTImap: A Python 3 alternative to Tplmap, offering an interactive interface and updated payloads [11][49][23][88][22].
- Hackmanit/TInjA: An efficient scanner utilizing novel polyglots for SSTI detection [49][23][22].
4. Hands-on Labs and Training
Practical experience is invaluable. Setting up local labs or participating in curated training environments allows for safe experimentation.
- TryHackMe Labs: Rooms dedicated to SSTI provide hands-on exercises with different template engines [24].
- 0xpriv.dev Lab: A self-hosted lab for practicing SSTI exploitation [1].
- Inj3ctlab: A Bug Bounty Labs offering with multiple SSTI challenges [3].
- TCM Security: Offers courses and labs focused on SSTI exploitation [5].
- GoSecure Workshop: Provides a workshop with multiple Dockerized labs for practicing template injection [82].
- Various Medium Articles: Many blog posts, such as those on 0xpriv.dev, karczewski.io, and medium.com, offer instructions for setting up vulnerable SSTI labs [1][92][29][65][80].
By engaging with these resources, practitioners can develop a deep understanding of SSTI, from fundamental principles to advanced exploitation and bypass techniques.