Avoid XSS in Template Toolkit

· Read in about 2 min · (233 Words)
perl xss template

Template Toolkit is an excellent and popular templating language for perl.

Here’s a quick tip about how to avoid cross-site scripting vulnerabilities when using it to write web apps.

Suppose you have a page in your app which takes some user input and displays it, like this:

<input name="user_supplied_input" value='[% input | html %]'>

The input could come from POSTing a form, or from a URL parameter, like:


You could be forgiven for thinking that because you’ve used the HTML filter your user supplied input will be safely encoded, but in this case you’d be wrong!

Generally, I find that Template Toolkit follows the principle of least astonishment, but read this snippet of the docs closely, and you might spot the issue:

Converts the characters <, >, & and " to &lt;, &gt;,&amp;, and &quot;
respectively, protecting them from being interpreted as representing HTML
tags or entities.

That’s right, it doesn’t encode single quote characters! That means that all a malicious user need do to perform a cross-site scripting attack is escape out of the attribute using a single quote, and inject whatever they want.

One contrived example might be this:


But a real attacker would obviously take the time to create a more awesome payload, or just use something like BeEF.

To avoid this, just make sure you use double quotes in HTML tags when building apps with Template Toolkit.