Course contentsShow
← Security
Lesson 1245 of 3,05225. Application Security - Secure CodingFree lesson

Template Engine Injection Fundamentals

Understanding how template engines process user input and the risks of server-side template injection (SSTI).

Template Engine Injection Fundamentals

What you'll learn: How template engines can become dangerous when they process untrusted user input directly.


What Are Template Engines?

Template engines are tools that combine static templates with dynamic data to generate output—usually HTML for web pages. They let you write something like Hello, {{username}}! and the engine replaces {{username}} with the actual user's name.

Common examples include Jinja2 (Python), Twig (PHP), FreeMarker (Java), and Handlebars (JavaScript).

The Injection Risk: Server-Side Template Injection (SSTI)

The danger arises when your application directly embeds user input into a template string before processing it, rather than passing user data as safe variables.

Safe Pattern

# User input passed as DATA
template = "Hello, {{name}}!"
render(template, {"name": user_input})  # SAFE

Dangerous Pattern

# User input becomes part of the TEMPLATE itself
template = "Hello, " + user_input + "!"
render(template, {})  # DANGEROUS

Why This Matters

Template engines are powerful. They often include features to:

  • Execute arbitrary code
  • Access server-side objects and functions
  • Read files or environment variables

If an attacker can inject template syntax (like {{7*7}} or {{system('whoami')}}), they're not just breaking output encoding—they're executing code on your server. This is similar to how SQL injection lets attackers run database commands, but SSTI lets them run server commands.


Key Takeaway: Server-Side Template Injection occurs when user input is treated as template code rather than safe data, potentially allowing attackers to execute arbitrary code on the server through the template engine's powerful expression language.