The Risk
Template engines turn templates plus data into output such as HTML or email. They are powerful because the template language can evaluate expressions. Server Side Template Injection, or SSTI, happens when user input is placed into the template itself rather than passed in as data. The engine then evaluates attacker supplied expressions, which can read internal objects and in many engines lead to code execution.
The flaw is treating untrusted input as template source instead of as a value to be displayed.
The Defense
- Never concatenate user input into a template string. Keep templates static and pass user values through the data context.
- Use automatic output escaping so values render as text, not markup.
- Avoid features that evaluate arbitrary expressions on user controlled fields.
- If users must supply templates, use a sandboxed engine with a tiny logic free dialect.
Key idea
Keep templates static and supply user input only as bound data, so the engine displays it as text and never evaluates it as expressions.