Start learning free

LESSON 19 OF 56 · SECURITY: INJECTION

Text Is Not a Template in Python

Practice

Flask's template engine, Jinja, reads a template and runs everything between {{ and }}. That is how a slot like {{ customer }} gets filled with a value. It also means that any text glued into the template itself is run as code.

The attack: some pages build their template by gluing in what the visitor typed. Then the name {{ 7 * 7 }} shows up as 49, and {{ config }} prints the app's settings. The attacker gets the app's secret key, so they can sign their own session cookie and act as any user.

# unsafe: the visitor's text becomes part of the template
page = "<p>Thanks, " + customer + "!</p>"
return render_template_string(page)

# safe: a fixed template, the text passed as a value
THANKS = "<p>Thanks, {{ customer }}!</p>"
return render_template_string(THANKS, customer=customer)

A value passed as a keyword argument fills its slot as plain text, escaped like any value, and Jinja never runs it. The gift card page must answer:

GET /gift-card?name=Ana&message=Happy birthday!  →  200  <h1>A gift for Ana</h1><p>Happy birthday!</p>
GET /gift-card?name={{ 7 * 7 }}&message=Hi  →  200  <h1>A gift for {{ 7 * 7 }}</h1><p>Hi</p>
GET /gift-card?name={{ config.SECRET_KEY }}&message=Hi  →  200  <h1>A gift for {{ config.SECRET_KEY }}</h1><p>Hi</p>
GET /gift-card?name={{ config }}  →  200  <h1>A gift for {{ config }}</h1><p></p>
GET /gift-card?name=Ben&message=<b>Thanks</b> for everything  →  200  <h1>A gift for Ben</h1><p>&lt;b&gt;Thanks&lt;/b&gt; for everything</p>

Your task: the starting gift_card reads name and message but returns nothing yet, so it answers 500. Write a fixed template CARD: an <h1> heading with a {{ name }} slot and a <p> paragraph with a {{ message }} slot. Then return it filled with the two values.


Assignment
Follow the Coding Tutorial to write the fixed CARD template and return it with render_template_string, with the name and the message passed as values.


Hint
Write CARD as two strings inside parentheses, one per line: Python joins strings that stand next to each other. Pass each value as a keyword argument named like its slot, such as name=name.


STEP 1 OF 4
    Ctrl + Enter to check

    Secx Template Injection in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free