Cross-site scripting (XSS)

Cross-site scripting (XSS)

Description

template.JS marks a value as trusted JavaScript without validating or escaping it. Converting a script assembled from user input to this type leaves that input in the code.

Potential impact

Scripts running in the page may read sensitive data, change the page, or send requests with the user’s privileges.

Remediation

Pass user input to html/template as an ordinary string. If JavaScript needs the value, render it in a quoted data attribute and read it as data after the element exists.

Examples

Before

go
package main

import (
    "html/template"
    "net/http"
)

// This example demonstrates the vulnerable pattern.

func UnsafeJS(w http.ResponseWriter, r *http.Request) {
    // User input from the id query parameter
    userID := r.URL.Query().Get("id")

    // Vulnerable: concatenate user input directly into HTML/JS
    // Converting to template.JS does not validate or escape the input
    js := "var msg = '<h1>" + userID + "</h1>'; document.write(msg);"

    // ruleid: unescaped-data-in-js
    safeLike := template.JS(js) // The value is still unsafe

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    _, _ = w.Write([]byte("<script>" + string(safeLike) + "</script>"))
}

After

go
package main

import (
    "html/template"
    "net/http"
)

// The template escapes data inserted at {{.UserID}}
var pageTmpl = template.Must(template.New("page").Parse(`
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>Profile</title></head>
<body>
  <h1>User: {{.UserID}}</h1>
  <div id="user" data-userid="{{.UserID}}"></div>
  <script>
    // Pass data through data-* attributes or appropriate JSON encoding
    const userId = document.querySelector('#user').dataset.userid;
    console.log('User:', userId);
  </script>
</body>
</html>
`))

type PageData struct {
    UserID string
}

func SafeJS(w http.ResponseWriter, r *http.Request) {
    userID := r.URL.Query().Get("id")

    // Validate length and allowed characters on the server as needed
    // if !validUserID(userID) { ... }

    data := PageData{UserID: userID}

    w.Header().Set("Content-Type", "text/html; charset=utf-8")
    // html/template escapes values for their output context
    _ = pageTmpl.Execute(w, data)
}

The template escapes UserID for both the heading and the data-userid attribute. JavaScript reads the string through dataset.userid and logs it.

References