Escaping Meta Tag Content? Help

Reviving for the sake of documenting a solution.

In order to disable escaping of HTML entities in a tag, use safeHTMLAttr, as previously suggested. However, the catch is that safeHTMLAttr should be used to mark the complete attribute (name + value), not just the value.

Original:

No escaping:

<meta name="description" {{ .Page.Description | printf "content=%q" | safeHTMLAttr }}>

Bear in mind that whenever you use the safe* functions (safeHTML, safeHTMLAttr, etc), it means you fully trust the input.

A malicious input could infect your website. Given a content file like this:

---
description: "Untrusted page's description. \"><script>alert('hello')</script>"
---

And a template:

<meta name="description" content="{{ .Description }}">
<meta name="description" {{ .Description | printf "content=%q" | safeHTMLAttr }}>

The output is:

<meta name="description" content="Untrusted page&#39;s description. &#34;&gt;&lt;script&gt;alert(&#39;hello&#39;)&lt;/script&gt;">
<meta name="description" content="Untrusted page's description. \"><script>alert('hello')</script>">

Notice that the original form escapes the script tag, and the form with safeHTMLAttr does not, thus outputting JavaScript that is executed on page load.

3 Likes