SSTI (Server-Side Template Injection) is a vulnerability where user input is embedded into a server-side template and then evaluated, so an attacker injects template syntax that the engine executes. Because template engines can reach language objects and functions, SSTI frequently escalates to remote code execution. It is caused by concatenating untrusted input into a template instead of passing it as data, and the fix is to keep user input strictly as rendered data, never template source.
What SSTI is
Template engines (Jinja2, Twig, Freemarker, Velocity, and others) turn templates plus data into output. The safe pattern passes user input as data to a fixed template.
SSTI occurs when an application builds the template from user input, for example string-concatenating a name into the template source. The engine then evaluates the attacker’s input as template code, which can read variables, call functions, and on many engines reach the underlying language runtime.
How it works and example
The classic probe is a math expression that only a template engine would evaluate:
- Send
{{7*7}}. If the response contains49, the input is being evaluated as a template (the hallmark SSTI test). - Identify the engine, then escalate. On Jinja2, attackers walk Python objects to reach OS commands, for example via
{{ ''.__class__... }}gadget chains ending inos.popen("id").read(). - Other engines (Twig, Freemarker) have their own gadgets to reach code execution.
Examples shown for defensive context.
How to fix it
- Never build templates from user input. Pass user data as context variables to a static template, so it is rendered as data, not code.
- Use logic-less or sandboxed templates where user-supplied templates are unavoidable, and keep the sandbox patched.
- Avoid letting users supply template content at all.
- Validate and contextually encode output.
- Test any feature that renders user-influenced content through a template engine.
References
- [1]OWASP Web Security Testing Guide(OWASP)
- [2]MITRE CWE-1336: Improper Neutralization of Special Elements Used in a Template Engine(MITRE CWE)
- [3]OWASP Top 10(OWASP)