Course contentsShow
← Software Engineering
Lesson 1059 of 1,93332. Security EngineeringFree lesson

Template and Expression Injection

Risks of server-side template injection and unsafe expression evaluation in template engines and DSLs.

Template and Expression Injection

What You'll Learn

You'll learn how attackers can exploit template engines and expression languages to execute arbitrary code when user input is unsafely embedded into templates.

The Core Risk

Modern web frameworks often use template engines (like Jinja2, Thymeleaf, or Handlebars) to dynamically generate HTML, or expression languages (like Spring Expression Language or OGNL) to evaluate dynamic values. When user input is directly inserted into templates or expressions before they're rendered, attackers can inject malicious template syntax that the engine will execute—potentially running arbitrary code on your server.

Think of it like this: if SQL injection tricks a database into running attacker commands, template injection tricks your rendering engine into executing attacker code.

Example Scenario

Imagine a greeting page that renders: "Hello {{username}}". If username comes from user input and is placed directly into the template string itself:

# DANGEROUS - user input in template source
template_string = "Hello " + user_input
template.render(template_string)

An attacker could submit: {{7*7}} or {{system('rm -rf /')}} (depending on the engine). The template engine sees this as valid syntax and evaluates it—executing code server-side.

Safe Practice

User data should only be passed as context variables, not concatenated into template source:

# SAFE - user input as data only
template = load_template("greeting.html")
template.render({"username": user_input})

The template itself remains trusted code; user input is treated as plain data to display, not instructions to execute.

Key Takeaway:
Never construct template source code from user input. Always pass user data as context variables to pre-defined templates, keeping the template logic separate from untrusted data to prevent server-side code execution.