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 questionsKey words
| Word | What it means | Example |
|---|---|---|
| Template | a page with gaps the server fills in | |
| Template engine | the library that fills the gaps | Jinja2, Pug, Twig |
| Expression | code inside the gaps that the engine works out | {{ 7*7 }} |
| Context | the named values passed to the template | |
| SSTI | typed text that becomes part of the template itself | |
| Sandbox | a 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 questionsValues 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
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 questionsWorked example: one probe, several engines
| Typed text | Engines that work it out | What the page shows if vulnerable |
|---|---|---|
| {{7*7}} | Jinja2, Twig, Nunjucks | 49 |
| ${7*7} | FreeMarker, Thymeleaf expressions | 49 |
| #{7*7} | Pug, Ruby string interpolation | 49 |
| <%= 7*7 %> | ERB, EJS | 49 |
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
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
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
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
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?
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
curl -s -b "token=$J" --data-urlencode "username=#{7*7}" -o /dev/null -w "%{http_code}\n" http://juice-shop:3000/profileShown here, not run. Press Start lab to type it into your own lab’s terminal.
What the profile page shows
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
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 questionsHow 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.
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