Golang HTMLTemplates

XSS is a common security problem in web-applications. It is an extremely common bug and, hopefully, is becoming less common.

Golang contains the HTMLTemplate package as it's mechanism for XSS prevention and serving dynamic html content.

Here's an example of how it works. The following program will print "AA" to stdout.

t.html

<html>
<head>
</head>
<body>
{{.}}
</body>
</html>

t.go

  tmpl, _:= template.ParseFiles("t.html")
  err := tmpl.Execute(os.Stdout, "AA")

This example is pretty boring though, let's see that filtering in action. Let's see what happens when I try to put some script tags into the template. The result of the code is below.

t.go

  tmpl, _:= template.ParseFiles("t.html")
  err := tmpl.Execute(os.Stdout, "<script>alert(1);</script>")

Result

&lt script &gt alert(1); &lt /script &gt

Not bad. Let's up the ante and output things directly into a script tag. Below is part of our new template, code, and the important part of the result.

t.html

<body>
<script>
{{.}}
</script>
</body>

t.go

  tmpl, _:= template.ParseFiles("t.html")
  err := tmpl.Execute(os.Stdout, "alert(1);")

Result


<script>
"alert(1);"
</script>

Nice. Not completely unexpected. Let's bring out the big guns where we use some less obvious XSS vectors.

t.html

<body>
<img src={{.}}/>
</body>

t.go

  tmpl, _:= template.ParseFiles("t.html")
  err := tmpl.Execute(os.Stdout, "alert(1);")

Result


<body>
<img src=#ZgotmplZ/>
</body>

This is pretty unexpected if you haven't read the docs. When the HTMLTemplate is used in a really unsafe way ZgotmplZ will be the output.

If you would like to see the and run the tests used when building this package, check out the source

ejj, March 2015