Description
template.HTMLAttr treats a whole string as a trusted HTML attribute. If you build that string from user input, the browser may interpret part of the value as another attribute.
Potential impact
Scripts running in the page may change its content, read data available to it, or send requests with the user’s privileges.
Remediation
Fix the attribute name and structure in the template. Restrict values to the expected format, then pass them to html/template as ordinary strings for context-aware handling.
Examples
Before
package main
import (
"html/template"
"net/http"
)
func unsafeHandler(w http.ResponseWriter, r *http.Request) {
// Read user input from the query parameter
color := r.URL.Query().Get("color") // Expected input, e.g. "red"
// Unsafe: concatenate user input into an HTML attribute
// Attack example: color="red" onclick="alert(1)"
attr := "style=\"color:" + color + "\""
// template.HTMLAttr does not escape the value
safeAttr := template.HTMLAttr(attr)
// Use attr directly in the template
t := template.Must(template.New("page").Parse(`
<html><body>
<p {{.}}>Hello</p>
</body></html>`))
// Injected attributes may execute code in the browser
_ = t.Execute(w, safeAttr)
}
After
package main
import (
"html/template"
"net/http"
"regexp"
)
var pageTmpl = template.Must(template.New("page").Parse(`
<html><body>
<p style="color:{{.Color}}">Hello</p>
</body></html>`))
// Limit characters and length; this does not validate CSS color names
var colorRe = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,20}$`)
func safeHandler(w http.ResponseWriter, r *http.Request) {
color := r.URL.Query().Get("color")
if !colorRe.MatchString(color) {
// Use the default when validation fails
color = "black"
}
// Pass an ordinary string to html/template
// The template escapes it for the output context
data := struct {
Color string
}{Color: color}
if err := pageTmpl.Execute(w, data); err != nil {
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
}
The template fixes the style attribute and the color property, leaving only Color as a CSS value. The regular expression checks allowed characters and a length of 1–20, with black as the fallback. To accept only valid color names, use a list of permitted colors.