Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Server-side template injection (SSTI) and its fixes

After this lesson: I can render a template so that what a visitor types stays text.

60 min lesson7 commandsOWASP Juice Shop lab: a vulnerable web shop to attack in your own copy

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

A user name that did sums

Server-side template injection, or SSTI, is when text a visitor typed becomes part of a page template, and the template engine runs it as code. It often gives an attacker the server.

A forum shows "Hello, name" on each profile. Someone sets their name to {{7*7}}. Their profile says "Hello, 49". The forum did the sum, which means it will run other things too.

The one rule

Warning

This lab is a shop that is insecure on purpose. Attack your own private copy and nothing else; it has no way out to the internet. A real system needs the owner's written permission first. Without it, in the UK, this is a crime under the Computer Misuse Act 1990.

By the end of this lesson

Note

I can render a template so that what a visitor types stays text.

Quick check: the rule

Have a go

Quick check: the rule

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Key words

WordWhat it meansExample
Templatea page with gaps the server fills in
Template enginethe library that fills the gapsJinja2, Pug, Twig
Expressioncode inside the gaps that the engine works out{{ 7*7 }}
Contextthe named values passed to the template
SSTItyped text that becomes part of the template itself
Sandboxa mode that limits what template code can reach

The cells students fill in are left blank in this preview.

Starter

Have a go

Starter

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Values in the gaps, never in the template

An engine reads the template, works out the expressions in its gaps, and fills them from the context. That is safe when the visitor's text arrives only in the context, as a value.

It goes wrong when a program builds the template itself by pasting the visitor's text into it, then hands it to the engine. Now the visitor writes part of the template, and the engine runs their expressions.

A careless engine

Code: python
def render(template, values):
    # A careless engine: it runs whatever sits between {{ and }}.
    while "{{" in template:
        start = template.index("{{")
        end = template.index("}}", start)
        result = eval(template[start + 2:end], {}, values)
        template = template[:start] + str(result) + template[end + 2:]
    return template


# Change name to "{{ 7*7 }}" and press Run.
name = "Sam"
page = "Hello " + name + ", you have {{ points }} points"
print(render(page, {"points": 12}))

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Worked example: one probe, several engines

Typed textEngines that work it outWhat the page shows if vulnerable
{{7*7}}Jinja2, Twig, Nunjucks49
${7*7}FreeMarker, Thymeleaf expressions49
#{7*7}Pug, Ruby string interpolation49
<%= 7*7 %>ERB, EJS49

The cells students fill in are left blank in this preview.

Read the flaw in your shop

Your lab runs Juice Shop, whose profile page uses the Pug engine. Start the lab, make an account and sign in with the first two Runs. The next two print lines of the profile page's code. The fifth asks the shop whether its SSTi challenge is on. The last two set your user name to a Pug expression and read back what the page shows.

Make an account in your copy

Command
curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"lab-pass-1","passwordRepeat":"lab-pass-1","securityQuestion":{"id":1},"securityAnswer":"blue"}' http://juice-shop:3000/api/Users | grep -o '"status":"[a-z]*"'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Sign in and keep the token

Command
J=$(curl -s -H "Content-Type: application/json" -d '{"email":"[email protected]","password":"lab-pass-1"}' http://juice-shop:3000/rest/user/login | sed -n 's/.*"token":"\([^"]*\)".*/\1/p'); echo ${#J}

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Where the name goes into the template

Command
docker exec juice-shop /nodejs/bin/node -e "require('fs').readFileSync('/juice-shop/build/routes/userProfile.js','utf8').split('\n').forEach((l,i)=>{if(l.includes('_username_'))console.log(i+1,l.trim())})"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What runs a name that looks like code

Command
docker exec juice-shop /nodejs/bin/node -e "require('fs').readFileSync('/juice-shop/build/routes/userProfile.js','utf8').split('\n').forEach((l,i)=>{if(l.includes('eval('))console.log(i+1,l.trim())})"

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Is the SSTi challenge on in a container?

Command
curl -s "http://juice-shop:3000/api/Challenges/?key=sstiChallenge" | grep -o '"disabledEnv":"[A-Za-z]*"'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

Set your user name to an expression

Command
curl -s -b "token=$J" --data-urlencode "username=#{7*7}" -o /dev/null -w "%{http_code}\n" http://juice-shop:3000/profile

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the profile page shows

Command
curl -s -b "token=$J" http://juice-shop:3000/profile | grep -o '>#{7\*7}<\|>49<'

Shown here, not run. Press Start lab to type it into your own lab’s terminal.

What the answers tell you

Line 105 is template = template.replace(/_username_/g, username);: the name pasted into the template. Line 109 pastes #{username} instead, a gap filled from the context. Line 95 is username = eval(code);.

The challenge prints "disabledEnv":"Docker". The check guarding line 105 is off in a container too, so your copy takes line 109. Setting the name prints 302, and the page shows >#{7*7}<: text, not 49.

A common mistake

Warning

Many people think escaping HTML in the name stops template injection. It does not: {{7*7}} has no HTML in it at all, so escaping leaves it alone and the engine still runs it. Keep typed text out of the template entirely and pass it in the context.

The fix: fixed templates and a context

Templates are files written by developers. Never build one from a visitor's text, and never let a visitor choose which template is used.

Pass every value in the context, where the engine treats it as data and escapes it. If users must write their own templates, as in an email tool, use a logic-less engine or the engine's sandbox, and keep its version current.

The same mistake with Python's format

Code: python
SECRET_KEY = "lab-only-4321"


class User:
    def __init__(self, name):
        self.name = name


# A greeting the user may choose. Change it to the line in the comment and press Run.
# greeting = "Hi {user.__init__.__globals__[SECRET_KEY]}"
greeting = "Hi {user.name}"
print(greeting.format(user=User("Sam")))

Make a free account to save your work and track your progress.

Check

Have a go

Check

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

How to detect template injection

Search request logs for template markers in fields that should hold names or text: {{, ${, #{, <%, {%. A probe such as 7*7 beside them is a strong sign of someone testing.

On the server, alert on template errors, which probes often cause, and on a web process starting a shell. In code review, flag every place a template is built by joining strings.

Assignment: a safe template renderer

Write two functions. render(template, values) fills each {{ name }} in the template, with or without spaces, from the dictionary values, escaped with html.escape. A gap whose inside is not a plain name, or a name not in values, becomes empty. Never evaluate anything, and never fill in gaps that appear inside a value. suspicious(text) returns True if the text holds any of the markers in MARKERS, and False otherwise.

Code: python
import html

MARKERS = ["{{", "{%", "${", "<%", "#{"]


def render(template, values):
    # Fill each {{ name }} from values, escaped. An unknown name or an expression gives "".
    # Never evaluate anything.
    return template


def suspicious(text):
    # True if the text holds any of the MARKERS.
    return False

Make a free account to save your work and track your progress.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.